text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
Symfony 4: Monolith vs Micro This is the second installment in a series of articles about Symfony 4. The first one was about the current limitations of the Symfony Distribution model.. This meta-package contains all the Symfony components and some "core" bundles. Among other features, you get Twig and the Web Profiler. But technically, you don't need them if you are developing an API for your next mobile application. Of course, some extra files under vendor/ don't change anything, but some developers think that their applications are more "bloated" because of those extra bits on their disk. It feels like those extra unused features make your application fat. This is mostly about perception though. Silex took another approach where each individual components are required when needed. Does it make Silex simpler, more lightweight, or faster than Symfony? No. Nevertheless, Symfony 4 is going to be more similar to Silex in this regard. Symfony Applications go minimal Out is the dependency on symfony/symfony. A Symfony application will now depend on the individual Symfony components and bundles. This is probably the most significant change in the way you will develop applications with Symfony 4. The main reason is not because it helps reducing the number of files under vendor/ though. It opens up many great opportunities. It helps with auto-configuration, one major Symfony 4 feature. When installing a bundle, Symfony will now configure it automatically with good defaults. Configuration also adapts according to your other dependencies. Take the Symfony Framework Bundle as an example. Some features can be enabled or disabled, like form, validation, templating, serializer, assets, … As of Symfony 3.2, form support is enabled by default, but you can disable it if you are not using it in your application. Why is it enabled by default? Because there is no way for Symfony to know if you will use forms in your application. Disabling it by default would lead to a slightly worse developer experience as that’s one configuration knob to tweak before your first form works. Now, imagine an application where symfony/symfony is not a dependency. An application can start with just symfony/framework-bundle. Automatically enabling form support is now trivial: enable it when symfony/form is installed, disable it otherwise. Simple, no magic, no configuration, great developer experience. You will love Symfony 4. As a great side-effect, performance is better as optional features are automatically disabled. Without any tweaks in configuration files. I will share some simple benchmarks in another post. Going minimal also means that Symfony does not try to make assumptions anymore about your stack. Besides the removal of the LICENSE or README files in the skeleton, there is no Apache .htaccess files anymore. What if you are using Apache then? Well, you will have to wait for another post to get the answer, but I got you covered. Composition Removing the dependency on symfony/symfony helps with another Symfony 4 feature: auto-discovery and dependency removals. I mentioned composition yesterday. Symfony 4 will lever those smaller dependencies to help you compose your applications. Want to use forms? Require symfony/form. Want to use the PHP built-in server? Require symfony/web-server-bundle. Progressive enhancement. Add dependencies only when needed. Coupled with auto-configuration, it is very powerful. Don’t need the built-in web server anymore? Remove the symfony/web-server-bundle package. Symfony takes care of un-configuring the bundle. This is a very simple example, but there is more. Let’s illustrate the power of this new paradigm with SensioDistributionBundle, a bundle required by default in Symfony Standard Edition. Don’t you think that requirement checks are currently weirdly implemented? Files are copied from the bundle to the Standard Edition on release. You are responsible for removing them before deploying (especially web/config.php). The whole logic has been moved to symfony/requirements-checker. Want to check requirements? Add the package with Composer. Run the scripts. Fix any issues. Uninstall the package when done. Files are added and removed automatically. The other main feature of SensioDistributionBundle is to execute some commands when you run composer install or composer update: they manage the bootstrap file (which is not needed anymore as of PHP 7), clear the cache, and install assets. Feels like hardcoded logic (have a look at the Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::* call in your project's composer.json file). I reworked the concept for Symfony 4 in an extensible way. You can hook into it and add your own commands and logic. There won’t be a SensioDistributionBundle version compatible with Symfony 4. We don’t need one. You can think of Symfony Flex as being the successor of it. A simpler and more powerful version of it. Bundle-less Applications When we wrote the first version of the Symfony best practices, we had a long debate about promoting “one bundle applications” vs “bundle-less applications”. We decided to go with a single AppBundle bundle to avoid a too-big disruption, but also because Symfony was not ready to support bundle-less applications as a first class citizens. But we worked hard during the last few months to make sure that Symfony 4 can embrace bundle-less applications. So Symfony 4 will recommend and generate bundle-less applications. No more bundle for your code, just use App\ as a namespace for any class under src/. It reduces the perceived complexity. It also makes your code feels more decoupled from Symfony. I don't think applications should decouple 100% of its code from the underlying framework, but as of Symfony 3.3, a lot of features help you just do that. Bundle-less applications is just one of the best practices changes for Symfony 4. Best practices is the topic for the next post. Originally published at fabien.potencier.org.
https://medium.com/@fabpot/symfony-4-monolith-vs-micro-52dc6b98c0c5
CC-MAIN-2019-18
en
refinedweb
The main goal of this project is to provide a code generator for serializing/deserializing C++ objects to/from JSON using Clang and RapidJSON. Extending the generator to generate code for other formats or other applications of reflection is possible as well. A serializer/deserializer for a platform independent binary format has already been implemented. It would also be possible to extend the library/generator to provide generic reflection (not implemented yet). The following documentation focuses on the JSON (de)serializer. However, most of it is also true for the mentioned binary (de)serializer which works quite similar. The reflection implementation used behind the scenes of this library is exchangeable: BOOST_HANA_DEFINE_STRUCTmacro rather than requiring the code generator. The basic functionality is implemented, tested and documented: There are still things missing which would likely be very useful in practise. The following list contains the open TODOs which are supposed to be most relevant in practise: For a full list of further ideas, see TODOs.md. The following table shows the mapping of supported C++ types to supported JSON types: const char *strings are only supported for serialization. null. std::shared_ptrinstance might point to the same object this object is serialized multiple times. When deserializing those identical objects, it is currently not possible to share the memory (again). So each std::shared_ptrwill point to its own copy. Note that this limitation is not true when using binary serialization. emplace_backmethod. So deserialization of eg. std::forward_listis currently not supported. REFLECTIVE_RAPIDJSON_TREAT_AS_MAP_OR_HASH, REFLECTIVE_RAPIDJSON_TREAT_AS_MULTI_MAP_OR_HASH, REFLECTIVE_RAPIDJSON_TREAT_AS_SETor REFLECTIVE_RAPIDJSON_TREAT_AS_MULTI_SET. std::map, std::unordered_mapmust be std::string. This example shows how the library can be used to make a struct serializable: #include <reflective_rapidjson/json/serializable.h> // define structures, eg. struct TestObject : public ReflectiveRapidJSON::JsonSerializable<TestObject> { int number; double number2; vector<int> numbers; string text; bool boolean; }; struct NestingObject : public ReflectiveRapidJSON::JsonSerializable<NestingObject> { string name; TestObject testObj; }; struct NestingArray : public ReflectiveRapidJSON::JsonSerializable<NestingArray> { string name; vector<TestObject> testObjects; }; // serialize to JSON NestingArray obj{ ... }; cout << "JSON: " << obj.toJson().GetString(); // deserialize from JSON const auto obj = NestingArray::fromJson(...); // in exactly one of the project's translation units #include "reflection/code-defining-structs.h" Note that the header included at the bottom must be generated by invoking the code generator appropriately, eg.: reflective_rapidjson_generator \ --input-file "$srcdir/code-defining-structs.cpp" \ --output-file "$builddir/reflection/code-defining-structs.h" There are further arguments available, see: reflective_rapidjson_generator --help It works very similar to the example above. Just use the BinarySerializable class instead (or in addition): #include <reflective_rapidjson/binary/serializable.h> struct TestObject : public ReflectiveRapidJSON::BinarySerializable<TestObject> It is possible to use the provided CMake macro to automate the code generator invocation: # find the package and make macro available find_package(reflective-rapidjson REQUIRED) list(APPEND CMAKE_MODULE_PATH ${REFLECTIVE_RAPIDJSON_MODULE_DIRS}) include(ReflectionGenerator) # "link" against reflective_rapidjson # it is a header-only lib so this will only add the required include paths # to your target target_link_libraries(mytarget PRIVATE reflective_rapidjson) # invoke macro add_reflection_generator_invocation( INPUT_FILES code-defining-structs.cpp GENERATORS json OUTPUT_LISTS LIST_OF_GENERATED_HEADERS CLANG_OPTIONS_FROM_TARGETS mytarget ) This will produce the file code-defining-structs.h in the directory reflection in the current build directory. So make sure the current build directory is added to the include directories of your target. The default output directory can also be overridden by passing OUTPUT_DIRECTORY custom/directory to the arguments. It is possible to specify multiple input files at once. A separate output file is generated for each input. The output files will always have the extension .h, independently of the extension of the input file. The full paths of the generated files are also appended to the variable LIST_OF_GENERATED_HEADERS which then can be added to the sources of your target. Of course this can be skipped if not required/wanted. The macro will also automatically pass Clang's resource directory which is detected by invoking clang -print-resource-dir. To adjust that, just set the cache variable REFLECTION_GENERATOR_CLANG_RESOURCE_DIR before including the module. For an explanation of the CLANG_OPTIONS_FROM_TARGETS argument, read the next section. It is possible to pass additional options to the Clang tool invocation used by the code generator. This can be done using the --clang-opt argument or the CLANG_OPTIONS argument when using the CMake macro. For example, additional definitions could be added using --clang-opt -DSOME_DEFINE -DANOTHER_DEFINE. But it is actually possible to pass anything from clang --help, including the -X... options. In case you get a massive number of errors, ensure Clang's resource directory can be located. Clang documentation: The default location to look for builtin headers is in a path $(dirname /path/to/tool)/../lib/clang/3.3/includerelative to the tool binary. To adjust the default location, just add eg. --clang-opt -resource-dir /usr/lib/clang/5.0.1 to the arguments. It makes most sense to specify the same options for the code generator as during the actual compilation. This way the code generator uses the same flags, defines and include directories as the compiler and hence behaves like the compiler. When using the CMake macro, it is possible to automatically pass all compile flags, compile definitions and include directories from certain targets to the code generator. Those targets can be specified using the Macro's CLANG_OPTIONS_FROM_TARGETS argument. -DNO_GENERATOR:BOOL=ONto the CMake arguments when building Reflective RapidJSON for the target platform. add_reflection_generator_invocationmacro, you need to set the following CMake cache variables: REFLECTION_GENERATOR_EXECUTABLE:FILEPATH=/path/to/reflective_rapidjson_generator REFLECTION_GENERATOR_TRIPLE:STRING=machine-vendor-operatingsystem examples for cross compiling with mingw-w64 under GNU/Linux: x86_64-w64-mingw32, i686-w64-mingw32 REFLECTION_GENERATOR_INCLUDE_DIRECTORIES:STRING=/custom/prefix/include example for cross compiling with mingw-w64 under GNU/Linux: /usr/lib/gcc/x86_64-w64-mingw32/7.2.1/include;/usr/x86_64-w64-mingw32/include/c++/7.2.1/x86_64-w64-mingw32;/usr/x86_64-w64-mingw32/include mingw-w64variants which give a concrete example how cross-compilation can be done. The same example as above. However, this time Boost.Hana is used - so it doesn't require invoking the generator. #include "<reflective_rapidjson/json/serializable-boosthana.h> // define structures using BOOST_HANA_DEFINE_STRUCT, eg. struct TestObject : public JsonSerializable<TestObject> { BOOST_HANA_DEFINE_STRUCT(TestObject, (int, number), (double, number2), (vector<int>, numbers), (string, text), (bool, boolean) ); }; struct NestingObject : public JsonSerializable<NestingObject> { BOOST_HANA_DEFINE_STRUCT(NestingObject, (string, name), (TestObject, testObj) ); }; struct NestingArray : public JsonSerializable<NestingArray> { BOOST_HANA_DEFINE_STRUCT(NestingArray, (string, name), (vector<TestObject>, testObjects) ); }; // serialize to JSON NestingArray obj{ ... }; cout << "JSON: " << obj.toJson().GetString(); // deserialize from JSON const auto obj = NestingArray::fromJson(...); So beside the BOOST_HANA_DEFINE_STRUCT macro, the usage remains the same. It is obvious that the previously shown examples do not work for classes defined in 3rd party header files as it requires adding an additional base class. To work around this issue, one can use the REFLECTIVE_RAPIDJSON_MAKE_JSON_SERIALIZABLE macro. It will enable the toJson and fromJson methods for the specified class in the ReflectiveRapidJSON::JsonReflector namespace: // somewhere in included header struct ThridPartyStruct { ... }; // somewhere in own header or source file REFLECTIVE_RAPIDJSON_MAKE_JSON_SERIALIZABLE(ThridPartyStruct) // (de)serialization ReflectiveRapidJSON::JsonReflector::toJson(...).GetString(); ReflectiveRapidJSON::JsonReflector::fromJson<ThridPartyStruct>("..."); The code generator will emit the code in the same way as if JsonSerializable was used. By the way, the functions in the ReflectiveRapidJSON::JsonReflector namespace can also be used when inheriting from JsonSerializable (instead of the member functions). By default, private members are not considered for (de)serialization. However, it is possible to enable this by adding friend methods for the helper functions of Reflective RapidJSON. To make things easier, there's a macro provided: struct SomeStruct : public JsonSerializable<SomeStruct> { REFLECTIVE_RAPIDJSON_ENABLE_PRIVATE_MEMBERS(SomeStruct); public: std::string publicMember = "will be (de)serialized anyways"; private: std::string privateMember = "will be (de)serialized with the help of REFLECTIVE_RAPIDJSON_ENABLE_PRIVATE_MEMBERS macro"; }; Sometimes it is appropriate to implement custom (de)serialization. For instance, a custom object representing a time value should likey be serialized as a string rather than an object containing the internal structure. An example for such custom (de)serialization can be found in the file json/reflector-chronoutilities.h. It provides (de)serialization of DateTime and TimeSpan objects from the C++ utilities library mentioned under dependencies. lib/testsand generator/tests. The following diagram gives an overview about the architecture of the code generator and wrapper library around RapidJSON:/> The following dependencies are required at build time. Note that Reflective RapidJSON itself and none of these dependencies are required at runtime by an application which makes use of Reflective RapidJSON. BOOST_HANA_DEFINE_STRUCTinstead of code generator Install all required dependencies. Under a typical GNU/Linux system most of these dependencies can be installed via the package manager. Otherwise follow the links in the "Dependencies" section above. C++ utilities is likely not available as package. However, it is possible to build C++ utilities together with reflective-rapidjson to simplify the build process. The following build script makes use of this. (To use system C++ utilities, just skip any lines with "`c++utilities`" in the following examples.) When installing (some) of the dependencies at custom locations, it is likely neccassary to tell CMake where to find them. If you installed everything using packages provided by the system, you can skip this step of course. To specify custom locations, just set some environment variables before invoking CMake. This can likely be done in your IDE settings and of course at command line. Here is a Bash example: export PATH=$CUSTOM_INSTALL_PREFIX/bin:$PATH export CMAKE_PREFIX_PATH=$CUSTOM_INSTALL_PREFIX:$CMAKE_PREFIX_PATH export CMAKE_LIBRARY_PATH=$CUSTOM_INSTALL_PREFIX/lib:$CMAKE_LIBRARY_PATH export CMAKE_INCLUDE_PATH=$CUSTOM_INSTALL_PREFIX/include:$CMAKE_INCLUDE_PATH There are also a lot of useful variables that can be specified as CMake arguments. It is also possible to create a toolchain file. #### 3. Get sources, eg. using Git: cd $SOURCES git clone c++utilities git clone If you don't want to build the development version, just checkout the desired version tag. Here is an example for building with GNU Make: cd $BUILD_DIR # generate Makefile cmake \ -DCMAKE_BUILD_TYPE:STRING=Release \ -DCMAKE_INSTALL_PREFIX:PATH="/final/install/prefix" \ -DBUNDLED_CPP_UTILITIES_PATH:PATH="$SOURCES/c++utilities" \ "$SOURCES/reflective-rapidjson" # build library and generators make # build and run tests (optional, requires CppUnit) make check # build tests but do not run them (optional, requires CppUnit) make tests # generate API documentation (optional, reqquires Doxygen) make apidoc # install header files, libraries and generator make install DESTDIR="/temporary/install/location" Add eg. -j to make arguments for using all cores. These packages shows the required dependencies and commands to build in a plain way. So they might be useful for making Reflective RapidJSON available under other platforms, too.
https://martchus.no-ip.biz/doc/reflective_rapidjson/?C=N&amp;O=D
CC-MAIN-2019-18
en
refinedweb
From VisTrailsWiki Also check our Known Issues page for troubleshooting. Running workflows How can I run a workflow using the command line? (Updated for version 1.2) Call vistrails using the following options: python vistrails.py -b path_to_vistrails_file:pipeline where pipeline can be a version tag name or version id NOTE: If you downloaded the MacOS X bundle, you can run vistrails from the command line via the following commands in the Terminal. Change the current directory to wherever VisTrails was installed (often /Applications), and then type: Vistrails.app/Contents/MacOS/vistrails [<cmd_line_options>] Running a Specific Workflow in Batch Mode Using the command line, we'd like to execute a workflow multiple times, with slightly different parameters, and create a series of output files. Is this possible? (Updated for version 1.2) We can change parameters that have an alias through the command line. For example, offscreen pipeline in offscreen.vt always creates the file called image.png. If you want generate it with a different filename: python vistrails.py -b ../examples/offscreen.vt (attention to how $ characters are escaped when running on bash): python vistrails.py -b ../examples/head.vt:aliases -a"isovalue=30\$&\$diffuse_color=0.8,0.4,0.2" You can also execute more than one pipeline on the command line: python vistrails.py -b ../examples/head.vt:aliases ../examples/spx.vt:spx \ -a"isovalue=30" Use the -a parameter only once regardless the number of pipelines. Running a Workflow with Specific Parameters. I have a workflow that reads a file and then does some processing. The first time it runs, it executes correctly. But in subsequent, nothing happens. VisTrails caches by default, so after a workflow is executed, if none of its parameters change, it won't be executed again. If a workflow reads a file using the basic module File, VisTrails does check whether the file was modified since the last run. It does so by keeping a signature that is based on the modification time of the file. And if the file was modified, the File module and all downstream modules (the ones which depend on File) will be executed. Note: If you would like your input and output data to be versioned, you can use the Persistence package. If you do not want VisTrails to cache executions, you can turn off caching: go to Menu Edit -> Preferences and in the General Configuration tab, change Cache execution results to Never. Workflow Execution Can VisTrails execute workflows in parallel? The VisTrails server can only execute pipelines in parallel if there's more than one instance of VisTrails running. The command self.rpcserver = ThreadedXMLRPCServer((self.temp_xml_rpc_options.server, self.temp_xml_rpc_options.port)) starts a multithreaded version of the XML-RPC server, so it will create a thread for each request received by the server. The problem is that Qt/PyQT doesn't allow these multiple threads create GUI objects, only in the main thread. To overcome this limitation, the multithreaded version can instantiate other single threaded versions of VisTrails and put them in a queue, so workflow executions and other GUI-related requests, such as generating workflow graphs and history trees can be forwarded to this queue, and each instance takes turns in answering the request. If the results are in the cache, the multithreaded version answers the requests directly. Note that this infrastructure works on Linux only. To make this work on Windows, you have to create a script similar to start_vistrails_xvfb.sh (located in the scripts folder) where you can send the number of other instances via command-line options to VisTrails. The command line options are: python vistrails_server.py -T <ADDRESS> -R <PORT> -O<NUMBER_OF_OTHER_VISTRAILS_INSTANCES> [-M]& If you want the main vistrails instance to be multithreaded, use the -M at the end. After creating this script, update function start_other_instances in vistrails/gui/application_server.py lines 1007-1023 and set the script variable to point to your script. You may also have to change the arguments sent to your script (line 1016: for example, you don't need to set a virtual display). You will need to change the path to the stop_vistrails_server.py script (on line 1026) according to your installation path. Executing Workflows in Parallel When a workflow is executed, what do the colors mean? - lilac: module was notexecuted - yellow: module is currently being executed - green: module was successfully executed - orange: module was cached - red: the execution of the module failed Workflow execution hangs on Windows This can happen if you are using "quick edit mode" in the console and have print statements in your code. Standard output can then get blocked by the console. Pressing space in the console resumes the execution. To avoid this problem, either disable "quick edit mode", or avoid print statements in your code. VisTrails do not install Missing System Packages If VisTrails do not try to install missing system packages it may be because it cannot determine your system type. I that case you can run this (in python) to determine your system type: import platform platform.linux_distribution() And add this system name to gui/bundles/utils.py by, e.g., modifying the _guess_ubuntu method (if your system is apt-based): def _guess_ubuntu(): return platform.linux_distribution()[0]=='Ubuntu' or \ platform.linux_distribution()[0]=='YourSystemName' Cannot update subworkflows after upgrading packages or vistrails version When packages used by a subworkflow is upgraded, any subworkflows that use it will be automatically upgraded. It may then lose the ability to be updated to a newer local subworkflow. In this case the subworkflow needs to be updated by hand by removing it from the pipeline and be dragged in again from the module palette. This may get fixed in a future release. Building workflows Is there a way to give each widget a "display name" in addition to the module name at the center of the widget? Yes, a "display name" can be assigned to a module by selecting the triangle in its top right corner to open a popup menu and selecting the Set Module Label... menu item. You will then be prompted to enter the "display name". Changing Module Labels Is there a way to re-center the picture-in-picture (PiP) view? Yes. If you click on the PIP window to bring it to focus, you can press Ctrl-R (or Command-R on Mac) to re-center the PiP window. Vistrails Interaction How do I search for a literal "?" (question mark) in the search box in the Property panel? Since we allow regular expressions in our search box, question marks are treated as meta-characters. Thus, searching for "?" returns everything and "abc?" will return everything containing "abc". You need to use "\?" instead to search for "?". So the search for "??" would be "\?\?". Textual Queries Saving a vistrail fails when Running VisTrails on Windows inside a Virtual Machine After installing Windows in a Virtual Machine, the path to zip.exe may be missing, and you may see this error when trying to save a vistrail: WindowsError: [Error 2] The system cannot find the file specified: '***/vt.zip' Then you need to add the path to zip.exe, which is included in the binary distribution of VisTrails, to your PATH variable. Using VisTrails as a server What is the VisTrails server-mode? Using the VisTrails server mode, it is possible to execute workflows and control VisTrails through another application. For example, the CrowdLabs Web portal () accesses a VisTrails sever to execute workflows, retrieve and display vistrail trees and workflows. Using VisTrails as a Server How do I execute workflows and control VisTrails through another application? The way you access the server is by doing XML-RPC calls. In the current VisTrails release, we include a set of PHP scripts that can talk to a VisTrails server instance. They are in "extensions/http" folder. The files are reasonably well documented. Also, it should be not difficult to create python scripts to access the server (just use xmlrpclib module). Note that the VisTrails server requires the provenance and workflows to be in a database. More detailed instructions on how to setup the server and the database are available here: If what you want is just to execute a series of workflows in batch mode, a simpler solution would be to use the VisTrails client in batch mode. Chapter 12 of the user's guide contains detailed information and examples on that. Running VisTrails in Batch Mode VisTrails server executes a workflow but generates a blank image and generates the error message cannot get access to X server You will need to check if the display the server is trying to use is a valid display (by default it uses the display 0). On linux, the command w will list the logged users and the display associated with them (FROM column). Note that the VisTrails server requires the machine to be running X. cannot get access to X server Running VisTrails in server or batch mode requires a connection to an X server. No additional setup is required if you run VisTrails on a terminal because you are already logged in to X. To make it work in other scenarios, you need to run the python command through Xvfb or make sure you can run cgi scripts that access the GUI. If you can run Xvfb, you can use the following script, where you need toconfigure the first four variables according to your system: (To run the script, rename the file and remove the ".txt") You should also modify yout cgi script to invoke the bash script instead of vistrails directly. The bash script will accept the virtual display, the vistrail file and workflow tag as input arguments. Another possibility is if your workflow does not require the GUI, you can use VisTrails as a regular python module and it will not require the GUI or X Server to run. This functionality is available in the nightly builds and will be included in VisTrails 2.0 beta to be released soon. There is an example of how to use this feature in our FAQ: Problems starting VisTrails Setup was unable to create the directory "N:\.vistrails" When VisTrails is installing, it tries to create the .vistrails folder in the users %HOMEPATH% directory. In some Windows installations, network accounts are set to a directory that a user does not have write access to. Consequently, the installation will fail. To get around this problem, you can use the "-S <directory>" flag when starting VisTrails. This option allows you to put the .vistrails directory wherever you wish. You could also write a short script that automatically invokes VisTrails with the "-S" flag pointing to a directory that makes sense to your network. If you are unable to install VisTrails, you can run the installer after setting a new home path from the command line like this: set HOMEPATH=\My\New\Home\ set HOMEDRIVE=C: vistrails-setup-2.0.1-xxx.exe Using VisTrails as a Python module Can I use VisTrails as a Python module without installing PyQt? Yes! We have improved the ability to use VisTrails from other software, and have eliminated most GUI (PyQt) dependencies in the core part of the code. Thus, you can now work with workflow versions and provenance information in a standard python shell. Note packages that directly rely on the GUI like the VisTrails Spreadsheet will still require PyQt to be installed. How do I open and execute workflows in a standard python shell? Here is a simple example that shows how you can open and execute a workflow from a Python script: >>> import vistrails as vt >>> >>> vistrail = vt.load_vistrail('simplemath.vt') >>> vistrail.select_latest_version() >>> result = vistrail.execute(in_a=2, in_b=4) >>> result.output_port('out_plus') 6.0 A more complete example is available in the VisTrails distribution as examples/api/ipython-notebook.ipynb Control Flow Note: using map When using 'map', the module (or subworkflow) used as function port in the map module MUST be a function, i.e., it can only define 1 output port. The Map Operator Spreadsheet Where pipeline is a version number or a tag. How can I save an image from the spreadsheet? While having the focus on a spreadsheet cell and select the camera on the toolbar to take a snapshot. The system will prompt you for the location and file name where it should be saved. The other icons can be used for saving multiple images that can be used for generating an animation on demand. A whole sheet can also be saved by selecting Export (either from the menu or from the toolbar). Saving a Spreadsheet Image Is it possible to save the complete state of the spreadsheet? Can I view multiple sheets at the same time? Yes. Each sheet on the spreadsheet can be displayed as a dock widget separated from the main spreadsheet window by dragging its tab name out of the tab bar at the bottom of the spreadsheet. Multiple Spreadsheets Then, how can I put back a separated sheet? A sheet can be docked back to the main window by dragging it back to the tab bar or double-click on its title bar. Multiple Spreadsheets How can I order sheets on the spreadsheet? This can be done by dragging the sheet name on the bottom top bar and drop it to the right place. Multiple Spreadsheets). Sending Output to the Spreadsheet How do I output results to the spreadsheet? By inspecting the VisTrails Spreadsheet package (in the list of packages, to the left of the pipeline builder), you can see there are built-in cells for different kinds of data, e.g., RichTextCell to display HTML and plain text. op You (the user) can also define new cell types to display application-specific data. For example, we have developed VtkCell, MplFigureCell, and OpenGLCell. It is possible to display pretty much anything on the Spreadsheet! Sending Output to the Spreadsheet Examples of writing cell modules can be found in: RichTextCell: packages/spreadsheet/widgets/richtext/richtext.py VTK: packages/vtk/vtkcell.py Here is the summary of some requirements on a cell widget: (1) It must be a Qt widget. It should inherit from spreadsheet_cell.QCellWidget in the spreadsheet package. Although any Qt Widget would work, certain features such as animation will not be available (without rewriting it). (2) It must re-implement the updateContents() function to take a set of inputs (usually coming from input ports of a wrapper Module) and display on the cells. VisTrails uses this function to update/reuse cells on the spreadsheet when new data comes in. (3) It needs a wrapper VisTrails Module (inherited from basic_widgets.SpreadsheetCell of the spreadsheet package). Inside the compute() method of this module, it may call self.display(CellWidgetType, (inputs)) to trigger the display event on the spreadsheet. Advanced Cell Options How do I control the default number of cells in the spreadsheet? You can configure the rowCount and colCount using the preferences dialog. Just go to the Module Packages tab, select spreadsheet in the "Enabled packages" and press the Configure button. Then a list of all the configuration options for the spreadsheet will show up. Custom Layout Options Is it possible to launch a web browser from the vistrails spreadsheet? We would like to output several urls from a parameter sweep and then have the option to click on each one to view the resulting page. I can view the page within the spreadsheet, but it is really too crowded. Currently, there isn't a widget that provides exactly this functionality, but I can think of a few solutions that may work for you: (1) You can use parameter exploration to generate multiple sheets so you might have an exploration that opens each page in a new sheet. Use the third column/dimension in the exploration interface to have a parameter span sheets. (2) The spreadsheet is extensible so you can write a custom spreadsheet cell widget that has a button or label with the desired link (a QLabel with openExternalLinks set to True, for example). (3) You can tweak the existing RichTextCell be adding the line "self.browser.setOpenExternalLinks(True)" at line 63 of the source file "vistrails/packages/spreadsheet/widgets/richtext/richtext.py". Then, if your workflow creates a file with html markup text like "<a href="">VisTrails</a>" connected to a RichTextCell, clicking on the rendered link in the cell will open it in a web browser. You need to add the aforementioned line to the source to let Qt know that you want the link opened externally; by default, it will just issue an event that isn't processed. Launching a Web Browser Integrating your software into VisTrails How can I integrate my own program into VisTrails? The easiest way is to create a package. Writing a package is often very simple; please refer to this section of the users' guide. You can also dynamically generate modules. For an example see: Generating Modules Dynamically In particular, see the new_module call which uses python's type() function to generate new classes dynamically. How do I add a port that is not visible on the module (when it appears on the design canvas)? This can be accomplished via the "optional" argument. This is the fourth argument of add_input_port (add_output_port) or can be specified as a kwarg. In your example, this would look like: reg.add_input_port(MyModule, "MyPort", (core.modules.basic_modules.String, 'MyPort Name'), True) or with kwargs reg.add_input_port(MyModule, "MyPort", (core.modules.basic_modules.String, 'MyPort Name'),\ optional=True) or _input_ports = [('MyPort', '(core.modules.basic_modules.String)', {"optional": True})] spreadsheet package uses this feature, so look there for usage examples (vistrails/packages/spreadsheet/basic_widgets.py) Configuring Ports Are there mechanisms for attaching widgets to different modules/parameters? Right now, we have a mechanism for putting a specific widget for an input port. For example, if a port is SetColor(red, green, blue), we can put a color wheel widget there. Or we can also replace the SetFileName port with a File Widget. However, this is not per parameter (only per port). We are currently working on this problem. Can I organize my package so it appears hierarchical in the module palette? Yes. Use the namespace keyword argument when adding the module to the registry. For example, registry.add_module(MyModule, namespace='MyNamespace') Configuring Modules - Hierarchy and Visibility Can I nest namespaces? Yes. Use the '|' character to separate different the hierarchy. For example, registry.add_module(MyModule, namespace='ParentNamespace|ChildNamespace') Configuring Modules - Hierarchy and Visibility Are there shortcuts for registry initialization? Yes. If you define _modules as a list of classes in the __init__.py file of your package, VisTrails will attempt to load all classes specified as modules. You can provide add_module options as keyword arguments by specifying a tuple (class, kwargs) in the list. For example: _modules = [MyModule1, (MyModule2, {'namespace': 'MyNamespace'})] In addition, you need to identify the ports of your modules as a field in your class by defining _input_ports and _output_ports lists. Here, the items in each list must be tuples of the form (portName, portSignature, optional=False, sort_key=-1). For example: class MyModule(Module): def compute(self): pass _input_ports = [('firstInput', String), ('secondInput', Integer, True)] _output_ports = [('firstOutput', String), ('secondOutput', String)] Customizing Modules and Ports Can I define ports to be of types that I do not import into my package? Yes. You can pass an identifier string as the portSignature instead. The port_signature string is defined by: <module_string> := <package_identifier>:[<namespace>|]<module_name>, <port_signature> := (<module_string>*) For example, registry.add_input_port(MyModule, 'myInputPort', '(edu.utah.sci.vistrails.basic:String)') or _input_ports = [('myInputPort', '(edu.utah.sci.vistrails.basic:String)')] Configuring Ports - Port Types What do I need to change in my package to make it reloadable (new in v1.4.2)? See Creating Reloadable Packages for an explanation. Can I add default values or labels for parameters? Yes. Versions 1.4 and greater support these features. See Configuring Ports - Default Values and Labels for more details. How can I access the default values for a parameter? The default values are stored in PortSpec.defaults for each port. I want to write a module to load HDF data whose output (e.g., data, string) varies according to the input I give it. Is is possible to do this in VisTrails, and if yes, how can I do that? Ideally, I would like to avoid having to change the connection of my output every time I change the input. There are a few ways to tackle this - each has it's own benefits and pitfalls. Firstly, module connections do respect class hierarchies as we're familiar with in object oriented languages. For instance, A module can output a Constant of which String, Float, Integer, etc are specifications. In this way, you can have a subclass of something like HDFData be passed out of the module and the connections will be established regardless of the sub-type. This is a bit dangerous though. Modules downstream of such a class may not really know how to operate on certain types derived from the super-class. Extreme care must be taken both when creating the modules as well as connecting them to prevent things like this from happening. A second method that I employ in several different packages is the idea of a container class. For instance, the NumSciPy package uses a relatively generic container "Numpy Array" to encapsulate the data. Of course, these encapsulating objects can store dictionaries that other modules can easily access and understand how to operate on. Although this method is slightly more work, the benefits of a stricter typing of ports is beneficial - particularly upon interfacing with other packages that may depend on strongly typed constants (for example). Varying Output According to the Input I need to determine, at run-time, whether or not a "child" module is attached to the output port of a "parent" module. (I do not specifically need to know which child; just if there is one). The outputPorts dictionary of the base Module stores this information. Thus, you should be able to check ("myPortName" in self.outputPorts) on the parent module to check if there are any downstream connections from the port "myPortName". This might be used, for example, to only set results for output ports that will be used. ***Note***, however, that the caching algorithm assumes that all outputs are set so adding a new connection to a previously unconnected output port will not work as desired if that module is cached. For this reason, I would currently recommend making such a module not cacheable. Another possibility is overriding the update() method to check the outputPorts and set the upToDate flag if they are not equal. In a single, limited test, this seemed to work, but be warned that it is not fully tested. Here is an example: class TestModule(Module): _output_ports = [('a1', '(edu.utah.sci.vistrails.basic:String)'), ('a2', '(edu.utah.sci.vistrails.basic:String)')] def __init__(self): Module.__init__(self) self._cached_output_ports = set() def update(self): if len(set(self.outputPorts) - self._cached_output_ports) > 0: self.upToDate = False Module.update(self) def compute(self): if "a1" in self.outputPorts: self.setResult("a1", "test") if "a2" in self.outputPorts: self.setResult("a2", "test2") self._cached_output_ports = set(self.outputPorts) Configuring Ports - Determining Whether or Not a Module is Attached to an Output Port How can I make a module not display in the modules list? You should set the abstract parameter to True when adding the module to the registry. Using the original syntax, this looks like: def initialize(): reg = core.modules.module_registry.get_module_registry() reg.add_module(InvisibleModule, abstract=True) # ... With the _modules dictionary shortcut (for more details, see the FAQ section on this), you include it in a kwargs dict as part of a module tuple: _modules = [AnotherModule, (InvisibleModule, {'abstract': True})] There is also a 'hide_descriptor' parameter that prevents the module from appearing in the module palette without declaring it to be abstract. The technical difference between the two is that 'abstract' will not add the item to the module palette while 'hide_descriptor' does add the item but immediately hides it. If the module should never be instantiated in a workflow, declare it abstract. If you don't want users to be able to add the module to a pipeline, but you have code that may add it programmatically, declare it with hide_descriptor=True. Configuring Modules - Hierarchy and Visibility How do I document individual ports? To access port documentation, users can right-click on the port in the port list and choose the corresponding menu item. To provide this documentation, you should define the provide_input_port_documentation and/or the provide_output_port_documentation class methods. Note that these methods take the class and the port name as arguments. For example, class MyModule(Module): _input_ports = [('test', '(edu.utah.sci.vistrails.basic:String)'), ('test2', '(edu.utah.sci.vistrails.basic:String)')] port_docs = {'test': 'Some documentation', 'test2': 'More documentation'} @classmethod def provide_input_port_documentation(cls, port_name): return cls.port_docs[port_name] How do I access modules from other packages? Currently, it is best to access modules from the registry. First, make sure that any dependencies on another package are specified in package_dependencies method in __init__.py. To create a module from another package as an output, you can generate it from the registry. For example, from core.modules.module_registry import get_module_registry from core.modules.vistrails_module import Module class ReturnFigManager(Module): _output_ports = [('figManager', '(edu.utah.sci.vistrails.matplotlib:MplFigureManager)')] def compute(self): reg = get_module_registry() wrapper = \ reg.get_descriptor_by_name("edu.utah.sci.vistrails.matplotlib", "MplFigureManager").module() wrapper.figManager = "blah" self.setResult('figManager', wrapper) You can also create subclass from classes obtained from the registry. For example, MplFigureManager = get_module_registry().get_descriptor_by_name( "edu.utah.sci.vistrails.matplotlib", "MplFigureManager").module class MplFigureManagerSubclass(MplFigureManager): pass How do I create a custom module configuration widget? See Module Configuration Example for a full example and notes about doing this. Can I make a PythonSource module cacheable? Yes. If you have a module that you are planning to re-use in a workflow, we recommend making a packaged module (which are by default cacheable). However, you can make a PythonSource (which are by default not cacheable) cacheable using the line self.is_cacheable = lambda *args, **kwargs: True in the source of the PythonSource module. The Console Where should I go to find out what I can call from the console and how to import it? We have tried to make some methods more accessible in the console via an api. You can import the api via from vistrails import api in the console and see the available methods with dir(api). To open a vistrail: from vistrails import api api.open_vistrail_from_file('/Applications/VisTrails/examples/terminator.vt') To execute a version of a workflow, you currently have to go through the controller: api.select_version('Histogram') api.get_current_controller().execute_current_workflow() Currently, only a subset of VisTrails functionality is directly available from the api. However, since VisTrails is written in python, you can dig down starting with the VistrailsApplication or controller object to expose most of our internal methods. If you have suggestions for calls to be added to the api, please let us know. One other feature that we're working on, but is still in progress is the ability to construct workflows via the console. For example: vtk = load_package('edu.utah.sci.vistrails.vtk') vtk.vtkDataSetReader() # adds a vtkDataSetReader module to the pipeline # click on the new module a = selected_modules()[0] # get the one currently selected module a.SetFile('/vistrails/examples/data/head120.vtk') # sets the SetFile parmaeter for the data set reader b = vtk.vtkContourFilter() # adds a vtkContourFilter module to the pipeline and saves to var b b.SetInputConnection0(a.GetOutputPort0()) # connects a's GetOutputPort0 port to b's SetInputConnection0 Finding Methods Via the Command Line Persistence Package How do I use the output of one workflow as the input for another using the persistence package? You need to configure the persistence modules using the module's configuration dialog. After adding a PersistentOutputFile to the workflow, click on the triangle in the upper-right corner of the PersistentOutputFile, and select "Edit Configuration" from the menu that appears. In this dialog, select "Create New Reference" and give the reference a name (and any space-delimited tags). Upon running that workflow, the data will be written to the persistent store. In the second workflow where you wish to use that file, add a PersistentInputFile and go to its configuration dialog in the same manner as with the output file. In that dialog, select "Use Existing Reference" and select the data that you just added in the first workflow in the list of files below. Now, when you run that workflow, it will grab the data from the persistent store. Here is an example: offscreen_persistent.vt. Run the "persistent offscreen" workflow first, and then run the "display persistent output" to use the output of the first workflow as the input for the second. VTK Given a VTK visualization, how can I generate a webpage from it? I'm trying to use VTK, but there doesn't seem to be any output. What is wrong? To use VTK on VisTrails, you need a slightly different way of connecting the renderer modules. Instead of using the standard RenderWindow/RenderWindowInteractor infrastructure, you simply connect the renderer to a VTKCell. The examples directory in the distribution has several VTK examples that illustrate. I am trying to add a module to the workflow via Python, but how can I access vtk modules? Here's an example: import api vtvtk = 'edu.utah.sci.vistrails.vtk' module = api.add_module(0, 0, vtvtk, 'vtkContourFilter', ) The third argument in add_module is the package identifier. You can find this in the "Module Packages" panel of the Preferences; just click on the package you're interested in and it will appear in the information on the right. matplotlib I'm experiencing a problem with Latex labels and the matplotlib that comes with VisTrails 1.5. The script below entered to the interpreter that comes with VT is sufficient to reproduce it. import matplotlib.pyplot as plt plt.plot([1,2,3],[1,2,3]) plt.xlabel("$foo$") Remove your ~/.matplotlib folder and re-start VisTrails rpy Package rpy fails with "module object has no attribute RVector" The rpy package needs to be updated to support a newer rpy version. In "packages/rpy/init.py", replace all instances of "objects.RVector" with "objects.Vector", or use this file. JobSubmission The JobSubmission package depends on the stable version of BatchQ. Download, copy the "BatchQ-stable/batchq" directory to your local site-packages folder. Copying it to the "vistrails/packages/JobSubmission" folder should also work. See batchq/contrib/vistrails for examples. VisTrails Development I would like to build VisTrails from source. Are there instructions on how to do this? Yes! Take a look at Installing VisTrails from source Accessing Provenance Information How do I access the information in the execution log? The code responsible for storing execution information is located in the "core/log" directories, and the code that generates much of that information is in "core/interpreter/cached.py". Modules can add execution-specific annotations to provenance via annotate() calls during execution, but much of the data (like timing and errors) is captured by the LogController and CachedInterpreter (the execution engine) objects. To analyze the log from a vistrail (.vt) file, you might have something like the following: import core.log.log import db.services.io def run(fname): # open the .vt bundle specified by the filename "fname" bundle = db.services.io.open_vistrail_bundle_from_zip_xml(fname)[0] # get the log filename log_fname = bundle.vistrail.db_log_filename if log_fname is not None: # open the log log = db.services.io.open_log_from_xml(log_fname, True) # convert the log from a db object core.log.log.Log.convert(log) for workflow_exec in log.workflow_execs: print 'workflow version:', workflow_exec.parent_version print 'time started:', workflow_exec.ts_start print 'time ended:', workflow_exec.ts_end print 'modules executed:', [i.module_id for i in workflow_exec.item_execs] if __name__ == '__main__': run("some_vistrail.vt") You should be able to see what information is available by looking at the "core/log" classes. Accessing the Execution Log VisTrails Binaries Is there a Mac OS X 10.6+ x64 binary of the version 1.7 of VisTrails available? We don't have a 64bit Mac binary for v1.7 release because at the time we didn't have 64 bit versions of the libraries shipped in the 1.7 binary. However, it is possible to update a 64bit or any other binary with a source release of VisTrails, including the sources of 1.7 version or the nightly builds. Assuming you have the sources of 1.7 in /vistrails1.7 and the 64bit binary in /Applications/VisTrails1.7 do the following steps: cp /vistrails1.7/vistrails/vistrails.py /Applications/VisTrails1.7/VisTrails.app/Contents/Resources cp -r /vistrails1.7/vistrails/api /Applications/VisTrails1.7/VisTrails.app/Contents/Resources/lib/python2.7/ cp -r /vistrails1.7/vistrails/core /Applications/VisTrails1.7/VisTrails.app/Contents/Resources/lib/python2.7/ cp -r /vistrails1.7/vistrails/db /Applications/VisTrails1.7/VisTrails.app/Contents/Resources/lib/python2.7/ cp -r /vistrails1.7/vistrails/gui /Applications/VisTrails1.7/VisTrails.app/Contents/Resources/lib/python2.7/ cp -r /vistrails1.7/vistrails/packages /Applications/VisTrails1.7/VisTrails.app/Contents/Resources/lib/python2.7/ cp -r /vistrails1.7/examples /Applications/VisTrails1.7/ cp -r /vistrails1.7/extensions /Applications/VisTrails1.7/ cp -r /vistrails1.7/scripts /Applications/VisTrails1.7/ AVG Antivirus falsely report a virus in VisTrails 2.0.2 32-bit Windows installer Problematic file is vistrails/Python27/Lib/site-packages/_mysql.pyd:. This is most likely a false positive and can be ignored. VisTrails fails after upgrading to OSX 10.9 Reinstalling XQuartz should solve the problem.
https://www.vistrails.org/index.php?title=FAQ&oldid=13971
CC-MAIN-2019-18
en
refinedweb
These are chat archives for opal/opal Opal.Foo.$new().$bar(); Opal.Foo, and opal methods get prefixed with $, so to create a Foo object, you'd do Opal.Foo.$new(), and you would just call $bar() off of that Opal.Foo.$new().$bar();is basically what Foo.new.barwould get compiled to return $scope.get('Foo').$new().$bar();after all the opal setup, but if you wanted the equivalent of Foo.new.bar in javascript, you'd write Opal.Foo.$new().$bar(); @adambeynon @elia guys, with arity check enabled (which is how specs are running), the following fails with an ArgumentError, wrong number of arguments(1 for 0) def test puts 'ok' end a = nil test(*a) But this works on MRI just fine. I think splat with a nil is a special case. Any idea where I could begin fixing this? I need this to work to pass some new rubyspecs... file.rbinto file.jsis to write this on the command line: opal -c file.rb > file.js file.jsinto your html page using a script tag, like any other javascript file. Make sense? if obj.is_a?(Native::Object) blahand if native?(obj) everything is an objectbeauty of Ruby @elia on a different front when would one want to do class Wrapper < `JsClass` alias_native :method_name def initialize `return new JsClass()` end end vs class Wrapper include Native def initialize @native = `new JsClass()` end end opal-slimwork but get NoMethodError: undefined methodindent_dynamic' for Temple::Utils`. Every one use it ? Thanks # config/initializers/opal.rb Rails.application.config.assets.paths << Rails.root.join('app', ’shared').to_s So far I am setting up a directory shared, which will contain ruby code that will get included in the server as well as the client... So for works okay, except I wanted to do this: class Jobs # bunch of stuff that only is relevant to the server end and in the shared directory class Jobs # stuff related to both client and server end The only problem is that rails will only find one (I think) so one has to require the other... not a big deal I guess
https://gitter.im/opal/opal/archives/2015/06/11
CC-MAIN-2019-18
en
refinedweb
Polymorphic line scaler. More... #include <LineScalers.hh> Polymorphic line scaler. Abstract base class for line scalers. Can be used when one basic algorithm should work in combination with multiple line scalers (e.g. several Scale_XonY variants). A line scaler takes one line of input pixels and outputs a different line of pixels. The input and output don't necessarily have the same number of pixels. An alternative (which we used in the past) is to templatize that algorithm on the LineScaler type. In theory this results in a faster routine, but in practice this performance benefit is often not measurable while it does result in bigger code size. Definition at line 282 of file LineScalers.hh. Is this scale operation actually a copy? This info can be used to (in a multi-step scale operation) immediately produce the output of the previous step in this step's output buffer, so effectively skipping this step. Implemented in openmsx::PolyScaleRef< Pixel, Scaler >, and openmsx::PolyScale< Pixel, Scaler >. Referenced by openmsx::calcEdgesGL(), and openmsx::RGBTriplet3xScaler< Pixel >::RGBTriplet3xScaler(). Actually scale a line. Implemented in openmsx::PolyScaleRef< Pixel, Scaler >, and openmsx::PolyScale< Pixel, Scaler >.
http://openmsx.org/doxygen/classopenmsx_1_1PolyLineScaler.html
CC-MAIN-2019-18
en
refinedweb
This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python. from sympy import * init_printing() import sympy.ntheory as nt Test whether a number is prime. nt.isprime(2011) Find the next prime after a given number. nt.nextprime(2011) What is the 1000th prime number? nt.prime(1000) How many primes less than 2011 are there? nt.primepi(2011) We can plot $\pi(x)$, the prime-counting function (the number of prime numbers less than or equal to some number x). The famous prime number theorem states that this function is asymptotically equivalent to $x/\log(x)$. This expression approximately quantifies the distribution of the prime numbers among all integers. import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.arange(2, 10000) plt.plot(x, list(map(nt.primepi, x)), '-k', label='$\pi(x)$'); plt.plot(x, x / np.log(x), '--k', label='$x/\log(x)$'); plt.legend(loc=2); Let's compute the integer factorization of some number. nt.factorint(1998) 2 * 3**3 * 37 A lazy mathematician is counting his marbles. When they are arranged in three rows, the last column contains one marble. When they form four rows, there are two marbles in the last column, and there are three with five rows. The Chinese Remainer Theorem can give him the answer directly. from sympy.ntheory.modular import solve_congruence solve_congruence((1, 3), (2, 4), (3, 5)) There are infinitely many solutions: 58, and 58 plus any multiple of 60. Since 118 seems visually too high, 58 is the right answer. You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).
http://nbviewer.jupyter.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter15_symbolic/05_number_theory.ipynb
CC-MAIN-2017-47
en
refinedweb
I'm trying to speed up a few regex's in a script that gets called a few dozen times a day. Each invocation basically loops through a ton of source code and builds a sort of searchable index. The problem is one single run of this script is now taking more than a day to run. There's some parallel-ization that can be done, but I'm hopeful there's something to be gained within each script as well. The script in question is MXR's "genxref": here Here's a relevant NYTProf run (one of the dozens that gets run daily, across different source repos): here. You can see some lines are getting hit a million times or more. Here's a good example fragment: 879 # Remove nested parentheses. 880 while ($contents =~ s/\(([^\)]*)\(/\($1\05/g || 881 $contents =~ s/\05([^\(\)]*)\)/ $1 /g) {} [download] This is one problematic snippet, but hardly the only one... the script is littered with complicated regex's. Most of them quick enough as-is, but some (like above) have become a significant performance bottleneck as our code base as grown. How might I improve upon this situation? Specific improvements and general ideas both welcome... I know the basics from a theoretical perspective (don't capture if you don't have to, try not to backtrack, etc), but not how to spot/fix problems. I don't have enough real-world experience with this. Thanks!. Thanks! There are a few places in the code where small savings can be achieved essentially for free: But even if you could make this level of savings on every single line in the program, you'd still save maybe an hour at most. Looking at a few of the individual REs, nothing leaps off the page as being particularly extravagant. You should heed the annotation at the top of the profiling and try to remove usage of $&. This has been known to effect a substantial time saving. The only place affected is this sub: sub java_clean { my $contents = $_[0]; while ($contents =~ s/(\{[^\{]*)\{([^\{\}]*)\}/ $1."\05".&wash($2)/ges) {} $contents =~ s/\05/\{\}/gs; # Remove imports ##$contents =~ s/^\s*import.*;/&wash($&)/gem; $contents =~ s/(^\s*import.*;)/&wash($1)/gem; # Remove packages ##$contents =~ s/^\s*package.*;/&wash($&)/gem; $contents =~ s/(^\s*package.*;)/&wash($1)/gem; return $contents; } [download] The uncommented replacements should have the same effect (untested) and the changes could have a substantial affect on the overall performance of a script dominated by regex manipulations. While you're at it, you can also add a few micro-optimisations where they are called millions of times like: sub wash { ##### my $towash = $_[0]; return ( "\n" x ( $_[0] =~ tr/\n// ) ); } [download] which will save the 7 seconds spent copying the input parameter. But given that the overall runtime is 7 minutes, that's not going to have a big effect. The only way you're a likely to get substantial savings from within the script, is to try optimising the algorithms used -- which amounts to tuning all of the individual regexes; and the heuristics they represent -- and that comes with enormous risk of breaking the logic completely and would require extensive and detailed testing. All of that said, if you split the workload across two processors, you're likely to achieve close to a 50% saving. Across 4, and a 75% saving is theoretically possible. It really doesn't make much sense to spend time looking for saving within the script when, with a little restructuring, it lends itself so readily to being parallelised. On the $& fix, all I can say is *thank you*. I had investigated this previously, but I was completely misreading the warning in NYTProf as complaining that line 32 itself was doing this, which I couldn't figure out at all. You actually found the offending lines and even offered a fix! After making your change, the warning does indeed go away. From the docs this seems like a safe change to make. Sadly, this seems to have a very small effect in this particular environment / workload. A 38-second run was virtually unaffected... +/- one second. On a 15-minute repo, it fell by about 4-5 seconds. There are bigger repos that might show a bigger benefit, but I suspect we'll only shave at most a few minutes off over a full day's work. Still, every little bit helps and fixing the warning is nice in and of itself. :) I'm working on some parallelization for this, which should help. I'm slightly concerned this might overload the system it runs on, but that can be fixed with the proper application of a wallet. For example, we have a set of repos that have this script run on them every 4 hours.. A better implementation (say, using GNU parallel) may get it down to an hour flat. At the same time there's a much bigger set of repos that get processed daily. I think it takes over 24 hours to run (separate issue: it stopped reporting its status regularly). This runs concurrently, and obviously can overlap the 4-hour jobs.. Still, it's clearly a very good approach to reducing wall-clock time. I was primarily hoping someone would spot something egregiously wrong with the regex's that I could fix, but that seems not to be the case. Oh well... guess we'll do it the hard way. :). You're only going to some limited benefit by tweaking the regex patterns. Shaving 20% off of 60 seconds is still 48 seconds. One thing I see is that you're scanning the file from to to bottom for each s/// operator, and often more than once per pattern. Your efforts might be better spent avoid that. Some examples are self contained, while ($contents =~ s/\05([^\n\05]+)\05/$1\05\05/gs) {} | | v $contents =~ s/\05([^\n\05]+)(?=\05)/$1\05/gs; [download] But that's not going to help you remove this waste in general. Hmm... going to have to get help here. I'm not familiar enough with this code or its expected output to really tell when it's working or when I might introduce a subtle bug somewhere. This seems more like the latter scenario. Thanks for pointing this out! On this particular example, I'm not understanding how the two things are identical. The substitution pattern in your version has one less \05. Is that intentional? If so, how does that work? I don't really grok the look-around assertion, and/or how that's relevant to not needing the extra \05 in the substitution pattern. For that matter, I'm not sure what \05 even is. Most places seem to say that an octal character code requires exactly 3 digits, but some say you can get away with less, as long as the leading digit is zero. But, \05 interpreted as octal is non-printing... don't know what it is, or why it would be in these files. Any thoughts on that?.
http://www.perlmonks.org/?node_id=935021
CC-MAIN-2017-47
en
refinedweb
This weekend’s big games – use public transport 11 October, 2006 This weekend’s big games – use public transport Special train and regular bus services are at hand to take rugby fans to this weekend’s big games, helping them avoid the expense of driving and hassle of finding a park. To choose which service best suits them, fans can call MAXX on (09) 366 6400 or visit. ARTA Acting Chief Executive Elena Trout, said, “League and Union fans alike can choose from many transport options to get to the weekend’s games. Many fans are already avoiding traffic queues and enjoying the freedom taking public transport to and from the games brings. Anyone who hasn’t taken a bus or train to a game should give it a go.” Ms Trout says offering integrated transport and more choice of services is consistent with ARTA’s plans to develop the region’s public transport system to better suit Aucklanders. She highlights that the region’s agencies with transport responsibilities are working together to continually improve the transport network’s efficiency. An overview of public transport to and from the weekend’s games: Air NZ Cup Rugby, semi final: Auckland vs Wellington Eden Park: Friday 13 October 2006, kick-off 7:35pm Aucklanders can choose from 18 different bus and train routes, and many more services to get to Eden Park: Bus services Any bus that runs along New North Road, Sandringham Road or Dominion Road stops within a five minute walk to Eden Park. These include: - New North Road: 210, 211, 215, 212, 223, 224 - Sandringham Road: 233, 241, 243, 248, 249 - Dominion Road: 256, 258, 267 - The crosstown 006 service from St Lukes to Newmarket - Two special match evening services: - Free neighbourhood shuttle running a local loop service (call MAXX or visit for more details) - A special Stagecoach bus service will operate from the central city to Eden Park and return (call MAXX or visit for more details). Train services (stopping at Kingsland Station) from: - CBD* (Britomart Transport Centre, next to the Downtown Ferry Terminal) – Any train heading West to Waitakere/New Lynn - West* (Waitakere/New Lynn) – any train heading into Britomart Transport Centre - South/ East (Papakura, Glen Innes) - change at Newmarket or Britomart Transport Centre for any train heading West to Waitakere/New Lynn - Please note that special return services will be provided after the game leaving Kingsland for the CBD at 9:52pm and for West at 9:56pm. 2006 Tri-Nations Series: New Zealand Kiwis vs Australian Kangaroos Mt. Smart Stadium: Saturday 14 October 2006, kick-off 7:45pm Aucklanders can choose from five different bus and train routes, and many more services to get within a 10-15 minute walk to Mt Smart Stadium: Train services (stopping at Penrose Station) from: - CBD (Britomart Transport Centre, next to the Downtown Ferry Terminal) – Any train heading South via Newmarket - West** (Henderson) – change at Newmarket or Britomart for any train heading South via Otahuhu - South (Papakura) – any train heading North to Britomart Transport Centre via Otahuhu. Please note a special service from Pukekohe will also be departing for Penrose station at 6.15pm and returning at 9.45pm - East (Glen Innes) - change at Britomart Transport Centre for any train heading South via Newmarket or head to Otahuhu and take any train heading North via Newmarket Bus services (along Great South Road) from: - CBD: 417, 472, 487, 497 – nearest stop is Great South Road, next to Penrose Train Station and the stadium is a 10 – 15 minute walk from there. - South, Otahuhu Transport Centre: 417, 472, 487, 497 – nearest stop is Great South Road, next to Penrose Train Station and the stadium is a 10 – 15 minute walk from there. Normal fares apply for all services, and passengers are encouraged to get to the stadiums early and enjoy the pre-match entertainment. For more information, including timetables and a recommendation of the best route passengers can call MAXX on (09) 366 6400 or visit * Two additional trains are running on the Western Line out to New Lynn and to Britomart **Trains will replace buses for the journey between Waitakere and New Lynn on Saturday 14 October ENDS
http://www.scoop.co.nz/stories/AK0610/S00099.htm
CC-MAIN-2017-47
en
refinedweb
Introduction: Big, Auto Dim, Room Clock (using Arduino and WS2811) First Hello instructables. This is my first contact with : - Instructables - Arduino - Programmable LED's So please don't trow rocks at me for noobish mistakes. Keeping that in mind I'm waiting to read your comments with grate interest and I'm open to any suggestion Features : - big digits ( each digit is approximately the size of a A4 paper). - slim in order to fit in a photo frame (a big one). - auto dim the light depending on the light in the room. - dedicated DST button. Step 1: Prerequisites Things I used for this project : Electronics : -) Total cost of electronics : 17.78 $ (without arduino donation) Miscellaneous : Heat Shrink Tubing - 7.99$ ebay (assortment, it total 33m) 20 pcs 5 x 7 cm prototype pcb - 3$ ebay 3 pcs Micro Switch - 1$ locally bought Solder - 1$ locally bought - Flux - 1$ locally bought - UTP cable (individual wires used for various connections) - LCD font () - free - Cardboard - free loacal supermarket Polystyrene board - 1.50$ locally bought Various tools. Step 2: Preparing - Digit Template - download and install LCD font ( - open word or similar editor and make a template similar to the image (first img) - font size ~800, - white font color black outline, - gray boxes where led strip fits - Print and cut the gray strips with a exacto knife (second img) Step 3: Preparing - Cut Cardboard and Led Strip Using the digit template cut the cardboard to size (don't forget to leave space for the dots between hours and minutes) If your LED strips came with connectors at each end (like mine did) desolder the connector and cut them in sets of 3. Step 4: Stick the LED Strips Using the template stick the LED strip on the cardboard. It's not mandatory but I used a pencil to mark where the LED strips should be placed, this way I got to see the final form before attaching the LED's. It was a good thing since this is how I noticed I left two much space for those dots in the middle, as a result I had stuck the LED strips a little closer. Step 5: Solder LED Strips Now starts a long soldering session. Solder the LED strips in order to form a continues strip. Notice the order in which to solder the strips in the picture. For the middle dots I used a single LED strip and covered the middle LED with duct tape. I used the following color code - Blue for ground - Green for data - Red for Vcc (12v) Step 6: Wire Arduino on Breadbord I tried doing a sketch in fritzing but I can't find all the parts :( , Sorry So here is a list with all the connections and another picture with the setup on a breadboard Step 7: Test LED's Before loading this sketch (for which I assume no credit) don't forget to add FastLED library. If everything went OK the LED's should cycle trough colors. If you have any problems first check your soldered points. Step 8: Program the Clock After struggling a little I managed to get a working clock that covers all my needs. I'm sure there is room for improvement. The code is very commented, if you have any questions please feel free to ask. Also if you have any suggestions, please do tell. All debugging messages are commented as well. In order to change the color used you must modify the variable at line 22 ( int ledColor = 0x0000FF; // Color used (in hex)). You can find a list of colors at the bottom of this page:... If you have problems downloading the code file from instructables here is a mirror : Step 9: Make Digits Form Using Polystyrene Cut each segment in the template printed at the beginning. Form each digit in the polystyrene using a exacto knife (very hard) or a Hot Wire Cutter. You can see how I made mine in the pictures. If you don't have a guitar string you can use just about any thin STEEL wire. In order to power the Hot Wire Cutter I used the 12v LED power supply. Also there is a picture with a cut digit. (sorry I forgot to take pictures in the process). Step 10: Glue Digits and Adding Diffuser After cutting all 4 digits and the dots glue all of them on the cardboard with the LED strips. (for this process I used double sided adhesive tape). In order to diffuse the LED light I used 2 paper sheets on top of the polystyrene. For convenience and aesthetics I used a single A2 size paper folded in two. Also for finishing touches I've put the entire assembly in a large picture frame. Very good project. Well done. could someone pass me the code please Hello everyone!!! Thank you for this awesome project! I already built, but I have a little problem... I conected D0 pin from light sensor to D3 arduino pin and no working, but when i connect D0 pin to A3 arduino pin it's working... This is good or bad? can someone help me... Thanks!! Sar plz add a HH:MM:SS code Where is 5 x 7 cm prototype pcb was used ? Thanks for your instructable ;) After i realized that i shorted the sdl and scl line it works like a charm. I've found a bug in your arduino script. You can't use integer for the ledcolor, you have to use longinteger. Else your unable to use the red color. Also i added some lines to use different colors at different times of day. regards Martin amigo serias tan amable de pasarme el codigo de programacion!!! he armado la circuiteria pero no se cual de las que exponen sea la correcta,por lo que muestras considero que la suya es la correcta. amigo podrias pasar el codigo Bug and addition can you post your code on github or directly here? I cant see well on those pictures.. thanks Thank you everyone, i made my 1st version based on WS2812B cut by 3. I will finish it later, maybe try to print the Temperature or add some effects! so many possibilities with those Leds it's awesome!! puedes pasarme el codigo amigo..hebuscado el codigo y nadie lo comparte! tek renk şerit led kullanarak yapmak mümkün mü termometre de ekleyebilir miyiz Nice work, You can get the temperature form RTC module using this code int t = RTC.temperature(); float celsius = t / 4.0; float fahrenheit = celsius * 9.0 / 5.0 + 32.0; You can comment the last line if you want celsius. hi, im almost finished with this great project. I just dont understand how to put this temperature code into the full code. Im total noob to programming ;-) can u help ? thanks a lot Thanks for sharing this with us and thx for the tip i think you meant float t ;) here is a video of what it looks like : every minute i add the cylon effet example and then it changes the color randomly from preselected array of colors. Here is my code : #include <DS3232RTC.h> #include <Time.h> #include <Wire.h> #include <FastLED.h> #define NUM_LEDS 90 // 5 by segment + 6 in the middle #define LED_TYPE WS2812 #define COLOR_ORDER GRB // Define color order for your strip #define BRIGHTNESS 150 #define LED_PIN 5 // Data pin for led comunication CRGB leds[NUM_LEDS]; // Define LEDs strip byte digits[10][21] = { { 0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } , // Digit 0 { 0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1 } , // Digit 1 { 1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0,0,0 } , // Digit 2 { 1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1 } , // Digit 3 { 1,1,1,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1 } , // Digit 4 { 1,1,1,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1 } , // Digit 5 { 1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } , // Digit 6 { 0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1 } , // Digit 7 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } , // Digit 8 { 1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1 } }; // Digit 9 | 2D Array for numbers on 7 segment byte firstdigit[2][10] = { { 0,0,0,0,0,0,0,0,0,0 } , // Digit 0 first number { 1,1,1,1,1,1,1,1,1,1 } }; // Digit 1 first number | 2D Array for numbers on 7 segment bool Dot = true; //Dot state bool DST = false; //DST state int last_digit = 0; //long ledColor = CRGB::DarkOrchid; // Color used (in hex) long ledColor = CRGB::MediumVioletRed; long ColorTable[16] = { CRGB::Amethyst, CRGB::Aqua, CRGB::Blue, CRGB::Chartreuse, CRGB::DarkGreen, CRGB::DarkMagenta, CRGB::DarkOrange, CRGB::DeepPink, CRGB::Fuchsia, CRGB::Gold, CRGB::GreenYellow, CRGB::LightCoral, CRGB::Tomato, CRGB::Salmon, CRGB::Red, CRGB::Orchid}; void setup(){ Serial.begin(9600); Wire.begin(); FastLED.addLeds<WS2812B, LED_PIN, RGB>(leds, NUM_LEDS); // FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip ); FastLED.setBrightness( BRIGHTNESS ); pinMode(2, INPUT_PULLUP); // Define DST adjust button pin pinMode(4, INPUT_PULLUP); // Define Minutes adjust button pin // pinMode(5, INPUT_PULLUP); // Define Hours adjust button pin } // Check Light sensor and set brightness accordingly void BrightnessCheck(){ const byte sensorPin = 3; // light sensor pin const byte brightnessLow = 75; // Low brightness value const byte brightnessHigh = 100; // High brightness value int sensorValue = digitalRead(sensorPin); // Read sensor if (sensorValue == 0) { Serial.println("Brightness High"); LEDS.setBrightness(brightnessHigh); } else { Serial.println("Brightness Low"); LEDS.setBrightness(brightnessLow); } }; // Get time in a single number int GetTime(){ tmElements_t Now; RTC.read(Now); //time_t Now = RTC.Now();// Getting the current Time and storing it into a DateTime object int hour=Now.Hour; int minutes=Now.Minute; int second =Now.Second; if (second % 2==0) { Dot = false; } else { Dot = true; }; return (hour*100+minutes); }; void DSTcheck(){ int buttonDST = digitalRead(2); Serial.print("DST is: "); Serial.println(DST); if (buttonDST == LOW){ if (DST){ DST=false; Serial.print("Switching DST to: "); Serial.println(DST); } else if (!DST){ DST=true; Serial.print("Switching DST to: "); Serial.println(DST); }; delay(500); }; } // Convert time to array needet for display void TimeToArray(){ int Now = GetTime(); // Get time int cursor = 90; //116 Serial.print("Time is: "); Serial.println(Now); if (Dot){ leds[42]=ledColor; leds[44]=ledColor; leds[45]=ledColor; leds[46]=ledColor; leds[47]=ledColor; //leds[48]=ledColor; } else { leds[42]=0x000000; leds[44]=0x000000; leds[45]=0x000000; leds[46]=0x000000; leds[47]=0x000000; //leds[48]=0x000000; }; for(int i=1;i<=4;i++){ int digit = Now % 10; // get last digit in time if (i==1){ cursor =69; //82 Serial.print("Digit 4 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; // fin for Serial.println(); if (digit != last_digit) { fadefonction(); ledColor = ColorTable[random(16)]; } last_digit = digit; }// fin if else if (i==2){ cursor =48; Serial.print("Digit 3 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; Serial.println(); } else if (i==3){ cursor =21; Serial.print("Digit 2 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; Serial.println(); } else if (i==4){ cursor =0; Serial.print("Digit 1 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; // Serial.println(); }; Now /= 10; }; }; void TimeAdjust(){ int buttonH = digitalRead(5); int buttonM = digitalRead(4); if (buttonH == LOW || buttonM == LOW){ delay(500); tmElements_t Now; RTC.read(Now); int hour=Now.Hour; int minutes=Now.Minute; if (buttonH == LOW){ if (Now.Hour== 24){ Now.Hour=1; } else { Now.Hour += 1; }; } else { if (Now.Minute== 59){ Now.Minute=0; } else { Now.Minute += 1; }; }; RTC.write(Now); } } void fadeall() { for(int m = 0; m < NUM_LEDS; m++) { leds[m].nscale8(250); } } void fadefon); } // Now go in the other direction. for(int i = (NUM_LEDS)-1; i >= 0;); } } void loop() // Main loop { /*BrightnessCheck(); // Check brightness DSTcheck(); // Check DST TimeAdjust(); // Check to se if time is geting modified*/ TimeToArray(); // Get leds array with required configuration FastLED.show(); // Display leds array /*float t = RTC.temperature(); float celsius = t / 4.0; Serial.println(); Serial.print("Temp is : "); Serial.print(celsius); Serial.println();*/ } Thx for this nice project. I made also a pcb for it. I'm totally new with Arduino. Can someone tell me how I can change the color on different times. For example: 8 am red, 10 am green, 10.15 am red 12 am green, 1 pm red, ... I used the clock.ino file of the site. Hello!! Someone have the corect code for this project, cause i get some error from this code. In principle the 'tmElements_t' was not declared. Can anybody give me a solution? Thanks. Did it a few weeks ago with 3 WS2812/segment and some 3D printing. Everything works but after some time, the clock just stop working (some lag at first then stucked) https: //tr.aliexpress.com/item/1m-4m-5m-WS2812B-Sm ... acaba hello, i interest with this project, but i use ws2812b for the segment, is anybody have a code, i try in saxos1983 github it's not available... i want 24 hours clock like onlynoise build.. thanks error error code please help. sketch_mar31a.ino:1:23: fatal error: DS3232RTC.h: No such file or directory compilation terminated. my gmail. [email protected] bu projenizi çok beğendim. bende yapmak istiyorum .kodlamada sorun yaşıyorum. program derlemede hata gösteriyor. bana projenizin detaylarını yollarmısınız. teşekkür ederim. iyi çalışmalar. [email protected] In English please, I can't understand where you need help.... with this product this project Can we work We only want to use arduino and rtc in the circuit, and we want to show the time on the screen. Could you help. calisan kod var mi hocam sizde Hi there, this is a cool project. I have already built the clock, but i'm having a problem with the code. When i try to compile it i get the error exit status 1 'tmElements_t' was not declared in this scope I have already fastled and DS3232RTC libraries. Any idea? Thanks. I am getting the same mistake, how did you solve I added #include and the problem was solved . Http: //urun.gittigidiyor.com/ev-bahce/5-metre-3-ci ... tek renk şerit led kullanarak bu projeyi yapabilir miyiz bu kodlar ile çalışır mı I had to add #include Problem solved :). I had to add #include <TimeLib.h> Thankyou :) Cool project! He decided to build this same! () Few had to rewrite the code, I have a number of LEDs in segments - more! It wanted to make it shows the date and temperature! I already have DHT11 module! Unfortunately, I do not know how to program the Arduino. projeniz calisir durumda mi kod ve devre semasini paylasir misiniz I have made the same project, it is gr8 weekend project yaptiginiz projeye ait devre semasi ve kodlari paylasir misiniz. than you good day sir! can i ask how you code this clock? i want to have a countdown timer similar to this display. can you help me how to program it? only 24 seconds for a shot clock. thanks. Hello Friend! I also plan to assemble LED ws2812b, but none like can`t find a suitable sketch. Could you share your sketch? Hello friend. share the sketch, too, wanta thermometer Thank you. I did on the 2812b, 2 pieces per segment. The hardest part was cut out pattern ... and it's not a joke, too small partitions in numbers. Thanks again. hey how do i add the temperature on the 7 digit display ? i made the clock with the ws2811 led's. Great build! I want build it but i want to edit a little. I want to make a stopwatch that can count until 99,99 seconds, please can you answer me to some questions ? 1. What more parts i need to make it work? 2. Can I add 3 buttons, Start,Stop and reset? 3 Can i use two stopwatches on one Arduino board and have there 4 buttons,Start, Stop 1, Stop 2 and reset? Thank you in advantage ps:I don't know nothing about Arduino, I am learning it now and i like it :) ayuda me brindarías los archivos no soy premiun metro es [email protected] muchas gracias In English, please. I don't understand where you need help. Hello, cool project. I was wondering if i can make the same with just a single color led strip instead of RGB? If they are individually addressable then yes. alguien que me heche una mano hace mucho tiempo que intente hacer este proyecto con ws2811 pero hice todo como el tuto dice y sismpre me sale error en la compilacion de arduiino,,simplemente no funciona,,alguien podria pasarme el codigo completo y correcto ,ya que tengo todo el material pero no me funcione,espero me ayuden porfavor que quiero hacer este reloj tambien Would the code for this be available please it's great Can this clock be modded to add seconds like 00:00:00? thanks in advance ordering the parts now
http://www.instructables.com/id/Big-auto-dim-room-clock-using-arduino-and-WS2811/
CC-MAIN-2017-47
en
refinedweb
I have a question about Custom UserControl binding properties. To be more specific, I've created a simple class like this one. public partial class LinearGradBrush : UserControl { public LinearGradBrush() { InitializeComponent(); } class LinearGradBrushProp : DependencyObject { public static DependencyProperty _background; static void BackgroundBrush() { _background = DependencyProperty.Register("_background", typeof(Brush), typeof(LinearGradBrushProp)); } [Description("CuloareBG"), Category("Z")] public Brush Background { get { return (Brush)GetValue(_background); } set { SetValue(_background, value); } } } } After I've searched all over the Internet I couldn't find the right answer so please, I want to ask you why I don't see in my DesignView the category Z with a brush in it.
http://www.dreamincode.net/forums/topic/293072-custom-usercontrol-binding-properties/
CC-MAIN-2017-47
en
refinedweb
#include "resource.h" An AsyncCallback for a freshen. The Done() callback in the default implementation deletes itself. This is called with resource_ok = true only if the hash of the fetched response is the same as the hash in input_info()->input_content_hash(). Implements net_instaweb::Resource::AsyncCallback. Returns NULL by default. Sublasses should override this if they want this to be updated based on the response fetched while freshening.
https://www.modpagespeed.com/psol/classnet__instaweb_1_1Resource_1_1FreshenCallback.html
CC-MAIN-2017-47
en
refinedweb
Import a sample from a CSV file¶ In this basic example we are going to import a CSV file In [15]: from __future__ import print_function import openturns as ot # write a csv file by hand with open('sample.csv', 'w') as f: f.write('0.1, 0.2, 0.3\n') f.write('0.7, 8.2, 4.3\n') In [16]: # default separator is ';' sample = ot.Sample.ImportFromCSVFile('sample.csv', ',') print(sample) [ data_0 data_1 data_2 ] 0 : [ 0.1 0.2 0.3 ] 1 : [ 0.7 8.2 4.3 ]
http://openturns.github.io/openturns/master/examples/data_analysis/import_sample_from_csv.html
CC-MAIN-2017-47
en
refinedweb
Introduction to ActionScript 3.0/Class structure Key concepts: - Objects, methods and properties - Classes - Packages - Importing - Variables and constants - Integrated development environments - Compilation - Document class - Object instantiation Definition: Organization of classes in a society Ah, classes. ActionScript projects are essentially made up of classes. (OK, there are interfaces too, but we'll cover them later.) Contents - 1 What is object-oriented programming? - 2 What are classes made of? - 3 How does Flash actually work? - 4 Let's do it! What is object-oriented programming?[edit] Object-oriented programming, as the name suggests, is a programming paradigm that involves the creation of and interaction among objects. An object consists of two parts: - Properties that define the object's characteristics. For example, an apple may have properties like 'size', 'colour', 'juiciness', and so on. - Methods that define what the object can do. Methods are a subset of functions, which we'll discuss later. An apple may have methods like 'transport', 'eat', etc. What are classes made of?[edit] A class in ActionScript 3.0 looks like this. Let's look at it the elements of it, one by one. package { import flash.display.Sprite; import flash.events.Event; /** * @author WikibooksOverlord */ public class Main extends Sprite{ private const HELLO_WORLD:String = "Hello, world!"; private var _username:String = "Daniel";. } } } Package definitions[edit] package { A package is a group of classes and other stuff inside a certain directory. The line of code above is called a package definition. For example, a package called 'fruit' might contain classes like Fruit and Apple. The word 'package' here is a keyword. A keyword is a word used by the language for basic operations. In our case, our class is stored in the main package, so we don't need additional information after the 'package' keyword. To specify that our class resides in the 'food' package, we can append the package name after the 'package' keyword: package food{ If there's a 'fruit' package inside the 'food' package, we separate the larger package and the smaller package with a dot ('.'): package food.fruit{ Apart from improving organisation, classes inside a package may have the same name as classes inside other packages. The package name is what distinguishes between them. You can have a class called applicances.Iron and another called materials.Iron. Notice that the opening brace after the definition is matched by a closing brace at the end of the class file. Everything else in the program is set to be enclosed in this block. A block is a logical 'unit' of commands, or directives, enclosed by a pair of braces. By convention, everything inside a block should be indented, as shown above. Indentation improves code readability a lot, but it is not necessary for the program to work. (In fact, you could put everything in a class into one line and it would still work; however, the code will no longer be readable.) Also notice that all package names start with lowercase letters, while all class names start with uppercase letters. This is a universally accepted convention that should be followed, even though the code still works if you rebel. Import statements[edit] import flash.display.Sprite; import flash.events.Event; An import statement is needed if we want to use classes from other packages, such as the standard library. In this case, we have imported two packages from the standard library: flash.display.Sprite and flash.events.Event. The standard library is a bunch of code that controls the basic operations of our Flash operation, such as text, graphics, sounds and so on. There are alternatives to the standard library, but that will not be covered here. Sometimes, if we're lazy, we can import everything in a package with an asterisk (*): import flash.events.*; As you can see, the syntax for an import statement is the 'import' keyword, followed by the path to the package. Note that although flash.display.Sprite and flash.events.Event are predefined classes, they are not keywords as they belong to the standard library rather than the language itself. Once imported, we can use those classes in any way we want. Class definitions[edit] Class Structure: An organization of class with in a society. public class Main extends Sprite{ In this statement, the 'public' keyword tells us that we can use the class anywhere, even if we're outside the current package. This is known as a namespace attribute. Namespaces handle access control; that is, how the class can be accessed (surprisingly enough). There are only two possible namespace attributes for classes: publictells us that we can use the class anywhere. internaltells us that we can use the class in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'. After the namespace attribute, we find another keyword, 'class'. Then we see the class identifier Main. (An identifier is a 'name' that uniquely identifies something within a namespace. The full name of that something is the namespace plus the identifier. This will be covered later; for now, you can just treat the word 'identifier' as a special 'name'.) After that, we see the keyword 'extends', followed by the class name 'Sprite'. This indicates that our Main class is a subclass of the Sprite class. Later, when we learn what the Main class actually is and what subclasses are, you'll understand what we're doing in this line. For now, just take it for granted. Class members[edit] Class members include properties and methods. Properties can be constants, which never change, or variables, which change. private const HELLO_WORLD:String = "Hello, world!"; private var _username:String = "Daniel"; 'private' is another namespace attribute we use on class members. There are four possible namespace attributes (apart from user-defined ones): publictells us that we can use the member anywhere. internaltells us that we can access the member in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'. Later, we'll learn to access members of other classes. protectedtells us that only the class itself and its subclasses can access the member. privateis the most restrictive attribute. Only the class itself can access the member. Not even subclasses have permission. In general, the attributes we choose should be as restrictive as possible. In the lines of code above, we have defined and initialised a constant and a variable. In the next chapter, we'll cover what these two lines actually do. Here are our method definitions:. } In the above, we can see two method definitions: Main and init. Main is called the constructor of the class. When a class is initialised, this method is called to set things up. Note that constructors are always public. init is a private function that can only be called within the class. There are a plenty of things in this code snippet that you don't understand. Don't worry - we'll cover everything in the first section. For now, just take it for granted that it works! A comment does not change how the program work, but is an efficient way to add information to the program, whether for yourself or other programmers. There are two kinds of comments: The first type of comments starts with // and is added to the end of the line. It cannot extend over one line. This type of comment is usually used to explain code. trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now. trace("Your name is " + name + "."); //Don't touch anything below this line. The second type of comments, enclosed by /* and */, allows for multiple lines. /* marks the beginning of the comment and */ marks the end of it. This type of comment can also be added in the middle of a line. They are widely used for elements such as to-do lists and copyright information. This is an example: /*Lorem ipsum The quick brown fox Jumped over the lazy dog */ As you may have noticed, this kind of comment did appear in our Main class. However, it looks a bit different. This is because it is a Javadoc comment, which will be covered later. /** * @author WikibooksOverlord */ Sometimes, we need to 'hide' some code temporarily. This can be achieved turning code into comments. This technique is known as commenting out. How does Flash actually work?[edit] What are integrated development environments?[edit] The .as file we created above was just a text file; it didn't do anything constructive for us. To get the program to work, we need a compiler. Before getting to compilers, let's look at the different integrated development environments (IDEs) for coding in ActionScript. Although you can use a text editor to code in ActionScript and feed it into a command-line compiler, it is not recommended to do so. An integrated development environment typically contains the following features: - A project management system that organises the resources and files the project uses. - Syntax highlighting is a feature in which different parts of code are coloured to improve code readability. In this book, syntax colouring is achieved with the MediaWiki software. - Code hinting speeds up development by reminding you what you need to type next. - Syntax checkers which check your syntax. - A built-in compiler and debugging utility/debugger which allows you to compile and debug in the IDE. We will cover debuggers later. A good IDE also provides features for the editing of related markup languages like MXML (which is outside the scope of this book but very helpful for ActionScript interfaces). Common IDEs for Flash include: - Flash Professional: The first Flash authoring software, Flash Professional combines animation and coding into one piece of software. However, its IDE abilities are limited as a result. Flash CS3 and above supports AS3. - Eclipse: An all-purpose IDE used for many different languages, including ActionScript. - Flash Builder: A proprietory IDE based on Eclipse. - FlashDevelop: An open-source IDE geared towards ActionScript. It provides handy features such as SharedObject tracing and also contains advanced code hinting features. In this book, we will provide instructions for FlashDevelop. If you use other IDEs, refer to the relevant documentation. What is compilation?[edit] Computers only understand machine language. ActionScript is a human-readable language, but not a computer-readable one. The more high-level a language is, the closer it is to the computer system. Machine code and assembly language are the lowest-level languages in that they boss around different parts of the computer system directly. Higher-level languages must be converted into lower-level languages for the computer to understand. A compiler is a program that converts code from a high-level programming language into a low-level language. For ActionScript, it is a bit more complicated. An ActionScript compiler compiles our ActionScript into a lower-level language known as ActionScript Bytecode (ABC). Then, the ABC is wrapped together with the resouces (music, graphics, and so on) into another file known as a Shockwave Flash file (SWF), a magic performed by a SWF compiler. Flash Professional uses a SWF compiler called the Flash compiler, while FlashDevelop, Flash Builder, etc., use a SWF compiler called the Flex compiler. The ABC is then executed by a runtime environment called Flash Player using the embedded resources. The runtime environment compiles the ABC into machine language that controls the computer's hardware. This conversion is performed in real time, and is known as just-in-time compilation. There are two kinds of compilation, debug build and release build. Debug build is what you'll build during the development of your project. Once your project is ready for compilation, you will compile the release build, which is faster and more lightweight. To toggle between the builds, FlashDevelop has a toolbar on top with a drop-down menu that shows the tooltip 'Select Configuration' when you hover over it. Let's do it![edit] Now open the IDE of your choice and create a new project. In FlashDevelop, click on Project > New Project > AS3 Project. Name your project whatever you want. Now add the following folders to your project's main folder if they aren't already there: - src contains your project's source code. - bin contains your project's compiled binary (i.e. the SWF file if you've read the above section carefully). Next, in the 'project' screen of your IDE, locate the Main class. If it isn't already there, create one. Copy the code above directly onto the text file. Set it as the document class (in FlashDevelop, right-click on the file in the Projects window and check 'Document class'). Now, set the compiler to compile to \bin\MyFile.swf (Project > Properties > Output in FlashDevelop). Now compile and run the project (CTRL + ENTER or the blue 'play' button in FlashDevelop). If you've done everything correctly, you should see this in the output screen of your IDE: Hello, world! Your name is Daniel. What happened just now?[edit] Once a Flash application is started, the very first thing that happens is: - A new instance of the document class is instantiated. - The new instance is added to the stage. Now, you may be completely confused. Don't let those new words intimidate you! We'll look at everything one by one. Object instantiation[edit] Let's say we now have a class called Apple. Fortunately, in the programming world, you don't need to take the time to grow the apple. All you need is to create an instance of the Apple class. To create 200 apples, create 200 intsances of the Apple class. The creation of an instance is called instantiation. Usually, object instantiation is done using the new keyword. For example, the expression new Apple() instantiates a new apple. (Note that the round brackets here can be skipped.) However, our Main class here is a document class. That means the runtime environment very kindly instantiated the Main class for us.
https://en.wikibooks.org/wiki/Introduction_to_ActionScript_3.0/Class_structure
CC-MAIN-2017-09
en
refinedweb
Hi, Im porting a plugin to ST3 and on_query_completions stopped working properly. So instead of adding the value returned by on_query_completions function, it is adding an empty line. An example CURSOR_HEREhit completion short cut,pick on optionprint the array returned by on_query_completions before returning:('1.0\tValue', '1.0'), ('2.0\tValue', '2.0'), ('3.0\tValue', '3.0'), ('4.0\tValue', '4.0'), ('5.0\tValue', '5.0')]and then, the result is: Any ideas? Thanks! I found out that this bug only occurs when dealing with XML files and under the following circumstances: So it fails to complete when cursor is placed right in between an opening and closing tags with no spaces in between like: <contact></contact> Ig there are spaces or new lines in between the opening and closing tags, the completion works properly. For example here: or here: <contact> < Another bug report about on_query_completions, thought I'd put it here in case there will be some fixing going on: I am developing an IPython Notebook plugin (github.com/maximsch2/SublimeIPythonNotebook) and having problems with completions (among a lot of other things). So IPython can complete both Python code and directories and I want to support. If I am completing code like this:numpy.linalg.e using completion list like this: (numpy.linalg.eig, numpy.linalg.eigval, ...)], then it works correctly by replacing "e" with last word from the selected completion (completion is separated by dots),but if I am trying to complete directory:/home/max/bu using completion list like this: (/home/max/bugaga, /home/max/bugaga2, ...)], then after I select completion I get: "/home/max//home/max/bugaga", so there was no "last word extraction" process there. I wonder if this is somehow connected to that XML completion problem and if there is a way to control it. I am currently forced to use a hack like this: def on_completion(): ... def get_last_word(s): # needed for file/directory completion if s.endswith("/"): s = s:-1] res = s.split("/")-1] return res return ((s + "\t (IPython)", get_last_word(s)) for s in compl], sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS)
https://forum.sublimetext.com/t/on-query-completions-not-working-properly-on-st3/10371
CC-MAIN-2017-09
en
refinedweb
Hello, So after spending some time with this exercise, I have managed to get the right amount of money that should be taxed on an individual based on their income, but the issue I have is how to find the remainder cents as if the entire tax amount was a decimal value (double). Anyway, here's my code, I think I might have it, but its the 0.5 that's bugging me and I think it might be eliminated with the use of the mod operator, but I'm no sure: Code:/* 3. Write a program that defines a floating-point variable * initialized with a dollar value for your income and a * second floating-point variable initialized with a value * corresponding to a tax rate of 35 percent. Calculate * and output the amount of tax you must pay with the dollars and cents * stored as separate integer values (use two variables of type int * to hold the tax, perhaps taxDollars and taxCents). */ public class Chapter2_Exercise3 { public static void main(String[] args){ float current_income = 655550; // 45550 float tax_rate = (float)(0.35); int taxDollars = (int)(current_income * tax_rate); // This part will calculate the remainder that contains cents: double taxCents = (double)(current_income * tax_rate); System.out.println("\nHere is your current income: $" + current_income); System.out.println("\nHere is the value of tax_rate: " + tax_rate + "%"); System.out.println("\nHere is the tax you have to pay on your income: $" + taxDollars); System.out.println("\nHere is the amount of tax cents that are remaining: " + taxCents); } }
http://forums.devshed.com/java-help-9/question-determining-taxcents-remainder-951790.html
CC-MAIN-2017-09
en
refinedweb
The service discovery has a plug-able backend using the ServiceDiscoveryBackend SPI. This is an implementation of the SPI based on Redis. To use the Redis backend, add the following dependency to the dependencies section of your build descriptor: Maven (in your pom.xml): <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-service-discovery-backend-redis</artifactId> <version>3.3.3</version> </dependency> Gradle (in your build.gradle file): compile 'io.vertx:vertx-service-discovery-backend-redis:3.3.3' Be aware that you can have only a single implementation of the SPI in your classpath. If none, the default backend is used. The backend is based on the vertx-redis-client. The configuration is the client configuration as well as key indicating in which key on Redis the records are stored. Here is an example: import io.vertx.groovy.servicediscovery.ServiceDiscovery ServiceDiscovery.create(vertx, [ backendConfiguration:[ host:"127.0.0.1", key:"records" ] ])
http://vertx.io/docs/vertx-service-discovery-backend-redis/groovy/
CC-MAIN-2017-09
en
refinedweb
Your presenters don’t need all those lifecycle events MVP is the new black in AndroidDev and there’s about a billion ways to do it. One common mistake that is oft repeated is that developers keep including way too many activity/fragment lifecycle events inside their presenters ending up destroying the separation between the view and presentation layers. The benefits that MVP provides us — testing, agility and separation of concerns can only be achieved if we keep our presentation and UI layers decoupled. My fellow developers, You must try your darndest to keep those presenters Android free. So here’s what I propose Let’s have only two lifecycle related methods inside your presenters. One will be called onViewAttached and another will be it’s counterpart onViewDetached. Here’s what it looks like: public interface Presenter { void onViewAttached(MVPView view); void onViewDetached(); } All your presenters would implement this interface and in turn would have to implement these methods. Great, but when do we call them from the view? I prefer calling onViewAttached and onViewDetached during onStart and onStop respectively. This way your UI will truly be ready to be interacted with when onViewAttached is called. Here’s what that looks like: public class BaseActivity extends AppCompatActivity { @Override protected void onStart() { super.onStart(); presenter.onViewAttached(this); } @Override protected void onStop() { super.onStop(); presenter.onViewDetached(); } } All your Activities would extend from this class and would get those method calls for free. Fragments can have a similar BaseFragment class or something and extend from that. What about saving and restoring state? Here we have two options: Let the view handle state management by itself: In this case your presenter doesn’t need any extra methods and the view will handle state restoration all on it’s own. Manage state from the presenter : Here, you can have two extra methods in your BasePresenter : onSaveState and onRestoreState which would be called by onSaveInstanceState and onRestoreInstanceState respectively. You can pass the Bundle object to these methods directly. This would break our “No Android in Presenters” rule but you can mock the Bundle during tests using Mockito or the like without too much trouble. Another way is to not use the bundle at all and save state somewhere else (DB, File, Shared prefs etc) but this might be slower to retrieve and you’ll have to clean up the saved state properly when you don’t need it anymore. Go with whatever is more convenient to implement and test. But I want to know if my Activity is new or not! I hear ya. There are cases when you would need to know if your view is a new instance or an old one being re-created. This might be useful in situations where you need to do something only the first time a particular view instance is brought into the world. To achieve this, we can modify our onViewAttached method with an extra boolean parameter isNew. So our presenter interface becomes: public interface Presenter { void onViewAttached(MVPView view, boolean isNew); void onViewDetached(); } and our BaseActivity becomes public class BaseActivity extends AppCompatActivity { private boolean isNewActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(); // Check if it's a new view isNewActivity = (savedInstanceState == null); } @Override protected void onStart() { super.onStart(); presenter.onViewAttached(this, isNewActivity); isNewActivity = false; } @Override protected void onStop() { super.onStop(); presenter.onViewDetached(); } } We’re basically keeping track of a new instance creation in the Activity itself and passing this to the presenter whenever it’s attached. I have a use case that needs more lifecycle events! Great. Then add them in. I won’t claim that these 2 lifecycle events address every use case in the world and you might occasionally need more of them. When you do need them however, just make sure you’re being careful and not overdoing it. Conclusion MVP — good. Too many lifecycle events in presenters — bad. If you liked this, click the💚 below so other people will see this here on Medium. For more musings about programming, follow me so you’ll get notified when I write new posts.
https://medium.com/@anupcowkur/your-presenters-dont-need-all-those-lifecycle-events-721f500eeef4
CC-MAIN-2017-09
en
refinedweb
SqlCommand.BeginExecuteReader Method (CommandBehavior) Assembly: System.Data (in system.data.dll) Parameters - behavior One of the CommandBehavior values, indicating options for statement execution and data retrieval. Return ValueAn IAsyncResult that can be used to poll, before the command's execution is completed causes the SqlCommand object to block until the execution is finished. The behavior parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's OR operator); generally, developers use the CommandBehavior.CloseConnection value to make sure that the connection is closed by the runtime when the SqlDataReader is closed. Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the IsCompleted property value. Once the process has completed, the code retrieves the SqlDataReader and displays its contents. This example also passes the CommandBehavior.CloseConnection and CommandBehavior.SingleRow values in the behavior parameter, causing the connection to be closed with the returned SqlDataReader is closed, and to optimize for a single row result. using System.Data.SqlClient; class Class1 { static void Main() { // This example is not terribly useful, but it proves a point. // The WAITFOR statement simply adds enough time to prove the // asynchronous nature of the command. string commandText = "WAITFOR DELAY '00:00:03';" + "SELECT ProductID, Name FROM Production.Product WHERE ListPrice < 100";. try { // The code does not need to handle closing the connection explicitly-- // the use of the CommandBehavior.CloseConnection option takes care // of that for you. SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(commandText, connection); connection.Open(); IAsyncResult result = command.BeginExecuteReader( CommandBehavior.CloseConnection); // Although it is not necessary, the following code //); } using (SqlDataReader reader = command.EndExecuteReader(result)) { DisplayResults(reader); } } void DisplayResults(SqlDataReader reader) { // Display the data within the reader. while (reader.Read()) { // Display all the columns. for (int i = 0; i < reader.FieldCount; i++) { Console.Write("{0}\t", reader.GetValue(i)); } Console.WriteLine(); } }.
https://msdn.microsoft.com/en-us/library/kddf8ah6(v=vs.85)
CC-MAIN-2017-09
en
refinedweb
I want to get a list containing all different tag names of a HTML document (a list of string of tag names without repetition). I tried putting empty entry with soup.findall() r = request.get() data = r.text soup = BeautifulSoup(data,'html.parser') Using soup.findall() you get a list of every single element you can iterate over. Therefore you can do the following: from bs4 import BeautifulSoup> """ # an html sample soup = BeautifulSoup(html_doc, 'html.parser') document = soup.html.find_all() el = ['html',] # we already include the html tag for n in document: if n.name not in el: el.append(n.name) print(el) The output of the code snippet would be: >>> ['head', 'title', 'body', 'p', 'b', 'a'] As @PM 2Ring Pointed out there, if you don't care about the order in which the elements are added (which as he says I don't think it is the case), then you may use sets. In Python 3.x you don't have to import it, but if you use an older version you may want to check whether it is supported. from bs4 import BeautifulSoup ... el = {x for x in document} # use a set comprehension to generate it easily el.add("html") # only if you need to
https://codedump.io/share/wGYX0G5T2vwm/1/list-of-all-element-names-in-html-document--beautifulsoup
CC-MAIN-2017-09
en
refinedweb
Sorting listview ListView (and the default GridView view) is a great bare bones control for us to add extra functionality – though sorting out of the box would have been handy. On the face of it, sorting is easy – you handle the click of the header and call Sort on the collection being bound to using the property of the header just clicked. What could be hard about that? Welllll, there are two problems. Firstly, you would like to make the sorting process generic rather than either repeating code for each header for each grid Secondly, you need to know which property to actually sort on and which direction. The reason that you don’t always know the property is due to the fact that the property may be in some arbitary point inside a template defined for the column. Attached properties are the answer to both these problems, as well as a custom GridViewColumn child class. For problem one, define an attached property to add sorting functionality and then add to the listview definition , like so: <ListView Name="lvItems" gu:IsGridSortable="True" Then to solve problem two, use the derived GridViewColumn class like so: <gu:SortableGridViewColumn The SortProperty property enables you to specify the property that needs to be sorted very easily Where gu is a xmlns definition to point to your namespace where your new attached property class lives. Luckily , for you and me, someone has kindly created just such classes, just check out Joel Rummerman’s blog: You will see on his blog that if you define two styles with keys HeaderTemplateArrowDown and HeaderTemplateArrowUp then that style will be shown in the header as well. So if they are triangles, the header will show them, which is great. For the listview sorting itself, take a look at the attached property implementation by Mike Brown, at his blog:  Comment on this Post
http://itknowledgeexchange.techtarget.com/wpf/sorting-listview/
CC-MAIN-2017-09
en
refinedweb
Welcome to follow me on GitHub or GoldWelcome to follow me on GitHub or Gold GitHub: Gold: AndroidInterview-Q-AAndroidInterview-Q-A Some of the questions (along with their answers) related to android and java asked in top notch companies. JavaJava Significance of InterfaceSignificance of Interface - Specification - Extension - Callback The significance of an abstract classThe significance of an abstract class - Provide a common type of its subclasses - Encapsulation subclasses of duplicate content - To define abstract methods The role of the inner classThe role of the inner class - The inner class can use multiple instances of each instance has its own state information, and information with other peripheral objects are independent of each other. - Outside of a single class, allows multiple inner class to implement the same interface in different ways, or the same class inheritance. - Create inner class object moment does not depend on peripheral class object creation. - Inner classes is not confusing "is - a"relationship, it is an independent entity. - Inner class provides better encapsulation, in addition to the outer class, other class cannot access Does static method can be overriden?Why or why not?Does static method can be overriden?Why or why not? No we can't override static methods. Subclass inherits the parent class, use the same method of static and non-static methods, then non-static methods covered in the parent class method (namely rewriting), the static method of the parent is hidden (if the object is the parent class is called the hidden method), the other a subclass inherits the parent class of the static and non-static methods, as for the method overloading I think it is one of the elements in the same class, can't say what the parent class method and what method in a subclass is the embodiment of the method overloading Major sorting algorithims and their implementation in JavaMajor sorting algorithims and their implementation in Java These can be found here in this blog - P.S- If you don't understand chinese then please translate blog to your local language. Enumerate the Java collection and inheritance relationshipsEnumerate the Java collection and inheritance relationships What are the important characteristics of the Java virtual machineWhat are the important characteristics of the Java virtual machine An important feature of the Java language is with platform independence.While using the Java virtual machine is the key to achieve this feature.The general high-level language if you want to run on different platforms, at least needs to be compiled into different object code.And after the introduction of Java virtual machine, the Java language runtime on different platforms do not need to recompile.Java language usage patterns Java virtual machine blocked information related to the specific platform, makes the Java language compiler to generate the Java virtual machine to run the target code (byte code), you can run on multiple platforms without modification.Java virtual machine when performing the bytecode, explain the bytecode into concrete platform machine instruction execution. Which object will be rid of garbage collectionWhich object will be rid of garbage collection The Java garbage collection mechanism is the most basic way is to generational collection.In memory area is divided into different generations, object according to its survival time is saved in the corresponding generation area.The general implementation is divided into three generation: young, old and permanent.Memory allocation is occurred in the young generation.When an object survival time long enough, it will be copied to the older generation.For different generations can use different garbage collection algorithm.Divides the starting point is the generation of application objects to study the survival time of statistical rule.In general, an application of most objects in the survival of the time is very short.Such as the survival of the local variable time is only the execution of the method.Based on this, the young generation garbage collection algorithm can be targeted. What is the difference between threads and processesWhat is the difference between threads and processes In short, a program of at least one process, a process of at least one thread.The thread dimension is less than the process of dividing, making high concurrency multithreaded program.In addition, the process is in the process of execution has an independent memory unit, and multiple threads to Shared memory, thus greatly improve the efficiency of the program.Threads in the process of execution and process or is there a difference.Each individual threads run a program entry, order execution sequence and the procedure of exports.But the threads will not be able to independently execute, must depend on application, provide multiple threads execute control by the application.From a logical point of view, a multithreaded significance lies in an application, there are multiple execution part can perform at the same time.But were not operating system with multiple threads as multiple independent applications, to realize the process of scheduling and management, and resource allocation.This is the important distinction between the threads and processes.Process is a certain independent function of the program on a run on one of the data collection activities, resource allocation and scheduling process is the system of an independent unit.Thread is a process of an entity, is the basic unit of the CPU scheduling and dispatching, which is smaller than the process of the basic unit of the can run independently. Thread basically does not own system resources, have only a little in operation of essential resources (such as the program counter, a set of registers and stack), but it can be to belong to a Shared other threads of a process possesses all the resources.A thread can be created and revoke another thread;Between the multiple threads in the same process can execute concurrently.Process and thread main difference is that they are the different ways of operating system resources management.Process has its own address space, a process after the collapse, in protected mode will not affect other processes, and in the process of the thread is just a different execution path.Thread has its own stack and local variables, but no single address space between thread, a thread die die is equal to the whole process, so the multi-process program than in a multithreaded program, but in the process of switching cost resources is bigger, the efficiency is less.But for some requirements and at the same time and again to share some of the variables of concurrent operation, can only use threads, cannot use process.If you are interested in further, I suggest you look at the modern operating systems or the design and implementation of the operating system.Said to is a problem more clearly. Difference between == && equals() in javaDifference between == && equals() in java What are the time complexities of common sorting algorithmsWhat are the time complexities of common sorting algorithms What is a HashMap implementation principleWhat is a HashMap implementation principle - A HashMap overview: HashMap is based on the hash Map interface of asynchronous implementation.This implementation provides all of the optional mapping operations, and allows the use of null values and null keys.Such does not guarantee the order of the map, in particular, it does not guarantee that the constant sequence. - The data structure of a HashMap: In the Java programming language, the basic structure is two kinds, one is an array, and another is to simulate a pointer (reference), all of the data structure can be used both to construct the basic structure, HashMap is no exception.HashMap is actually a "linked list hash data structure, which is a combination of array and chain table. Define Java state machineDefine Java state machine How many bits and bytes does each of short, int, long, char, float, double contains in JavaHow many bits and bytes does each of short, int, long, char, float, double contains in Java 1 byte contains 8 bits, therefore short - 16 bits or 2 bytes int - 32 bits or 4 bytes long - 64 bits or 8 bytes float - 32 bits or 4 bytes double - 64 bits or 8 bytes char - 16 bits or 2 bytes What is the difference between int and an Integer in JavaWhat is the difference between int and an Integer in Java What is the Difference between string, stringbuffer and stringbuilderWhat is the Difference between string, stringbuffer and stringbuilder String String constants StringBuffer A string variable(Thread safe) StringBuilder A string variable(Not thread-safe) In short, the type String and StringBuffer types of main performance difference is that the String is an immutable object, so in when to change the type String is equal to generate a new String object, then the pointer to a new String object, so often it is best not to change the contents of the String with a String, because every time generated objects will have an effect on system performance, especially when memory without much reference object, the JVM GC will start to work, that is will be a rather slow speed. And if it is to use StringBuffer class the result is different, every time the results to StringBuffer object itself, rather than generating new objects, then change the object reference.So in general we recommend StringBuffer, especially a string object changes often.And in some special cases, the String object String concatenation is explained by the JVM became StringBuffer object, so when the String object than StringBuffer object will not be slow, and in particular, in which of the following String objects generated String efficiency is far faster than StringBuffer: String S1 = “This is only a” + “ simple” + “ test”; StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”); You will be surprised to find that generated String S1 object speed is too fast, and this time StringBuffer incredibly speed is not dominant.This is a trick of the JVM, in the eyes of the JVM, the String S1 = “This is only a” + “ simple” + “test”; In fact is: String S1 = “This is only a simple test”; So, of course, don't need too much time.But everyone here to note is that if you have a String is a String object from another, is not so fast, such as: String S2 = “This is only a”; String S3 = “ simple”; String S4 = “ test”; String S1 = S2 +S3 + S4; At that time the JVM will behave according to the original way to do it In most cases StringBuffer > String StringBuffer java.lang.StringBuffer thread safe variable character sequence. A similar String String buffer, but cannot be modified. Though at any point in time it contains some specific sequences of characters, but through certain method calls can change the length of the sequence and content. A string buffer can be safely used in multiple threads. Can be in when necessary to synchronization of these methods, therefore all operations on any particular instance as if in a serial order, the order and method invocations of each thread order. Are the major operating on the StringBuffer append and insert method, can override these methods, to accept any type of data.Each method can effectively to the given data into a string, then the string of characters added or inserted into the string in the buffer.These characters of append method will always add it to the end of the buffer;While the insert method add character at the specified point. If z refer to a current contents, for example, is "start" string buffer object, then this method calls z.a ppend (" le ") can make the string buffer includes "tackle", while z.i nsert (4, "le") will change the string buffer, to include the "starlet. In most cases StringBuilder > StringBuffer java.lang.StringBuilder java.lang.StringBuilder a mutable sequence of characters is the new 5.0.This provides an API compatible with StringBuffer, but does not guarantee that synchronization.This class is designed to be used as a replacement of a simple StringBuffer, when used in string buffer is used by a single thread (this is very common). If possible, it is recommended that the priority use this class, because in most implementations, it is faster than StringBuffer.Both methods are basically the same. Explain polymorphism in JavaExplain polymorphism in Java The understanding of Java polymorphism Java realization of polymorphism What is a polymorphism? Object-oriented programming has three features: encapsulation, inheritance and polymorphism. From a certain perspective, encapsulation and inheritance are almost for state. This is our last concept, which is the most important for knowledge as an android developer. The definition of polymorphism refers to allow different kinds of objects to respond to the same news.The same message can be according to difference of sending objects and use a variety of different ways of behavior (send a message is a function call). Polymorphism of the technology, called: dynamic binding (dynamic binding), refers to judgment during the execution of the actual type of reference objects, according to its actual type call the corresponding method. The role of polymorphism: eliminate the coupling relationship between the types. In reality, examples of polymorphism. If we press the F1 key action, for example, the current in the pop-up Flash screen is AS 3 help documentation;If the current pop-up is Word then it display "help" under the Word;Under the Windows is a pop-up Windows help and support. The same event will produce different results in different objects. Here are three necessary conditions for the existence of polymorphism Three necessary conditions for the existence of polymorphism *inherited; *rewrite; *The parent class reference is to subclass object。 Benifits of Polymorphism: Replaceability (substitutability).Polymorphism with replaceability to existing code.Polymorphism of Circle Circle kind of work, for example, to any other Circle geometry, such as Circle, also work. Scalability (extensibility).Polymorphism has scalability to the code.Add new subclass does not affect existing class polymorphism, inheritance, and other characteristics of run and operation.New subclasses are more likely to actually get polymorphic function.For example, in the realization of the cone, cone and half sphere of polymorphism, it is easy to add ball class polymorphism. Interface (interface - ability).Polymorphism is the superclass method signature by to subclass provides a common interface, by subclasses to refine or cover it.As shown in figure 8.3.The Shape CSL class defines two implementations of polymorphic interface methods, computeArea () and computeVolume ().Subclasses, such as Circle and Sphere in order to achieve the polymorphism, perfect or covering the two interface methods. Flexibility (flexibility).It embodies the operation of flexible in application, improve the efficiency. Simplify (simplicity).Polymorphic simplify the coding of application software and modification process, especially in dealing with a large number of operation and operation of the object, this feature is particularly prominent and important. Java realization of polymorphic methods: interface implementation, rewrite the inheritance of the parent class method, in the same class method overloading. What causes thread blockWhat causes thread block The blocking of the thread: In order to solve the conflict of access to the Shared storage area, Java synchronization mechanism was introduced, now let's examine multiple threads access to Shared resources, synchronization mechanism has obviously not enough, because the resources required at any time may not ready to be accessed, in turn, the same time ready resources can be more than one.In order to solve the problem of this kind of access control, Java's support for blocking mechanism is introduced. Blocking refers to suspend the execution of a thread to wait for a condition (such as a resource in place), studied the operating system's classmate of it must have been very familiar with.Java provides a number of ways to support block, let's analyze them one by one. - Sleep() methods: sleep() allows you to specify a period of time in milliseconds as a parameter, it makes the thread into the blocked state within a specified time, can't get the CPU time, the specified time, the thread back into the executable.Typically, the sleep() is used in waiting for a resource ready: test found that when conditions are not fulfilled, the thread block after a period of time to test, until a condition is met. - Suspend() and resume() method: two methods, suspend() makes the thread into the blocking state, and does not automatically restore, must have its corresponding resume() is called, to make the thread back into the executable.Typically, suspend() and resume() is used in waiting for the result of a another thread: after tests found that the result has not produced, let the thread block, another thread produced results, calls resume() to make it recover. - Yield() method: the yield() allows a thread to abandon the current share of CPU time, but don't make the thread block, the thread is still in the executable state, could share of CPU time again at any time.Call the yield() is equivalent to the effect of the scheduler that the thread has been carried out enough time to go to another thread. - Wait() and notify() method: two methods are used, wait() makes the thread into the blocking state, it has two forms, one allows you to specify a period of time in milliseconds as a parameter, another has no parameters, the former when the corresponding notify() is invoked or beyond the specified time back into the executable thread state, the latter must correspond to the notify() is invoked. At first glance, suspend() and resume() method looks no different, but in fact they are very different. The core difference is that in front of the narrative method of all blocked will not release takes lock (if takes up), and the opposite each other. The core difference between them led to a series of the difference on the details. First of all, in front of the narrative of all methods belongs to the Thread class, but the pair of directly affiliated to the Object class, that is to say, all objects with the two methods.At first glance it is quite incredible, but in fact it is very natural, because it blocked a method to release takes up the lock, the lock is any object, invoke arbitrary objects of wait() method of thread blocks, and the lock of the object is released.Object and calling any notify() method to call on the object of the wait() method and random selection in the blocked thread a unblocked (but have to wait until after the lock truly executable). Second, the narrative of all method calls can be in any position, but the two methods must be in a synchronized method or block calls, reason is very simple, only in a synchronized method or block the current thread holds locks, lock can be released.In the same way, call this method on the object lock must be owned by the current thread, so you can release a lock.As a result, the pair of method calls must be placed in such a synchronized method or block, the method or block the locked object is to call this method.If they do not meet the conditions, the program, though still able to compile, but abnormal IllegalMonitorStateException at run time. Wait() and notify() method of the above features determines they often use, together with a synchronized method or block them and inter-process communication mechanism of the operating system you will find a comparison of their similarities: a synchronized method or block provides a similar to the function of the operating system primitives, their execution will not be multi-threaded mechanism of the interference, and the laws of the other party is equal to the block and wakeup primitives (the two methods are declared as synchronized).They allow us to realize the combination of the operating system on a series of subtle interprocess communication algorithm (e.g., semaphore algorithm), and is used to solve the problem of all kinds of complex communication between threads. About the wait() and notify() method and then two points: First: call notify() method to remove blocked thread from object by calling the wait() method and random in blocked thread, we cannot predict which thread will be selected, so to be very careful when programming, to avoid the problem due to the uncertainty. Second: in addition to notify(), and a method of notifyAll() can also play a similar role, the only difference is that the notifyAll() method will turn the object by call wait() method and block all the threads of disposable is unblocked.Of course, only get a lock that a thread can enter the executable. When it comes to block, that is to talk about a deadlock, slightly analysis can be found that suspend() method and do not specify a timeout period of wait() method calls are likely to produce a deadlock.Unfortunately, the Java does not support in the language level to avoid deadlock, we must be careful to avoid deadlock in the programming. Above we implemented in Java thread blocking the various methods for the analysis, we analyzed the wait() and notify() method, because they are the most powerful, use is also the most flexible, but it also leads to low efficiency, the more error prone.We should be flexible use of various methods in practical use, in order to better achieve our purpose. What is the difference between an abstract class and interfaceWhat is the difference between an abstract class and interface The realization of the default method: An abstract class can have a default method is completely abstract.The realization of the interface method doesn't exist Implementation: Subclasses use the extends keyword to inherit an abstract class.If a subclass isn't an abstract class, it will need to provide all the methods declared in the abstract class.A subclass to implement the interface with the keyword implements.It will need to provide all the methods declared in the interface implementation - The constructor: An abstract class can have a constructor,Interface can not have a constructor - The difference between the interface and the normal Java classes: Besides you cannot instantiate an abstract class, it and ordinary Java classes without any difference The type of interface is completely different - Access modifiers: Abstract methods can be public, protected, and the default these modifiers The default modifier is public interface methods.You can not use other modifiers. - The main() method Abstract method can have the main method and we can run it Interface is not the main method, so we can't afford to run it. - Multiple inheritance Abstract classes in the Java language is a kind of inheritance, said in a subclass is only one parent, but there can be multiple interfaces. - Speed Abstract class are faster than interfaces Interface is a little slow, because it need time to find the method to realize in the class. - Add new methods If you have to add a new method in an abstract class, you can give it the default implementation. So you don't need to change your code now. If you added a new method to the interface, then you have to change the class implementation of that interface. What is the difference between container classesWhat is the difference between container classes For english readers: Define Inner classes in JavaDefine Inner classes in Java For english language users: What is HashMap?Differentiate between a HashMap and HashTable in JavaWhat is HashMap?Differentiate between a HashMap and HashTable in Java For english language users: Differentiate between ArrayMap and HashMapDifferentiate between ArrayMap and HashMap AndroidAndroid What types the operation of the database, how to import the external databaseWhat types the operation of the database, how to import the external database The original database is included in the project source res/raw Under the android system should be stored in a database/data/data/com. *. * (package name)/directory, so we need to do is to put the existing database into the directory. Operation method is to use FileInputStream read the original database, reoccupy FileOutputStream your read write to that directory. Whether used the local radio, and what is the difference between a global broadcastWhether used the local radio, and what is the difference between a global broadcast Because of radio data transmission in the application scope, don't have to worry about privacy data leakage problems. Don't have to worry about other application forge the broadcast, cause potential safety hazard. Compared to send global broadcast in the system, it is more efficient. Have you used intentService? What is the function of intentService? Does AIDL has solved the problemHave you used intentService? What is the function of intentService? Does AIDL has solved the problem To generate a default and independent of each other than the main thread to execute all sent to onStartCommand () method of Intetnt. Generate a work queue to send Intent object to your onHandleIntent () method, the same time send an Intent object, only in this way, you don't have to worry about multi-threading.In all request (Intent) was performed after will automatically stop the service, so you shouldn't have to call stopSelf () method to stop. The service provides a onBind() method of the default implementation, it returns null Provides a onStartCommand() method of the default implementation, it will be the Intent to transfer to the work queue, and then from the work queue every time a transmitted onHandleIntent () method, in the method of Intent on corresponding processing. AIDL (Android Interface Definition Language) is a kind of IDL Language, is used to generate on Android devices can be interprocess communication between two processes (interprocess communication, IPC) code.If in a process (such as activities) to invoke another object (e.g., Service) in the process of operation, you can use AIDL generates serializable parameters. AIDL IPC mechanism is an interface, like COM and Corba, but more lightweight.It is to use the proxy class transfer data on the client and implementation. What is the difference between an Activity, the Window, and the View? What are some of the characteristics of the fragmentsWhat is the difference between an Activity, the Window, and the View? What are some of the characteristics of the fragments Activity as a craftsman (control unit), the Window like a Window (carrying model), the View like a paper-cut (display View) LayoutInflater like scissors, Xml configuration like window drawings. - Calls to attach in the Activity, to create a Window - Create a window is its subclasses PhoneWindow, create PhoneWindow in the attach - Call in the Activity setContentView(R.layout.xxx) - Which is actually call getWindow().setContentView() - Call of the setContentView PhoneWindow method - Create ParentView As a subclass of ViewGroup, is actually a DecorView create (as a subclass of FramLayout) - For filling out will specify the R.l ayout. XXX college through the layout filler filler (including the parent means DecorView) - Calls to a ViewGroup - Invoke the ViewGroup removeAllView(), all of the first view to remove - Add a new view: addView() Characteristics of fragments: - Fragments can be used as the Activity of part of the interface - Can appear many fragments at the same time, in an Activity and a fragments can also be used in more than one Activity - In the process of Activity operation, can add, remove or replace the fragments - Fragments can respond to their own input events, and has its own life cycle, their life cycle will be affected by the host of the Activity lifecycle What is the difference between Handler, Thread and HandlerThreadWhat is the difference between Handler, Thread and HandlerThread Thread from the Android (Java. Lang. Thread - > Java. Lang. Object) description can be seen that the Android Thread in Java Thread to do no encapsulation, but Android provides a inheriting from the Thread class HandlerThread (Android. OS. HandlerThread - > Java. Lang, Thread), the class of Java Thread did a lot of convenience Android encapsulation. Android. The OS. The Handler can be instantiated by which objects, and running in other threads, android provides for Handler thread running in other threads, is also a HandlerThread.HandlerThread start can be obtained after the stars object, and using this Handler which object instance. Low version of the SDK to achieve high version of the APILow version of the SDK to achieve high version of the API Implement it myself or @ TargetApi annotation Ubuntu compiled androidUbuntu compiled android - Enter the source root directory - . build/envsetup.sh - lunch - full(Compile all) - userdebug(Select compiler version) - make -j8(Open eight compilation thread) Describe various launch mode Application scenariosDescribe various launch mode Application scenarios Standard, create a new Activity. SingleTop, stack is not the type of Activity, to create a new Activity.Otherwise, onNewIntent. SingleTask, back up the stack without this type of Activity, to create the Activity, otherwise, onNewIntent + ClearTop. Note: - Set the startup mode "singleTask" Activity, when it is launched, affinity will first look for in the system attribute value is equal to the Task that it taskAffinity attribute values exist;If there is such a Task, it will start in this Task, or it will start in the new Task stack.So if we want to set the boot mode "singleTask" Activity start in a new mission, for it set up an independent taskAffinity attribute values. - If set the startup mode "singleTask" Activity is not started in the new task, it will check whether already exists in the existing task corresponding Activity instance, if present, will be put in the end of this Activity instance Activity above all, namely the Activity instance will end up in the task of the top of the Stack. - In a task stack only a "singleTask" startup mode of Activity.He can have other Activity.There is a difference between this and singleInstance. SingleInstance, back up the stack, only that an Activity, there is no other Activity. SingleTop is suitable for receiving notifications start according to the content of the page. For example, a client's news news content page, if you receive 10 news feeds, open a news content page every time, it is very annoying. Serve as singleTask program entry point. For example, the browser's main interface.No matter how many applications from launch a browser, it will only start the main interface once, the rest will go onNewIntent, and clears the main interface on other pages. SingleInstance application scenarios: The alarm bell ring interface.You used to set up an alarm: six o 'clock in the morning.58 points at 5 o 'clock in the morning, you start the alarm Settings interface, and press the Home button back to the desktop;At 59 to 5 in the morning, you at WeChat and friend chat;At 6 o 'clock, when the alarm rang, and pop up a dialog box in the form of Activity (called AlarmAlertActivity) prompts you to 6 (this Activity is to SingleInstance loading mode to open), you press the return key, back is WeChat chat interface, this is because the AlarmAlertActivity stack of the Task is only one element, he therefore exit after the Task stack is empty.If is AlarmAlertActivity SingleTask open, so when the alarm is ringing, press the return key should alarm set into the interface. Describe Touch event delivery processDescribe Touch event delivery process How the view drawing process worksHow the view drawing process works How to use Multithreading in AndroidHow to use Multithreading in Android - Activity.runOnUiThread(Runnable) - View.post(Runnable),View.postDelay(Runnable,long) - Handler - AsyncTask Describe Thread synchronization process in AndroidDescribe Thread synchronization process in Android singleton public class Singleton{ private volatile static Singleton mSingleton; private Singleton(){ } public static Singleton getInstance() { if(mSingleton == null) { \\ A synchronized(Singleton.class) { \\ C if(mSingleton == null) { mSingleton = new Singleton();\\ B } } } return mSingleton; } What are causes of the memory leakWhat are causes of the memory leak - A memory leak caused by resource object is not closed Resource objects such as Cursor, File documents, etc.) are often used some buffer, when not in use, we should close them in time, so that their timely recovery of memory buffer.Their buffer not only exists in the Java virtual machine, also exists in the Java virtual closed.If we just put it in the reference set to null, and do not close them, tend to cause a memory leak.Because some resource objects, such as SQLiteCursor (in the destructor finalize (), if we don't close it, it will adjust the close (closed), if we don't close it, system will close it when recycling it, but the efficiency is too low.So for resource object when not in use, should call it the close () function, will close it out, and then set to null. When exiting in our program must ensure that our resource object has been closed.Programs often to query the database operation, but often have completed used without shut down after the Cursor.If our query result set is small, the memory consumption is not easy to find, often the only time a large number of operating case retrieval memory problems, it will bring to screening tests and problems later difficulties and risks. - Construct the Adapter, without using a cache convertView To construct the ListView BaseAdapter, for example, in the BaseAdapter provides methods:Public View getView (int position, ViewconvertView, ViewGroup parent)Give ListView view objects needed for each item.Initial ListView will based on the current screen layout from BaseAdapter instantiate a certain number of view objects, at the same time the ListView will the view object cache.When the scroll up to ListView, originally located at the top of the list item of view objects will be recycled, is then used to construct new appear at the bottom of the list item.The construction process is the getView () method, getView () the second parameter of the View convertView is cached item in the list are of the View object (initialization time the cache does not View objects convertView is null).Thus it can be seen that if we don't use convertView, but each time the getView () to instantiate a View object, namely the waste of resources and waste of time, will also make the memory footprint is more and more big.ListView to recycle the list view object process can view the item:Android. Widget. AbsListView. Java -- > voidaddScrapView (View scrap) method. The sample code: public View getView(int position, ViewconvertView, ViewGroup parent){ View view= new Xxx(...); // ... ... return view; } Revised sample code: public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (convertView !=��null) { view = convertView; populate(view, getItem(position)); // ... } else { view=new Xxx(...); // ... } return view; } - Bitmap object when not in use call recycle() free memory Sometimes we manual operation Bitmap object, if a Bitmap object comparison of memory, when it is not used, can call the Bitmap. The recycle () method to recycle the object pixels of the memory, but it is not necessary, as the case may be.May I see the comments in the code: /** •Free up the memory associated with thisbitmap's pixels, and mark the •bitmap as "dead", meaning itwill throw an exception if getPixels() or •setPixels() is called, and will drawnothing. This operation cannot be •reversed, so it should only be called ifyou are sure there are no •further uses for the bitmap. This is anadvanced call, and normally need •not be called, since the normal GCprocess will free up this memory when •there are no more references to thisbitmap. */ - Try to use the context of the application to replace the context related to the activity This is a very obscure memory leaks.There is a simple way to avoid the context related to the memory leak.The most significant one is to avoid the context to escape from outside the scope of his own.Use the Application context.The context of the life cycle and the application of life cycle, you are long, instead of depending on the activity lifecycle.If you want to keep a long-term survival of object, and this requires a context object, remember to use the application object.You can call the Context. GetApplicationContext () or Activity. GetApplication ().More look at how to avoid this articleAndroid memory leaks. - Registered didn't cancel cause memory leaks Some Android program may refer to our Android objects (such as registration mechanism).Even though our Android program has ended, but the other reference program is still on our Android applications of an object reference, leak memory still cannot be garbage collected.After calling registerReceiver unregisterReceiver did not call.For example, suppose that we want in the lock screen interface (LockScreen), listen to telephone services in order to get some information in the system (such as the signal strength, etc.) can be defined in LockScreen a PhoneStateListener object, register it into the TelephonyManager service at the same time.For LockScreen object, when need to display the lock screen interface can create a LockScreen object, and when the lock screen interface disappeared LockScreen object will be released. But if at the time of release LockScreen object forget cancel before we register PhoneStateListener object, leads to LockScreen cannot be garbage collected.If constantly make the lock screen interface display and disappear, will eventually because of a large number of LockScreen object can't be recycled and cause OutOfMemory, make system_process process hang up.Although some system program, it can itself seems to be cancelled automatically registered (not in time, of course), but we should be clear in our programs to cancel the registration, at the end of the program should cancel all registered. - Collection of objects not clean up the cause of memory leaks We usually add some reference to the collection, when we don't need this object, did not make it a reference from the collection, so that this collection will be bigger and bigger.If this set is static, the situation is more serious. ANR positioning and correctionANR positioning and correction If development machine appear problem, we can by looking at the/data/anr/traces. TXT, the latest anr information in the first part. - The main thread is IO operations (from 4.0 after network IO is not allowed in the main thread) obstruction. - The main thread of time-consuming calculation - The wrong operation in the main Thread, such as Thread. Wait or Thread. Sleep, etcThe Android system will monitor the response of the situation, once appear, the following two cases, the pop-up ANR dialog - Application in 5 seconds did not respond to user input events (such as buttons or touch) - BroadcastReceiver not complete relevant processing in 10 seconds Service in a particular time to handle complete 20 seconds Use AsyncTask processing time consuming IO operations. - Using Thread or HandlerThread, call Process. SetThreadPriority (Process. THREAD_PRIORITY_BACKGROUND) set priority, or still can reduce response Process, because the default Thread priority is the same as the main Thread. - Using Handler Thread processing results, rather than using Thread. The wait () or Thread. The sleep () to block the main Thread. - The Activity's onCreate and onResume avoid time-consuming code in a callback - The BroadcastReceiver onReceive code also want to minimize the time consuming, it is recommended to use IntentService processing. Android Memory optimationzan TechniquesAndroid Memory optimationzan Techniques 1)Use more lightweight data structure 2)Android use Enum inside 3)Bitmap object memory footprint 4)The bigger picture 5)Ontouch method perform object created inside 6)StringBuilder What are some of modes of communication between Android Service with the ActivityWhat are some of modes of communication between Android Service with the Activity - Through a Binder object - Through the broadcast in the form of (radio) The difference between Android API versionsThe difference between Android API versions Implementation in the Android WAP way connected to the InternetImplementation in the Android WAP way connected to the Internet How to ensure that the service does not get killed in backgroundHow to ensure that the service does not get killed in background Return to START_STICKY onStartCommand method START_STICKY After running after onStartCommand service process is the kill, it will be held at the beginning, but don't keep the incoming intent.Shortly after the service will try to create again, because in the start state, call onstartCommand will ensure that after creating the service.If not pass any start command to the service, it will get to null intent. START_NOT_STICKY After running after onStartCommand service process is the kill, and there is no new intent passed to it.State of the Service will be removed from the start, and until the new obvious way startService () call to recreate.Because if you don't pass any pending intent so the service is not started, namely during onstartCommand will not receive any null intent. START_REDELIVER_INTENT After running after onStartCommand service process is the kill, system will restart the service, and passed the last intent to onStartCommand.Didn't stop until the call stopSelf (int) passed the intent.If is in after the kill and untreated good intent, the service will start automatically after being the kill.Therefore, onstartCommand will not receive any null intent. *Improve the service priority In AndroidManifest. XML file for intent - can filter through the android: priority = "1000" this attribute sets the highest priority, 1000 is the highest, if the number is smaller, the lower the priority, suitable for broadcast at the same time. *Improve the service process priority Android is managed in the process, when the system process space is tight, will be in accordance with the priority automatically the process of recovery.Android process can be divided into six grades, they in priority order from high to low in turn is: - Foreground process - The visual process - Secondary service process - Background processes - Content supply nodes - An empty process When the service running in low memory conditions, will kill off some existing process.So the process priority will be very important, you can use startForeground put the service in the front desk.When the low memory so kill probability is lower. *Restart the service in the onDestroy method Service + broadcast mode, that is, when the service go ondestory, send a custom broadcast, when the received radio, restart the service; *Application add Persistent property *Monitoring system broadcasts to judge the Service state Through some broadcasting system, such as: mobile phone restart, interface sensei, application state changes, and so on to monitor and capture, then judge whether our Service also live, don't forget to add permissions. Requestlayout onlayout, ontouch, DrawChild differences and their relationshipRequestlayout onlayout, ontouch, DrawChild differences and their relationship RequestLayout() method, can lead to call measure () process and layout () process.Description: just back to the View tree layout layout process includes the measure () and layout () procedure, don't call the draw () procedure, but not redrawnAny view including the caller itself. OnLayout() method (if the View is ViewGroup object, you need to implement the method, for each child View layout) Calling ontouch() method draw View itself (each View to override this method, ViewGroup don't need to implement the method) DrawChild() to the callback for each child view the draw () method What is the difference between invalidate() and postInvalidate()What is the difference between invalidate() and postInvalidate() How Android animation framework worksHow Android animation framework works Animation framework defines transparency, rotate, scale and displacement of several common Animation, and control the whole View, the realization principle is every time map View in the View of ViewGroup drawChild function to get the View the Animation of the Transformation of value, and then call canvas. The concat (transformToApply. GetMatrix ()), through the matrix operations complete Animation frames, if there is no complete Animation, continue to call invalidate () function, start the next map to drive the Animation, Animation in the process of clearance between the frame time is consumed by a mapping function, may cause Animation consume more CPU resources, the most important thing is, Animation change just show, and not the corresponding event. Android for each application allocated memory size is itAndroid for each application allocated memory size is it It varies with screen size and android versions, however the android program memory is generally limited to 16 mb as in android 4.1. Describe View refresh mechanism in AndroidDescribe View refresh mechanism in Android Object by ViewRoot performTraversals () method calls the draw () method to draw the tree View, it is worth noting that every time a drawing, does not redraw each View tree View, and will only be redraw those who "need to redraw the View, the View class internal variable contains a sign DRAWN, when the View needs to redraw, will be for the View to add the logo. Call the process: mView.draw() began to draw,draw() methods the functions as follows: - Draw the View of the background - Do some preparation for the gradient dialog operation (see 5, in most cases, do not need to change the gradient box) - Calling ontouch() method draw View itself (each View to override this method, ViewGroup don't need to implement the method) - Call dispatchDraw() method draw child views (if the View type of ViewGroup that does not contain child views, do not need to reload the method) is worth, ViewGroup class has been rewritten for us dispatchDraw() function implementation, application generally does not need to rewrite the method, but you can override the parent class function to achieve specific functions. LinearLayout contrast RelativeLayoutLinearLayout contrast RelativeLayout - RelativeLayout can let the child View call two onMeasure, LinearLayout in weight, also can call onMeasure View2 times - RelativeLayout child View if different height and RelativeLayout, will lead to efficiency, when the View is very complex, this problem will be more serious.If you can, try to use padding instead of margin. - In does not affect the levels of depth, under the condition of using LinearLayout and FrameLayout rather than RelativeLayout. Finally, consider the question of opening the contradiction, why Google to developers default has built a RelativeLayout, in using a LinearLayout DecorView on yourself.Because of the depth of the hierarchy of DecorView is known and fixed, a title bar above, below a NaRongLan.Using RelativeLayout will not reduce the levels of depth, so at this point on the root node using LinearLayout is the most efficient.And the reason for developers default has built a RelativeLayout is a hope that developers can use less as far as possible to express the View hierarchy layout to achieve optimal performance, because the View of complex nested will be a greater impact on performance. Optimization of the custom viewOptimization of the custom view In order to speed up your view, for the method called frequently, need to try to reduce unnecessary code.Begin with ontouch, need special attention should not be here to do the memory allocation, because it will lead to the GC, resulting in caton.During the initialization or animation clearance do allocate memory.Don't do memory allocation when animation is executing. You need as far as possible to reduce ontouch is called the number of times, most of the time, cause all ontouch because of call invalidate(). So please try to reduce the call invaildate() the number of times.If possible, try to call contains four parameters invalidate() method rather than no parameters invalidate().No arguments will invalidate mandatory redraw the entire view. Another very time-consuming operation is requested layout.At any time to perform requestLayout(), will make the Android UI system to traverse the entire View hierarchy to calculate the size of each View.If found conflicting values, it will need to recalculate the several times.Also need to try to keep the View hierarchy is flat, it is very helpful to improve efficiency. If you have a complex UI, you should consider writing a custom ViewGroup to perform his layout operations.With built-in view is different, the custom view can make the program simply measure the part, this avoids to traverse the entire view hierarchy to calculate the size.The PieChart example shows how to inherit the ViewGroup as part of a custom view.PieChart have child views, but it never measure them.But according to the laws of his own layout, the size of the set them directly. What are ContentProvidersWhat are ContentProviders Life cycle of FragmentsLife cycle of Fragments Volley Networking LibraryVolley Networking Library Glide LibraryGlide Library Design Patterns in AndroidDesign Patterns in Android Architecture designArchitecture design Android attribute animation featuresAndroid attribute animation features If you only need to View in the demand of the mobile, zoom, rotate and fades operation, then fill between animation is enough for the sound.But obviously, these functions is not enough to cover all of the scene, once we demand beyond the mobile, zoom, rotate and fade out of these four, to the operation of the View that filling between the animation will not be able to help us again, that is to say it in terms of function and extensible has considerable limitations, so let's take a look at between animation is not up to the scene. Notice above when I fill in the introduction animation has used "to manipulate the View", that's right, curation of animation is only able to function in the View.That is to say, we can on a Button, TextView, even a LinearLayout, or any other inherited from the View of animation component for operation, but if we want to be the object of a non View animation operation, I'm sorry, fill between animation can't help you.Some friends may feel do not understand, how could I need animation on a non View object for operation?Here I cite a simple example, for example we have a custom View, in the View of a Point object is used to manage coordinates, and then in ontouch () method is based on the Point of the object's coordinates to draw.That is to say, if we can to animation operation Point object, so the custom View of animation effects.Obviously, the animation is not have this feature, which is the first of its defects. And then fill between animation has a defect, is it can only realize mobile, zoom, rotate and fade out the four kinds of animation, that if we want can be dynamically change the background color of the View?It's a pity that we can only rely on yourself to achieve it.To put it bluntly, before filling mechanism between animation is to use hard-coded way to complete, function is the limited death, basically do not have any extensibility. Finally, fill between animation has a fatal flaw, is it just changed the display View, rather than to change the View of the real property.What does that mean?At the upper left of the screen, for instance, now there is a button, and then we through filling between animation to move it to the lower right corner of the screen, now you can go to try to click this button, click event is absolutely not trigger, because in fact this button or stay on the top left corner of the screen, just fill between animation are drawn this button in the lower right corner of the screen.
http://pythonhackers.com/p/JackyAndroid/AndroidInterview-Q-A
CC-MAIN-2017-09
en
refinedweb
Download presentation Presentation is loading. Please wait. Published byBernard Waterhouse Modified over 2 years ago 1 1 Headline Goes Here Speaker Name or Subhead Goes Here DO NOT USE PUBLICLY PRIOR TO 10/23/12 Building a Data Collection System with Apache Flume Arvind Prabhakar, Prasad Mujumdar, Hari Shreedharan, Will McQueen, and Mike Percy October 2012 2 2 Headline Goes Here Speaker Name or Subhead Goes Here DO NOT USE PUBLICLY PRIOR TO 10/23/12 Apache Flume Arvind Prabhakar | Engineering Manager, Cloudera October 2012 3 What is Flume Collection, Aggregation of streaming Event Data Typically used for log data Significant advantages over ad-hoc solutions Reliable, Scalable, Manageable, Customizable and High Performance Declarative, Dynamic Configuration Contextual Routing Feature rich Fully extensible 3 4 Core Concepts: Event An Event is the fundamental unit of data transported by Flume from its point of origination to its final destination. Event is a byte array payload accompanied by optional headers. Payload is opaque to Flume Headers are specified as an unordered collection of string key- value pairs, with keys being unique across the collection Headers can be used for contextual routing 4 5 Core Concepts: Client An entity that generates events and sends them to one or more Agents. Example Flume log4j Appender Custom Client using Client SDK (org.apache.flume.api) Decouples Flume from the system where event data is consumed from Not needed in all cases 5 6 Core Concepts: Agent A container for hosting Sources, Channels, Sinks and other components that enable the transportation of events from one place to another. Fundamental part of a Flume flow Provides Configuration, Life-Cycle Management, and Monitoring Support for hosted components 6 7 Typical Aggregation Flow 7 [Client] + Agent [ Agent]* Destination 8 Core Concepts: Source An active component that receives events from a specialized location or mechanism and places it on one or Channels. Different Source types: Specialized sources for integrating with well-known systems. Example: Syslog, Netcat Auto-Generating Sources: Exec, SEQ IPC sources for Agent-to-Agent communication: Avro Require at least one channel to function 8 9 Core Concepts: Channel A passive component that buffers the incoming events until they are drained by Sinks. Different Channels offer different levels of persistence: Memory Channel: volatile File Channel: backed by WAL implementation JDBC Channel: backed by embedded Database Channels are fully transactional Provide weak ordering guarantees Can work with any number of Sources and Sinks. 9 10 Core Concepts: Sink An active component that removes events from a Channel and transmits them to their next hop destination. Different types of Sinks: Terminal sinks that deposit events to their final destination. For example: HDFS, HBase Auto-Consuming sinks. For example: Null Sink IPC sink for Agent-to-Agent communication: Avro Require exactly one channel to function 10 11 Flow Reliability Reliability based on: Transactional Exchange between Agents Persistence Characteristics of Channels in the Flow Also Available: Built-in Load balancing Support Built-in Failover Support 11 12 Flow Reliability Normal Flow Communication Failure between Agents Communication Restored, Flow back to Normal 12 13 Flow Handling Channels decouple impedance of upstream and downstream Upstream burstiness is damped by channels Downstream failures are transparently absorbed by channels Sizing of channel capacity is key in realizing these benefits 13 14 Configuration Java Properties File Format # Comment line key1 = value key2 = multi-line \ value Hierarchical, Name Based Configuration agent1.channels.myChannel.type = FILE agent1.channels.myChannel.capacity = 1000 Uses soft references for establishing associations agent1.sources.mySource.type = HTTP agent1.sources.mySource.channels = myChannel 14 15 Configuration Global List of Enabled Components agent1.soruces = mySource1 mySource2 agent1.sinks = mySink1 mySink2 agent1.channels = myChannel... agent1.sources.mySource3.type = Avro... Custom Components get their own namespace agent1.soruces.mySource1.type = org.example.source.AtomSource agent1.sources.mySource1.feed = agent1.sources.mySource1.cache-duration = 16 Configuration agent1.properties: # Active components agent1.sources = src1 agent1.channels = ch1 agent1.sinks = sink1 # Define and configure src1 agent1.sources.src1.type = netcat agent1.sources.src1.channels = ch1 agent1.sources.src1.bind = agent1.sources.src1.port = # Define and configure sink1 agent1.sinks.sink1.type = logger agent1.sinks.sink1.channel = ch1 # Define and configure ch1 agent1.channels.ch1.type = memory 16 Active Agent Components (Sources, Channels, Sinks) Individual Component Configuration 17 Configuration A configuration file can contain configuration information for many Agents Only the portion of configuration associated with the name of the Agent will be loaded Components defined in the configuration but not in the active list will be ignored Components that are misconfigured will be ignored Agent automatically reloads configuration if it changes on disk 17 18 Configuration Typical Deployment All agents in a specific tier could be given the same name One configuration file with entries for three agents can be used throughout 18 19 Contextual Routing Achieved using Interceptors and Channel Selectors 19 20 Contextual Routing Interceptor An Interceptor is a component applied to a source in pre-specified order to enable decorating and filtering of events where necessary. Built-in Interceptors allow adding headers such as timestamps, hostname, static markers etc. Custom interceptors can introspect event payload to create specific headers where necessary 20 21 Contextual Routing Channel Selector A Channel Selector allows a Source to select one or more Channels from all the Channels that the Source is configured with based on preset criteria. Built-in Channel Selectors: Replicating: for duplicating the events Multiplexing: for routing based on headers 21 22 Channel Selector Configuration Applied via Source configuration under namespace “selector” # Active components agent1.sources = src1 agent1.channels = ch1 ch2 agent1.sinks = sink1 sink2 # Configure src1 agent1.sources.src1.type = AVRO agent1.sources.src1.channels = ch1 ch2 agent1.sources.src1.selector.type = multiplexing agent1.sources.src1.selector.header = priority agent1.sources.src1.selector.mapping.high = ch1 agent1.sources.src1.selector.mapping.low = ch2 agent1.sources.src1.selector.default = ch 23 Contextual Routing Terminal Sinks can directly use Headers to make destination selections HDFS Sink can use headers values to create dynamic path for files that the event will be added to. Some headers such as timestamps can be used in a more sophisticated manner Custom Channel Selector can be used for doing specialized routing where necessary 23 24 Load Balancing and Failover Sink Processor A Sink Processor is responsible for invoking one sink from an assigned group of sinks. Built-in Sink Processors: Load Balancing Sink Processor – using RANDOM, ROUND_ROBIN or Custom selection algorithm Failover Sink Processor Default Sink Processor 24 25 Sink Processor Invoked by Sink Runner Acts as a proxy for a Sink 25 26 Sink Processor Configuration Applied via “Sink Groups” Sink Groups declared at global level: # Active components agent1.sources = src1 agent1.channels = ch1 agent1.sinks = sink1 sink2 sink3 agent1.sinkgroups = foGroup # Configure foGroup agent1.sinkgroups.foGroup.sinks = sink1 sink3 agent1.sinkgroups.foGroup.processor.type = failover agent1.sinkgroups.foGroup.processor.priority.sink1 = 5 agent1.sinkgroups.foGroup.processor.priority.sink3 = 10 agent1.sinkgroups.foGroup.processor.maxpenalty = 27 Sink Processor Configuration A Sink can exist in at most one group A Sink that is not in any group is handled via Default Sink Processor Caution: Removing a Sink Group does not make the sinks inactive! 27 28 Summary Clients send Events to Agents Agents hosts number Flume components – Source, Interceptors, Channel Selectors, Channels, Sink Processors, and Sinks. Sources and Sinks are active components, where as Channels are passive Source accepts Events, passes them through Interceptor(s), and if not filtered, puts them on channel(s) selected by the configured Channel Selector Sink Processor identifies a sink to invoke, that can take Events from a Channel and send it to its next hop destination Channel operations are transactional to guarantee one-hop delivery semantics Channel persistence allows for ensuring end-to-end reliability 28 29 29 Questions? 30 30 Headline Goes Here Speaker Name or Subhead Goes Here DO NOT USE PUBLICLY PRIOR TO 10/23/12 Flume Sources Prasad Mujumdar | Software Engineer, Cloudera October 2012 31 Flume Sources 32 What is the source in Flume 32 Source Sink Channel Agent External Data External Repository 33 How does a source work? 33 Read data from externals client/other source Stores events in configured channel(s) Asynchronous to the other end of channel Transactional semantics for storing data 34 Source Channel Event Transaction batch Begin Txn Commit Txn Event 35 Source features 35 Event driven or Pollable Supports Batching Fanout of flow Interceptors 36 Reliability 36 Transactional guarantees from channel External client needs handle retry Built in avro-client to read streams Avro source for multi-hop flows Use Flume Client SDK for customization 37 Simple source 37 public class SequenceGeneratorSource extends AbstractSource implements PollableSource, Configurable { public void configure(Context context) { batchSize = context.getInteger("batchSize", 1);... } public void start() { super.start();... } public void stop() { super.stop();.. } 38 Simple source (cont.) 38 public Status process() throws EventDeliveryException { try { for (int i = 0; i < batchSize; i++) { batchList.add(i, EventBuilder.withBody( String.valueOf(sequence++).getBytes())); } getChannelProcessor().processEventBatch(batchList); } catch (ChannelException ex) { counterGroup.incrementAndGet("events.failed"); } return Status.READY; } 39 Fanout 39 Source Channel Processor Channel Selector Channel2 Channel1 Transaction handling Flow 2 Flow 1 Fanout processing 40 Channel Selector 40 Replicating selector Replicate events to all channels Multiplexing selector Contextual routing agent1.sources.sr1.selector.type = multiplexing agent1.sources.sr1.selector.mapping.foo = channel1 agent1.sources.sr1.selector.mapping.bar = channel2 agent1.sources.sr1.selector.mapping.defalt = channel1 41 Built-in source in Flume 41 Asynchronous sources Client don't handle failures Exec, Syslog Synchronous sources Client handles failures Avro, Scribe Flume 0.9x Source AvroLegacy, ThriftLegacy 42 Avro Source 42 Reading events from external client Connecting two agents in a distributed flow Configuration agent_foo.sources.avrosource-1.type = avro agent_foo.sources.avrosource-1.bind = agent_foo.sources.avrosource-1.port = 43 Exec Source 43 Reading data from a output of a command Can be used for ‘tail –F..’ Doesn’t handle failures.. Configuration: agent_foo.sources.execSource.type = exec agent_foo.sources.execSource.command = 'tail -F /var/log/weblog.out’ 44 Syslog Sources 44 Reads syslog data TCP and UPD Facility, Severity, Hostname & Timestamp are converted into Flume Event headers Configuration: agent_foo.sources.syslogTCP.type = syslogtcp agent_foo.sources.syslogTCP.host = agent_foo.sources.syslogTCP.port = 45 Questions? Thank You 46 46 Questions? 47 47 Headline Goes Here Speaker Name or Subhead Goes Here DO NOT USE PUBLICLY PRIOR TO 10/23/12 Channels & Sinks Hari Shreedharan | Software Engineer, Cloudera October 2012 48 Channels Buffer between sources and sinks No tight coupling between sources and sinks Multiple sources and sinks can use the same channel Allows sources to be faster than sinks Why? Transient downstream failures Slower downstream agents Network outages System/process failure 48 49 Transactional Semantics Not to be confused with DB transactions. Fundamental to Flume’s no data loss guarantee.* Provided by the channel. Events once “committed” to a channel should be removed only once they are taken and “committed.” * Subject to the specific channel’s persistence guarantee. An in-memory channel, like Memory Channel, may not retain events after a crash or failure. 49 50 Transactional Semantics 50 51 Transactional Semantics How do transactions guarantee no data loss? 2 hops: 51 52 Transactional Semantics Flow: Event generated by Source 1, “put” and “committed” to Channel 1. Sink 1 “takes” event from Channel 1 and sent over to Source 2. Source 2 “puts” and “commits” event to Channel 2. Source 2 sends success to Sink 1. Sink 1 commits the “take” to the channel – which in turn, deletes the event. Conclusion: Event is available at at least one channel at any point in time. This can be scaled to any number of nodes. 52 53 Flume Channels Memory Channel Recommended if data loss due to crashes are ok File Channel Recommended channel. JDBC Channel 53 54 Memory Channel 54 Events stored on heap Limited capacity No persistence after a system/process crash Very fast 3 config parameters: capacity: Maximum # of events that can be in the channel transactionCapacity: Maximum # of events in one txn. keepAlive: how long to wait to put/take an event 55 File Channel 55 Events stored in WAL, on disk Persistent High performance More disks better performance Highly scalable – just throw more disks at it. 56 File Channel 56 Event Log 1 Event Log 2 Events stored in multiple log files, on disk Pointers (log id + offset) to events stored in in-memory queue Queue = current state of the channel. 57 File Channel 57 Queue periodically synced to disk - checkpoint On channel restart – checkpoint is mmap-ed. Actions(put/take/commit/rollback) that happened after last checkpoint - replayed from log files Queue now in same state as it was when channel was stopped – ready for action! 58 Custom Channels 58 Usually not required ;) Most complex Flume component to write! Implement: Channel interface Transaction Interface Every channel must ensure that the transactional guarantees are respected. Easier route: Extend BasicChannelSemantics and BasicTxnSemantics. Creates thread-local transactions. 59 Custom Channels 59 Optional code walkthrough: MemoryChannel 60 Sinks 60 Writes data to the next hop or to the final destination. Flume Sinks: Avro Sink HDFS Sink Hbase Sink File Sink Null Sink Logger Sink 61 HDFS Sink 61 Writes events to HDFS (what!) Configuring (taken from Flume User Guide): 62 HDFS Sink 62 Supports dynamic directory naming using tags Use event headers : %{header} Eg: hdfs://namenode/flume/%{header} Use timestamp from the event header Use various options to use this. Eg: hdfs://namenode/flume/%{header}/%Y-%m-%D/ Use roundValue and roundUnit to round down the timestamp to use separate directories. Within a directory – files rolled based on: rollInterval – time since last event was written rollSize – max size of the file rollCount – max # of events per file 63 AsyncHBase Sink 63 Insert events and increments into Hbase Writes events asynchronously at very high rate. Easy to configure: table columnFamily batchSize - # events per txn. timeout - how long to wait for success callback serializer/serializer.* - Custom serializer can decide how and where the events are written out. 64 Avro Sink 64 Sends events to the next hop’s Avro Source Configuring: hostname port batch-size - # events per txn/batch sent to next hop connect-timeout – how long to wait successful connection request-timeout – how long to wait for success of batch 65 Sink Runner and Sink Processors 65 Sink Runner: Thread which calls SinkProcessor#process(). SinkProcessor manages a sink group which is defined as a top level component. SinkProcessor#process chooses one of the sinks in its group, based on some criteria It then calls Sink#process on the selected sink 66 Custom Sink 66 Custom sinks written quite often Allows Flume to write to your own storage system like Cassandra (- ng-cassandra-sink) or even something like JMS. 67 Custom Sink 67 How? Implement the Sink Interface Extend the Abstract Sink class Sink#process method is the key. Return Status.BACKOFF if no events were available in the channel, else return Status.SUCCESS 68 68 Questions? 69 Headline Goes Here Speaker Name or Subhead Goes Here Flume Topologies Will McQueen | Software Engineer, Cloudera October 2012 70 Topology #1 Flume SDK's RPC Client Sources Interceptors Channel Selectors Channels Sinks 71 Topology #1 App Tier... Flume Agent Tier 1 Storage Tier Flume Agent Tier 2 Flume SDK App-1 HDFS... LB + failover LB + failover avro src agent11 Flume SDK App-2 Flume SDK App-3 file ch avro sink avro sink avro src agent12 file ch avro sink avro sink avro src agent13 file ch avro sink avro sink avro src hdfs sink file ch agent21 avro src hdfs sink file ch agent22 72 Topology #1 App Tier talks to Flume Agent Tier 1 App-1 uses Flume SDK to build and send Flume events over Avro Flume Event = [headers] + payload Contextual routing from headers Using LoadBalancingRpcClient with 'backoff=true' to get both load balancing and failover Avro source accepts avro events from multiple clients, up to the # specified in 'threads' prop 73 Topology #1 Sample Config for 1st Flume Tier a1.channels = c1 a1.sources = r1 a1.sinks = k1 k2 a1.sinkgroups = g = AVRO a1.sources.r1.bind = = 41414 74 Topology #1 Tier 1 talks to Tier 2 over Avro Sink groups Load balancing Failover 75 Topology #1 Sample Config for 2nd Flume Tier a2.channels = c1 a2.sources = r1 a2.sinks = k1 a2.channels.c1.type = FILE a2.sources.r1.channels = c1 a2.sources.r1.type = AVRO a2.sources.r1.bind = a2.sources.r1.port = a2.sinks.k1.channel = c1 a2.sinks.k1.type = HDFS a2.sinks.k1.hdfs.path = hdfs://namenode.example.org a2.sinks.k1.hdfs.fileType = DataStream 76 agent21 Topology #2 App Tier... Flume Agent Tier 1Storage Tier App-1 App-2 App-3 HDFS LB + failover LB + failover HBase Flume Agent Tier 2... syslog src agent11 file ch avro sink avro sink... syslog src agent12 file ch avro sink avro sink... syslog src agent13 file ch avro sink avro sink avro src file ch hdfs sink hbase sink agent22 avro src file ch hdfs sink hbase sink... syslog 77 Topology #2 App Tier talks to Flume Agent Tier 1 App-1 is some syslog-enabled program Sends syslog events to remote Flume agent that's running with Flume syslog source (UDP or TCP) Alternatively: Syslog-enabled program sends to local Flume agent App-1 could also be a web server You can use Flume SDK to create client daemon that reads httpd logs, builds the Flume events, and then sends them to tier 1 78 Topology #2 a1.channels = c1 a1.sources = r1 a1.sinks = k1 k2 a1.sinkgroups = g1 a1.sinkgroups.g1.sinks = k1 k = SYSLOGTCP a1.sources.r1.host = = Sample config for 1st flume tier 79 Topology #2 Contextual Routing in Agent Tier 2 All events are going to HDFS Only events with high importance are going to HBase emergency, alert, critical, error HDFS path bucketing with escape sequences hdfs://nn.example.org/demo/%Y-%m-%d/%H/%M FlumeData-%{host}- 80 Topology #2 a2.channels = c1 a2.sources = r1 a2.sinks = k1 k2 a2.sinkgroups = g1 a2.sinkgroups.g1.sinks = k1 k2 a2.sinkgroups.g1.processor.type = LOAD_BALANCE a2.sinkgroups.g1.processor.selector = ROUND_ROBIN a2.sinkgroups.g1.processor.backoff = true a2.channels.c1.type = FILE a2.channels.c1.checkpointDir = /var/run/flume-ng/.flume/ch-1/checkpoint a2.channels.c1.dataDirs = /var/run/flume-ng/.flume/ch-1/data a2.channels.c2.type = FILE a2.channels.c2.checkpointDir = /var/run/flume-ng/.flume/ch-2/checkpoint a2.channels.c2.dataDirs = /var/run/flume-ng/.flume/ch-2/data Sample config for 2nd Flume Tier a2.sources.r1.channels = c1 c2 a2.sources.r1.type = AVRO a2.sources.r1.bind = a2.sources.r1.port = a2.sources.r1.selector.type = MULTIPLEXING a2.sources.r1.selector.header = Severity a2.sources.r1.selector.default = c1 a2.sources.r1.selector.mapping.0 = c1 c2 a2.sources.r1.selector.mapping.1 = c1 c2 a2.sources.r1.selector.mapping.2 = c1 c2 a2.sources.r1.selector.mapping.3 = c1 c2 a2.sinks.k1.channel = c1 a2.sinks.k1.type = HDFS a2.sinks.k1.hdfs.path = hdfs://nn.example.org/demo/%Y-%m-%d/%H%M/ a2.sinks.k1.hfds.filePrefix = FlumeData-%{host}- a2.sinks.k1.hdfs.fileType = DataStream a2.sinks.k1.hdfs.round = true a2.sinks.k1.hdfs.roundUnit = minute a2.sinks.k1.hdfs.roundValue = 10 a2.sinks.k2.channel = c2 a2.sinks.k2.type = org.apache.flume.sink.hbase.AsyncHBaseSink a2.sinks.k2.table = mytable1 a2.sinks.k2.columnFamily = mycolfam1 81 Topology #2 Using interceptors For all other source that don't auto-insert host and timestamp like syslog sources do, you can use host interceptor and timestamp interceptor. Inserts 'host' and 'timestamp' headers Can chain them Can choose to preserve existing value 82 Explore the Flume User Guide See what flume components are available and the properties used to configure them by reading through the latest Flume User Guide at: 83 83 Questions? 84 84 Headline Goes Here Speaker Name or Subhead Goes Here DO NOT USE PUBLICLY PRIOR TO 10/23/12 Customization, Monitoring & Performance Mike Percy | Software Engineer, Cloudera 85 85 Customization 86 One size does not fit all 86 87 87 Customization 1. Top-level components a. Sources b. Channels c. Sinks 2. Sub-components a. Serializers b. Interceptors 3. Client SDK 88 Customization: Top-level components: Architecture 88 89 Customization: Top-level components: Sources 89 90 Customization: Top-level components: Sources 90 91 Customization: Top-level components: Sources 91 For examples of how to write a source, look at the Flume source code NetcatSource SequenceGeneratorSource 92 Customization: Top-level components: Channels 92 93 Customization: Top-level components: Channels 93 In practice, channels are tricky to get right It’s best to not write your own Channel implementation Work with the community to add or improve existing channels 94 Customization: Top-level components: Sinks 94 95 Customization: Top-level components: LoggerSink 95 96 Customization: Sub-components: Serializers 96 Serializers allow full control over how events are written Native support for raw text and Avro Easy to extend to support arbitrary formats CSV XML JSON Protobufs 97 Customization: Sub-components: EventSerializer 97 EventSerializer is a file-oriented serialization interface Supported in the HDFS sink and File Rolling sink 98 Customization: Sub-components: EventSerializer 98 99 Customization: Sub-components: Hbase Serializers 99 Async Hbase serializers Hbase serializers 100 Customization: Sub-components: Interceptors 100 Interceptors give full access to each event mid-stream Filtering Allow or drop events meeting a certain pattern Routing Inspect events, add header tags to indicate a destination Transformation Convert an event from one format to another 101 Customization: Sub-components: Interceptors 101 102 Customization: Sub-components: Interceptors 102 Out of the box: Timestamp Interceptor Host interceptor Regex Filtering Interceptor 103 Customization: Client SDK 103 The Client SDK allows easy integration of Flume into apps Load balancing RPC client Durability guarantees – Avro RPC support Fast, based on Netty Flexible and straightforward to use 104 Customization: Client SDK: Minimal example 104 105 Customization: Client SDK: Minimal example 105 106 106 Monitoring 107 107 Monitoring Protocol support Configuration The most useful metrics 108 Monitoring: protocol support 108 Several monitoring protocols supported out of the box JMX Ganglia HTTP (JSON) 109 Monitoring: configuration 109 Java opts must be set in flume-env.sh to configure monitoring Ganglia and HTTP monitoring are mutually exclusive 110 Monitoring: configuration 110 111 Monitoring: Useful metrics: JSON output 111 ssss 112 Monitoring: Useful metrics: The config file 112 113 Monitoring: Useful metrics: Channel 113 Channel ChannelSize ChannelCapacity ChannelFillPercentage EventPut(Attempt/Success)Count PutAttempt >> PutSuccess means channel is full or misconfigured EventTake(Attempt/Success)Count Note: Take attempts will always grow as sinks poll for activity 114 Monitoring: Useful metrics: Source 114 Source Event(Received/Accepted)Count Append(Received/Accepted)Count AppendBatch(Accepted/Received)Count 115 Monitoring: Useful metrics: Sink 115 Sink EventDrain(Attempt/Success)Count Batch(Complete/Underflow)Count 116 116 Performance 117 117 Performance 1. Choosing the right channel a. File channel b. Memory channel 2. Tuning Flume for performance a. Capacity planning b. Watching steady state buffer sizes c. Modifying the batch size d. Incorporating parallelism 118 Performance: Choosing the right channel 118 There are two recommended channel implementations: 1. File channel 2. Memory channel Others you may hear mention of: 3. JDBC channel (superseded by File channel) 4. RecoverableMemoryChannel (unstable) 119 Performance: Channels: File channel 119 High-performance disk-based queue Guarantees durability of committed events Flushes to disk at the end of each transaction Use larger batch sizes to maximize the performance Able to perform parallel writes to multiple disks Cheaper per GB than Memory channel, yet scalable Able to buffer lots of data when there is a downstream outage 120 Performance: Channels: Memory channel 120 Limited durability guarantees Events stored only in memory Very low read/write latencies Less sensitive to batch size settings than File Channel Single-event transactions are still pretty fast Limited by available physical RAM Much higher cost per GB than File channel Lower capacity, so less able to tolerate downstream outages 121 Performance: Tuning: Capacity planning 121 Rules of thumb At any given hop, consider how much downtime you want to tolerate. Set your channel capacity to tolerate it e.g.: Tolerate 1 hour of downtime. Rate = 1,000 events/sec Channel capacity = 1,000 events/sec * 60 sec/min * 60 min/hour Channel capacity = 3,600,000 events Plan for 2 or more Flume agent tiers: collection & storage Use a load-balancing sink processor to spread the load 20:1 or 30:1 ratio of clients to collection agents is reasonable 122 Performance: Tuning: Steady-state ChannelSize 122 Critical metric: ChannelSize at each hop Watch ChannelSize to pinpoint bottlenecks in the flow 123 Performance: Tuning: Batch Size 123 Batch size affects throughput and duplication under failure The higher the batch size, the better performance, but… If there is a failure mid-transaction, as many as batchSize Events may be duplicated (re-tried) downstream Rule of thumb: Batch sizes of 100 or 1,000 or 10,000 may be optimal depending on event size, throughput, etc. 124 Performance: Tuning: Batch Size 124 Batch size should equal sum of batch sizes of input streams 125 Performance: Tuning: Using parallelism 125 Sinks are single-threaded Attach multiple sinks to a single channel: Increase throughput 126 126 Questions? 127 127 Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/2367364/
CC-MAIN-2017-09
en
refinedweb
ok i want to make a program to show a teacher at my school so i can get into computer Ap which teaches you java(but they say u have to know stuff to get in it makes no sense i am in highschool). here is some seudocode and the code i already have. int grades = 0; boolean acceptance = true;//a variable to see if the user got accepted into the course ask user ("what did u get in math"); input = grades //user inputs his math grades if (grades >= 89) display ("you have a good chance of being accepted"); else display ("you still have a chance i would apply"); ask user ("did you get into the course"); if (acceptance = true) display("nice, good job"); else display("sorry, better luck next time") end here is wat i have so far already written in java public class computer { public static void main(String[] args) { boolean acceptance; int grades = 0; System.out.println("what is your grade in math"); //need the input function right here if (grades >= 89) System.out.println("you have a good chance of getting into computer AP"); else System.out.println("you still have a chance but it will be harder to get in"); } } So i need to know the input functions and do i need to end that before i can start the other if then statement with the boolean, and if anybody feels like they have time could u tell me how i would make this into a gui. Thank you for your help i really want to get into this course.
https://www.daniweb.com/programming/software-development/threads/21234/need-help-with-java-program
CC-MAIN-2017-09
en
refinedweb
How do I verify a download?. === 0.60 - Tue 30 Apr 2013 === * In this release the required python version is changed from 2.5 to 2.6 ! * Added a Recent Changes dialog and a Recent Changes pathbar option * Added search entry to toolbar * Added function to attachment browser plugin to zoom icon size * Added new template by Robert Welch * by Stéphane Aulery * Removed custom zim. class in favor of standard library version * New translations for Korean and Norwegian Bokmal This release fixes a critical bug in the editor widget that can lead to loss of content for specific combinations of formatting. In addition week numbers in Journal pages are fixed and Tasklist tag inheritance is improved.. === 0.58 - Sat 15 Dec 2012 === * Added new plugin for distraction free fullscreen mode * Added options to limit tasklist plugin to certain namespaces - Pierre-Antoine Champin * Added option to tasklist plugin to flag non-actionable tasks by a special tag * Added prompt for filename for Insert New File action * Added template option to list attachments in export * Added class attributes to links in HTML output * Added two more commandline options to quicknote plugin * Made sidepanes more compact by embedding close buttons in widgets * Critical fix for restarting zim after a crash (cleaning up socket) *
https://launchpad.net/zim/+download
CC-MAIN-2017-09
en
refinedweb
This action might not be possible to undo. Are you sure you want to continue? # Rob Miles Edition 2.0 July 2010 2010 Department of Computer Science, The University of Hull. ii All rights reserved.robmiles. Cottingham Road HULL HU6 7RX UK Department: Email: rob@robmiles. copy or transmission of this publication may be made without written permission.com If you find a mistake in the text please report the error to [email protected]. 28 July 2010 iii . No reproduction.ac. Edition 2.0 Wednesday.dcs.com Blog: and I will take a look. Robert Blackburn Building The University of Hull. The author can be contacted at: The Department of Computer Science. . the fastest.csharpcourse. don't get too persistent.e.dcs. just ones which are better in a particular context. These are based on real programming experience and are to be taken seriously. If you have not programmed before.ac. Programming is not rocket science it is. puns.com. They contain a number of Programming Points.Introduction Welcome Introduction Welcome Welcome to the Wonderful World of Rob Miles™.9. The keys to learning programming are: Practice – do a lot of programming and force yourself to think about things from a problem solving point of view Study – look at programs written by other people. the smallest. Staying up all night trying to sort out a problem is not a good plan. If you have any comments on how the notes can be made even better (although I of course consider this highly unlikely) then feel free to get in touch Above all. We will cover what to do when it all goes wrong later in section 5. If you have programmed before I'd be grateful if you'd still read the text.com C# Programming © Rob Miles 2010 5 . well. Font. i. There are also bits written in a Posh These are really important and should be learnt by heart. the easiest to use etc. enjoy programming. Rob Miles rob@robmiles. The bad news about learning to program is that you get hit with a lot of ideas and concepts at around the same time when you start.com www. However. programming. The principle reason why most folks don't make it as programmers is that they give up. The website for the book is at. and this can be confusing. And you have to work hard at it. and programming. Persistence – writing programs is hard work. Not because they are stupid. Reading the notes These notes are written to be read straight through.hull. If you haven't solved a programming problem in 30 minutes you should call time out and seek help. It is worth it just for the jokes and you may actually learn something. Or at least walk away from the problem and come back to it. And remember that in many cases there is no best solution. You can learn a lot from studying code which other folk have created. Figuring out how somebody else did the job is a great starting point for your solution.uk Getting a copy of the notes These notes are made freely available to Computer Science students at the University of Hull. and then referred to afterwards. do not worry. In this book I'm going to give you a smattering of the C# programming language. This is a world of bad jokes. It just makes you all irritable in the morning. C# Programming © Rob Miles 2010 6 . A better way is to describe it as: A device which processes information according to instructions it has been given. to be useful. while technically correct.1 An Introduction to Computers Qn: Why does a bee hum? Ans: Because it doesn't know the words! One way of describing a computer is as an electric box which hums. and further because there are people willing to pay you to do it. This is not what most people do with computers. A programmer has a masochistic desire to tinker with the innards of the machine. particularly amongst those who then try to program a fridge. Software uses the physical ability of the hardware. If a computer has a soul it keeps it in its software. The box.2 Hardware and Software If you ever buy a computer you are not just getting a box which hums. At this point we must draw a distinction between the software of a computer system and the hardware. and it stops working when immersed in a bucket of water. we are going to consider computers. to ensure that you achieve a ―happy ending‖ for you and your customer. A user has a job which he or she finds easier to do on a computer running the appropriate program. This. This general definition rules out fridges but is not exhaustive. Finally you will take a look at programming in general and the C# language in particular. Hardware is the physical side of the system. 1. 1. Essentially if you can kick it. We must therefore make a distinction between users and programmers. because it sets the context in which all the issues of programming itself are placed. You will discover what you should do when starting to write a program.e.1. Software is what makes the machine tick. i. The instructions you give to the computer are often called a program. One of the golden rules is that you never write your own program if there is already one available. The business of using a computer is often called programming. Before we can look at the fun packed business of programming though it is worth looking at some computer terminology: 1. because you will often want to do things with computers which have not been done before. it is hardware. which can run programs. However for our purposes it will do.1. we are going to learn how to program as well as use a computer. a keen desire to process words with a computer should not result in you writing a word processor! However. Hardware is the impressive pile of lights and switches in the corner that the salesman sold you. They use programs written by other people.Computers and Programs Computers 1 Computers and Programs In this chapter you are going to find out what a computer is and get an understanding of the way that a computer program tells the computer what to do. can lead to significant amounts of confusion. must also have sufficient built-in intelligence to understand simple commands to do things. Most people do not write programs.1 Computers Before we consider programming. This is an important thing to do. Put duff data into a computer and it will do equally useless things. as well as a useful thing to blame. So why am I being so pedantic? Because it is vital to remember that a computer does not "know" what the data it is processing actually means. It gives computer programs a platform on which they can execute. some processing is performed. You will have to learn to talk to an operating system so that you can create your C# programs and get them to go.388. A computer works on data in the same way that a sausage machine works on meat. Put a bicycle into a sausage machine and it will try to make sausages out of it. It looks after all the information held on the computer and provides lots of commands to allow you to manage things.Computers and Programs Computers do something useful. An example. It also lets you run programs. and something comes out of the other end: Data Computer Data This makes a computer a very good "mistake amplifier". I regard data and information as two different things: Data is the collection of ons and offs which computers store and manipulate. All computers are sold with some software. It is called software because it has no physical existence and it is comparatively easy to change. and then generate further information.. A computer program tells the computer what to do with the information coming in.. Without it they would just be a novel and highly expensive heating system..608 in your account! Data Processing Computers are data processors. 1.3 Data and Information People use the words data and information interchangeably. A program is unaware of the data it is processing in the same way that a sausage machine is unaware of what meat is. The software which comes with a computer is often called its Operating System. A computer program is just a sequence of instructions which tell a computer what to do with the data coming in and what form the data sent out will have. The Operating System makes the machine usable. it is the user who gives meaning to these patterns. As far as the computer is concerned data is just patterns of bits. something is put in one end. C# Programming © Rob Miles 2010 7 . As far as the computer is concerned data is just stuff coming in which has to be manipulated in some way. humans work on information. They seem to think that one means the other. Software is the voice which says "Computer Running" in a Star Trek film. Windows 7 is an operating system.1. Information is fed into them... Strictly speaking computers process data. It is only us people who actually give meaning to the data (see above). they do something with it. Information is the interpretation of the data by people to mean something. ones you have written and ones from other people. Remember this when you get a bank statement which says that you have £8. However the CD player and games console could not be made to work without built-in data processing ability. CD Player: A computer is taking a signal from the disk and converting it into the sound that you want to hear. Tell people that you program computers and you will get one of the following responses: 1. and ever will have. examples of typical data processing applications are: Digital Watch: A micro-computer in your watch is taking pulses from a crystal and requests from buttons. road speed. You will not press a switch to make something work. you will press a switch to tell a computer to make it work. Games Console: A computer is taking instructions from the controllers and using them to manage the artificial world that it is creating for the person playing the game. "That's interesting". Car: A micro-computer in the engine is taking information from sensors telling it the current engine speed. A look which indicates that you can't be a very good one as they all drive Ferraris and tap into the Bank of England at will. 3. is much more than that. timing of the spark etc. For example a doctor may use a spread sheet to calculate doses of drugs for patients. setting of the accelerator etc and producing voltages out which control the setting of the carburettor. which you might think is entirely reading and writing numbers. as software writers are moving. You must make sure that the code you write will actually fit in the target machine and operate at a reasonable speed. It is the kind of thing that you grudgingly admit to doing at night with the blinds drawn and nobody watching. 1. In this case a defect in the program could result in illness or even death (note that I don't think that doctors actually do this – but you never know. 2. to optimise the performance of the engine. Asked to solve every computer problem that they have ever had. reading in numbers and printing out results. followed by a long description of the double glazing that they have just had fitted. 4. processing this data and producing a display which tells you the time. I will mention them when appropriate. oxygen content of the air. As software engineers it is inevitable that a great deal of our time will be spent fitting data processing components into other devices to drive them. C# Programming © Rob Miles 2010 8 . The power and capacity of modern computers makes this less of an issue than in the past. Note that some of these data processing applications are merely applying technology to existing devices to improve the way they work. A blank stare. Most reasonably complex devices contain data processing components to optimise their performance and some exist only because we can build in intelligence. but you should still be aware of these aspects. and we will have to make sure that they are not even aware that there is a computer in there! You should also remember that seemingly innocuous programs can have life threatening possibilities. These embedded systems will make computer users of everybody.2 Programs and Programming I tell people I am a "Software Engineer"..) Programmer’s Point: At the bottom there is always hardware It is important that you remember your programs are actually executed by a piece of hardware which has physical limitations.. Programming is a black art. These are the traditional uses of computers. It is into this world that we. It is important to think of business of data processing as much more than working out the company payroll. so as soon as they are given a problem they immediately start thinking of ways to solve it. tut tutting. Having looked at it for a while. Solving the Wrong Problem Coming up with a perfect solution to a problem the customer has not got is something which happens surprisingly often in the real world. The computer has to be made to understand what you are trying to tell it to do. In the real world such a definition is sometimes called a Functional Design Specification or FDS. We shall assume that the customer knows even less about computers than we do! Initially we are not even going to talk about the programming language. The worst thing you can say to a customer is "I can do that". From Problem to Program Programming is not about mathematics. the right thing was being built. since the developers had stopped asking them questions. If you think that learning to program is simply a matter of learning a programming language you are very wrong. 1. we are simply going to make sure that we know what the customer wants. Programming is defined by me as deriving and expressing a solution to a given problem in a form which a computer system can understand and execute. I am going to start on the basis that you are writing your programs for a customer. he will open his bag and produce various tools and parts. The developers of the system quite simply did not find out what was required. Both you and the C# Programming © Rob Miles 2010 9 . fit them all together and solve your problem. In fact if you think that programming is simply a matter of coming up with a program which solves a problem you are equally wrong! There are many things you must consider when writing a program. Many software projects have failed because the problem that they solved was the wrong one. I like to think of a programmer as a bit like a plumber! A plumber will arrive at a job with a big bag of tools and spare parts. He or she has problem and would like you to write a program to solve it. You are given a problem to solve. The art of programming is knowing which bits you need to take out of your bag of tricks to solve each part of the problem. You look at the problem for a while and work out how to solve it and then fit the bits of the language together to solve the problem you have got.1 What is Programmer? And remember just how much plumbers earn…. which both you and the customer agree on. You have at your disposal a big bag of tricks.2. This tells you exactly what the customer wants. Instead you should think "Is that what the customer wants?" This is a kind of self-discipline. not all of them are directly related to the problem in hand. Programming is just like this. and only at the final handover was the awful truth revealed. this almost a reflex action. Programmers pride themselves on their ability to come up with solutions. What you should do is think "Do I really understand what the problem is?" Before you solve a problem you should make sure that you have a watertight definition of what the problem is.Computers and Programs Programs and Programming Programming is defined by most people as earning huge sums of money doing something which nobody can understand. Unfortunately it is also the most difficult part of programming as well. type of computer or anything like that. The customers assumed that. in this case a programming language. The art of taking a problem and breaking it down into a set of instructions you can give a computer is the interesting part of programming. it is about organization and structure. It is therefore very important that a programmer holds off making something until they know exactly what is required. One or two things fall out of this definition: You need to be able to solve the problem yourself before you can write a program to do it. but instead created what they thought was required. "This looks like a nice little earner" you think. This is true even (or perhaps especially) if I do a job for a friend. He knows you are a programmer of sorts and would like your help in solving a problem which he has: He has just started making his own window units and is looking for a program which will do the costing of the materials for him. then you can think about ways of solving the problem.2. Modern development techniques put the customer right at the heart of the development. Once you have got your design specification. you are sitting in your favourite chair in the pub contemplating the universe when you are interrupted in your reverie by a friend of yours who sells double glazing for a living. Programmer’s Point: The specification must always be there I have written many programs for money. He wants to just enter the dimensions of the window and then get a print out of the cost to make the window. The height of the window. 1. There are lots of ways of representing this information in the form of diagrams. This is called prototyping. Writing some form of specification forces you to think about your problem at a very detailed level. Information coming out The information that our customer wants to see is: the area of glass required for the window the length of wood required to build a frame. It also forces you to think about what your system is not going to do and sets the expectations of the customer right at the start.. as a developer don’t really know much about the customer’s business and they don’t know the limitations and possibilities of the technology. These work on the basis that it is very hard (and actually not that useful) to get a definitive specification at the start of a project. The first thing you need to do is find out exactly what the customer wants you to do. What the system does with the information. and the bottom line is that if you provide a system which behaves according to the design specification the customer must pay you. and once you have agreed to a price you start work. This is not true. What flows out of the system.2 A Simple Problem Consider the scenario.. C# Programming © Rob Miles 2010 10 . there is no customer to satisfy. and involve them in the design process. Specifying the Problem When considering how to write the specification of a system there are three important things: What information flows into the system. You might think that this is not necessary if you are writing a program for yourself.Computers and Programs Programs and Programming customer sign it. for now we will stick with written text when specifying each of the stages: Information going in In the case of our immortal double glazing problem we can describe the information as: The width of a window. 0 metres inclusive. we now have to worry about how our program will decide when the information coming in is actually valid. in metres and being a value between 0. Remember that we are selling double glazing. in square metres. and two pieces of wood the height of the window. Note that we have also added units to our description.5 metres and 2.5 Metres and 3. In the case of the above we could therefore expand the definition of data coming in as: The width of the window. and work can commence. this is very important . Having written this all up in a form that both you and the customer can understand.perhaps our customer buys wood from a supplier who sells by the foot.25 feet per metre. he or she must understand that if information is given which fits within the range specified. so two panes will be required. In the case of our window program the metadata will tell us more about the values that are being used and produced. we must then both sign the completed specification. in which case our output description should read: Note that both you and the customer must understand the document! The area of glass required for the window. in metres and being a value between 0. Being sensible and far thinking people we do not stop here..Computers and Programs Programs and Programming You can see what we need if you take a look at the diagram below: Height of Window Width of Window The area of the glass is the width multiplied by the height. For any quantity that you represent in a program that you write you must have at least this level of metadata . The length of wood required for the frame. The height of the window. Programmer’s Point: metadata is important Information about information is called metadata. To make the frame we will need two pieces of wood the width of the window. specifically the units in which the information is expressed and the valid range of values that the information may have.5 metres inclusive. given in feet using the conversion factor of 3. The word meta in this situation implies a "stepping back" from the problem to allow it to be considered in a broader context. C# Programming © Rob Miles 2010 11 . This must be done in conjunction with the customer. your program will regard the data as valid and act accordingly. set up a phased payment system so that you get some money as the system is developed. we have come full circle here. if you are going to use prototypes it is a good thing to plan for this from the C# Programming © Rob Miles 2010 12 . What will happen is that you will come up with something which is about 60% right. You then go back into your back room. The customer will tell you which bits look OK and which bits need to be changed.to emerge later with the perfect solution to the problem. there is no ambiguity which can lead to the customer requesting changes to the work although of course this can still happen! The good news for the developer is that if changes are requested these can be viewed in the context of additional work. reminiscent of a posh tailor who produces the perfect fit after numerous alterations. At this point the supplier knows that if a system is created which will pass all the tests the customer will have no option but to pay for the work! Note also that because the design and test procedures have been frozen.. sometimes even down to the colour of the letters on the display! Remember that one of the most dangerous things that a programmer can think is "This is what he wants"! The precise interaction with the user . Testing is a very important part of program development. There is even one development technique where you write the tests before you write the actual program that does the job. Customer Involvement Note also in a "proper" system the customer will expect to be consulted as to how the program will interact with the user.. you could for example say: “If I give the above program the inputs 2 metres high and 1 metre wide the program should tell me I need 4 square metres of glass and 19. Again. you can expect to write as much code to test your solution as is in the solution itself. This is not going to happen. This is actually a good idea.. is something which the customer is guaranteed to have strong opinions about. In a large system the person writing the program may have to create a test harness which is fitted around the program and will allow it to be tested. Remember this when you are working out how much work is involved in a particular job.Computers and Programs Programs and Programming Proving it Works In a real world you would now create a test which will allow you to prove that the program works. suggests changes and then wait for the next version to find something wrong with. how the information is presented etc. and emerge with another system to be approved. Ideally all this information should be put into the specification. Fact: If you expect to derive the specification as the project goes on either you will fail to do the job. However. Actually. . Rob's law says that 60% of the duff 40% will now be OK. muttering under your breath. which should include layouts of the screens and details of which keys should be pressed at each stage. In terms of code production. Quite often prototypes will be used to get an idea of how the program should look and feel.5 feet of wood. including the all-important error conditions. Both the customer and the supplier should agree on the number and type of the tests to be performed and then sign a document describing these.. They will get a bit upset when the delivery deadline goes by without a finished product appearing but they can always cheer themselves up again by suing you. because I did mention earlier that prototyping is a good way to build a system when you are not clear on the initial specificaiton. All the customer does is look at something. for which they can be expect to be paid.” The test procedure which is designed for a proper project should test out all possible states within the program. so you accept changes for the last little bit and again retreat to your keyboard. Getting Paid Better yet. and one we will explore later.what the program does when an error is encountered. Please note that this does not imply that tape worms would make good programmers! Computers are too stupid to understand English. particularly when you might have to do things like trade with the customer on features or price. You do not work for your customers.25 and print it The programming portion of the job is now simply converting the above description into a language which can be used in a computer. The customer may well say "But I am paying you to be the computer expert. One very good reason for doing this kind of thing is that it gets most of the program written for you . why can we not use something like English?" There are two answers to this one: 1.3 Programming Languages Once we know what the program should do (specification). an art. This is no excuse. This is very important. It is very hard to express something in an unambiguous way using English.. and there are limits to the size of program that we can create and the speed at which it can talk to us. therefore we cannot make a computer which can understand English. Explain the benefits of "Right First Time" technology and if that doesn't work produce a revolver and force the issue! Again. At the moment. If you do not believe me. You might ask the question "Why do we need programming languages. We cannot make very clever computers at the moment. you work with them. Programmer’s Point: Good programmers are good communicators The art of talking to a customer and finding out what he/she wants is just that. if I could underline in red I would: All the above apply if you are writing the program for yourself. The best we can do is to get a computer to make sense of a very limited language which we use to tell it what to do. the kind of simple systems we are going to create as we learn to program are going to be so trivial that the above techniques are far too long winded. by using the most advanced software and hardware..often with the help of the customer.. and how we are going to determine whether it has worked or not (test) we now need to express our program in a form that the computer can work with. You are wrong. ask any lawyer! Time Flies like an Arrow. all to the better. Fruit Flies like a Banana! C# Programming © Rob Miles 2010 13 . If you want to call yourself a proper programmer you will have to learn how to do this. we can make computers which are about as clever as a tape worm. Computers are made clever by putting software into them. You are your own worst customer! You may think that I am labouring a point here. Tape worms do not speak very good English. Fact: More implementations fail because of inadequate specification than for any other reason! If your insistence on a cast iron specification forces the customer to think about exactly what the system is supposed to do and how it will work. When we start with our double glazing program we now know that we have to: read in the width verify the value read in the height verify the value calculate width times height times 2 and print it calculate ( width + height ) * 2 * 3. One of the first things you must do is break down the idea of "I am writing a program for you" and replace it with "We are creating a solution to a problem".. 1. English would make a lousy programming language. To take the second point. I know nothing about these machines". 2. English as a language is packed full of ambiguities.Computers and Programs Programming Languages start rather than ending up doing extra work because your initial understanding of the problem was wrong. To take the first point... C is famous as the language the UNIX operating system was written in. If I make a mistake with the professional tool I could quite easily lose my leg. They are simple enough to be made sense of by computer programs and they reduce ambiguity. This makes the language much more flexible. The managed code is fussed over by the system which runs it.1 Dangerous C I referred to C as a dangerous language. Programmer’s Point: Computers are always stupid I reckon that you should always work on the basis that any computer will tolerate no errors on your part and anything that you do which is stupid will always cause a disaster! This concentrates the mind wonderfully. If you ever make the mistake of calling the language C hash you will show your ignorance straight away! C# is a very flexible and powerful programming language with an interesting history. i. Rob Miles.4 C# There are literally hundreds of programming languages around. which is a highly dangerous and entertaining language which was invented in the early 1970s. An unmanaged program goes faster.4. In programming terms what this means is that C lacks some safety features provided by other programming languages. 1. but do not think that it is the only language you will ever learn. you will need to know at least 3! We are going to learn a language called C# (pronounced C sharp). This makes sure that it is hard (but probably not impossible) to crash your computer running managed code. and enable direct access to parts of the underlying computer system. To get the maximum possible performance. having borrowed (or improved) features provided by these languages. As I am not an experienced chain saw user I would expect it to come with lots of built in safety features such as guards and automatic cut outs. causing your programs to run more slowly.4. However. all this fussing comes at a price. So what do I mean by that? Consider the chain saw. but if it crashes it is capable of taking the computer C# Programming © Rob Miles 2010 14 . C# is a great language to start programming in.2 Safe C# The C# language attempts to get the best of both worlds in this respect. because of all the safety stuff I might not be able to cut down certain kinds of tree. If I. you can mark your programs as unmanaged. It was developed by Microsoft Corporation for a variety of reasons. If I was a real lumberjack I would go out and buy a professional chain saw which has no safety features whatsoever but can be used to cut down most anything. and was specially designed for this. The origins of both Java and C++ can be traced back to a language called C. want to use a chain saw I will hire one from a shop.Computers and Programs C# Programming languages get around both of these problems. during your career you will have to learn more than just one.e. some political and others marketing. something the amateur machine would not let happen. so I have a much greater chance of crashing the computer with a C program than I do with a safer language. However. Programmer’s Point: The language is not that important There are a great many programming languages around. C# bears a strong resemblance to the C++ and Java programming languages. These will make me much safer with the thing but will probably limit the usefulness of the tool. 1. if I do something stupid C will not stop me. 1. some technical. A C# program can contain managed or unmanaged parts. Later on we will look at how you can break a program of your own down into a number of different chunks (perhaps so several different programmers can work on it).5 Creating C# Programs Microsoft has made a tool called Visual Studio. each of which is in charge of part of the overall system. which is a great place to write programs. They are then located automatically when your program runs. along with an integrated editor. i. These extra features are available to your C# program but you must explicitly ask for them.4. 1. Only if no errors are found by the compiler will it produce any output.NET Framework.4. 1. C# is a compiled programming language. which can be used to compile and run C# programs. A compiler is a very large program which knows how to decide if your program is legal. It comprises the compiler. The use of objects is as much about design as programming. C# is a great language to start learning with as the managed parts will make it easier for you to understand what has happened when your programs go wrong. Another free resources is the Microsoft . for now the thing to remember is that you need to show your wonderful C# program to the compiler before you get to actually run it. This provides a bunch of command line tools.3 C# and Objects The C# language is object oriented. There is a free version. This is not because I don't know much about it (honest) but because I believe that there are some very fundamental programming issues which need to be addressed before we make use of objects in our programs. It is provided in a number of versions with different feature sets. We will look in more detail at this aspect of how C# programs work a little later. I am very keen on object oriented programming. which is a great place to get started. set up network connections and the like. The C# language is supplied with a whole bunch of other stuff (to use a technical term) which lets C# programs do things like read text from the keyboard. How you create and run your programs is up to you. Objects are an organisational mechanism which let you break your program down into sensible chunks. Switching to unmanaged mode is analogous to removing the guard from your new chainsaw because it gets in the way. but may indicate that you have made a mistake somewhere. but I am not going to tell you much about it just yet. called Visual Studio Express edition.which may be part of the compiling and running system. in case you had forgotten to add a bit of your program. and debugger. The computer cannot understand the language directly. so a program called a compiler converts the C# text into the low level instructions which are much simpler. 1. print on the screen. The compiler would tell you about this. test and extend.Computers and Programs C# with it. An example of a warning situation is where you create something but don't use it for anything.e. It also lets you create programs which can have a high degree of reliability and stability.4. things that you type to the command prompt. The compiler will also flag up warnings which occur when it notices that you have done something which is not technically illegal. and we have to know how to program before we can design larger systems.4 Making C# Run You actually write the program using some form of text editor . The first thing it does is check for errors in the way that you have used the language itself. C# Programming © Rob Miles 2010 15 . Object Oriented Design makes large projects much easier to design. These low level instructions are in turn converted into the actual commands to drive the hardware which runs your program. Some parts of your program will simply provide this information to tell the compiler what to do. You must also decide on sensible names that you will use to identify these items. If you had sat down with a pencil and worked out the solution first you would probably get to a working system in around half the time. It also can be told about any options for the construction of your program which are important.NET framework. I am going to assume that you are using a computer which has a text editor (usually Notepad) and the . i.Computers and Programs C# I'm not going to go into details of how to download and install the .e. To take these in turn: Controlling the Compiler . which you will then spend hours fiddling with to get it going. This is not good technique. The C# compiler needs to know certain things about your program. I reckon that you write programs best when you are not sitting at the computer.4. for example a single structure could hold all the information about a particular bank customer. As part of the program design process you will need to decide what items of data need to be stored. A variable is simply a named location in which a value is held whilst the program runs. The recipe would be a list of ingredients followed by a sequence of actions to perform on them. not a cook. This is what the compiler acts on. All computer languages support variables of one form or another. Rather than writing the program down on a piece of paper you instead put it into a file on the computer. The Human Computer Of course initially it is best if we just work through your programs on paper. A program can be regarded as a recipe.NET framework installed. C# also lets you build up structures which can hold more than one item. the best approach is to write (or at least map out) your solution on paper a long way away from the machine.6 What Comprises a C# Program? If your mum wanted to tell you how to make your favourite fruitcake she’d write the recipe down on a piece of paper. often called a source file. that is for other documents. You will almost certainly end up with something which almost works. The ingredients will be values (called variables) that you want your program to work with. but written for a computer to follow. A source file contains three things: instructions to the compiler information about the structures which will hold the data to be stored and manipulated. The program itself will be a sequence of actions (called statements) that are to be followed by the computer. Programmer’s Point: Great Programmers debug less I am not impressed by hacking programmers who spend whole days at terminals fighting with enormous programs and debugging them into shape. Once you are sitting in front of the keyboard there is a great temptation to start pressing keys and typing something in which might work. instructions which manipulate the data. C# Programming © Rob Miles 2010 16 . Storing the Data Programs work by processing data. It needs to know which external resources your program is going to use. The data has to be stored within the computer whilst the program processes it. types in the program and makes it work first time! 1. I am impressed by someone who turns up. We will look at methods in detail later in these notes. Your mum might add the following instruction to her cake recipe: Now write the words “Happy Christmas” on top of the cake in pink icing. They are added automatically by the editor as you write your program. The colours just serve to make the programs easier to understand. and you try to make the name of the function fit what it does. These kinds of messages are coloured red in this text. Identifiers and Keywords You give a name to each method that you create. In fact. Seasoned programmers break down a problem into a number of smaller ones and make a method for each. and C# works in exactly the same way. The C# language actually runs your program by looking for a method with a special name. it is what needs to be written. and when Main finishes. for example add two numbers together and store the result. The really gripping thing about programs is that some statements can change which statement is performed next. which are used during the cooking process. One method may refer to others. for example ShowMenu or SaveToFile.Computers and Programs C# Describing the Solution The actual instructions which describe your solution to the problem must also be part of your program. Main. instruction to do something is in a C# program is called a statement. C# Programming © Rob Miles 2010 17 . Text in a Computer Program There are two kinds of text in your program. These save you from "re-inventing the wheel" each time you write a program. A single. To continue our cooking analogy. In a recipe a keyword would be something like "mix" or "heat" or "until". The names of objects will be given in a different shade of blue in some of the listings in this text. This method is called when your program starts running. A statement is an instruction to perform one particular operation. Keywords will appear blue in some of the listings in this text. these are things like mixing bowls and ovens. or very large. They would let you say things like "heat sugar until molten" or "mix until smooth". The names that you invent to identify things are called identifiers. She is using double quote characters to mark the text that is to be drawn on the cake. you'll find that programs look a lot like recipes. You also create identifiers when you make things to hold values. Later on we will look at the rules and conventions which you must observe when you create identifiers. It can have any name you like. woodLength might a good choice when we want to hold the length of wood required. It can return a value which may or may not be of interest. Colours and Conventions The colours that I use in this text are intended to line up with the colours you will see when you edit your programs using a professional program editor such as the one supplied as part of Visual Studio. so that your program can look at things and decide what to do. Such a lump is called a method. There are the instructions that you want the computer to perform and there are the messages that you want the program to actually display in front of the user. your program ends. The words which are part of the C# language itself are called keywords. and your program can contain as many methods as you see fit. A method can be very small. Objects Some of the things in the programs that we write are objects that are part of the framework we are using. In the case of C# you can lump statements together to form a lump of program which does one particular task. simple. ―Happy Christmas‖ is not part of the instructions. and do not have any special meaning. The C# language also has a huge number of libraries available which you can use. woodLength.ReadLine(). C# Programming © Rob Miles 2010 18 .1 The Program Example Perhaps the best way to start looking at C# is to jump straight in with our first ever C# program. height. We can now go through each line in turn and try to see how it fits into our program. 2.Parse(widthString). Here it is: using System. } } Code Sample 1 . height = double.1. The stuff after the two lines is concerned with displaying the answer to the user. Then we will use additional features of the C# language to improve the quality of the solution we are producing.WriteLine( "The area of the glass is " + glassArea + " square metres" ) .Simple Data Processing A First C# Program 2 Simple Data Processing In this chapter we are going to create a genuinely useful program (particularly if you are in the double glazing business). widthString = Console. class GlazerCalc { static void Main() { double width. woodLength = 2 * ( width + height ) * 3. This is the problem we set out to solve as described in section0. string widthString. Console.25 . We will start by creating a very simple solution and investigating the C# statements that perform basic data processing.1 A First C# Program The first program that we are going to look at will read in the width and height of a window and then print out the amount of wood and glass required to make a window that will fit in a hole of that size. Broadly speaking the stuff before these two lines is concerned with setting things up and getting the values in to be processed. glassArea. Console.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . heightString.Parse(heightString). If you gave it to a C# compiler it would compile.ReadLine(). width = double. 2. glassArea = 2 * ( width * height ) . The actual work is done by the two lines that I have highlighted. heightString = Console. and you could run it.GlazerCalc Program This is a valid program. If you miss out the Main method the system quite literally does not know where to start. However. For now. i. Main You choose the names of your methods to reflect what they are going to do for you. this must be a mistake. One of these useful things provided with C# is the Console object which will let me write things which will appear on the screen in front of the user.Simple Data Processing A First C# Program using System. This is an instruction to the C# compiler to tell it that we want to use things from the System namespace. This method (and there must be one. Oh. In the case of our double glazing calculator the class just contains a single method which will work out our wood lengths and glass area. in other words the program above should be held in a file called GlazerCalc. static This keyword makes sure that the method which follows is always present. void A void is nothing. This means that if I refer to something by a particular name the compiler will look in System to see if there is anything matching that name. A big part of learning to program is learning how to use all the additional features of the system which support your programs.e. and one other thing. I've called ours GlazerCalc since this reflects what it does. In programming terms the void keyword means that the method we are about to describe does not return anything of interest to us. The method will just do a job and then finish. We will use other namespaces later on. You need to invent an identifier for every class that you create. A C# program is made up of one or more classes. When we get to consider objects we will find that this little keyword has all kinds of interesting ramifications. In some cases we write methods which return a result (in fact we will use such a method later in the program). C# Programming © Rob Miles 2010 19 . When your program is loaded and run the first method given control is the one called Main. just make sure that you pick sensible names for the classes that you create. in order to stop someone else accidentally making use of the value returned by our Main method. We have namespaces in our conversations too. This makes our programs safer. A namespace is a place where particular names have meaning. if I am using the "Football" namespace and I say “That team is really on fire” I'm saying something good. don't worry too much about classes. the word static in this context means "is part of the enclosing class and is always here". If I am using the "Firefighter" namespace I'm saying something less good. There is a convention that the name of the file which contains a particular class should match the class itself. If I want to just refer to this as Console I have to tell the compiler I'm using the System namespace. and only one such method) is where your program starts running. But for now I'd be grateful if you'd just make sure that you put it here in order to make your programs work properly. as we shall see later. class GlazerCalc Classes are the basis of object oriented programming. Except for Main. we are explicitly stating that it returns nothing. In the case of C# the System namespace is where lots of useful things are described.cs. but a class can contain much more than that if it needs to. in that the compiler now knows that if someone tries to use the value returned by this method. A class is a container which holds data and program code to do a particular job. you 2010 2010 2010 22 for two panes of glass). Note that I use a factor of 3.25 . However. so I multiply the result in meters by this factor.ReadLine(). Console. so I did what you would do in mathematics. I've put one multiplication in brackets to allow me to indicate that I am working out two times the area (i. The calculation is an expression much like above.25 feet in a meter.25 to allow for the fact that the customer wants the length of wood in feet. The + and * characters in the expression are called operators in that they cause an operation to take place. There is no need to do this particularly. i. These are what the operators work on. The other items in the expression are called operands.Simple Data Processing A First C# Program heightString = Console. This line repeats the calculation for the area of the glass. It is a string of text which is literally just in the program. not instructions to the compiler itself. all multiplication and division will be done first. followed by addition and subtraction.Parse(heightString). glassArea = 2 * ( width * height ) . 2 Another TV show reference C# Programming © Rob Miles 2010 23 . except that this one takes what it is given and then prints it out on the console. This is the bit that does the work. this time it is important that you notice the use of parenthesis to modify the order in which values are calculated in the expression. Note that the area is given in square meters. + Plus is an addition operator. Normally C# will work out expressions in the way you would expect.e. In this case it means "add two strings together". so no conversion is required. The string of text is enclosed in double quote characters to tell the compiler that this is part of a value in the program. We have seen these used in the calls of Parse and also ReadLine "The length of the wood is " This is a string literal.e. It takes the height and width values and uses them to calculate the length of wood required. I put brackets around the parts to be done first. woodLength = 2*(width + height)*3. When I write programs I use brackets even when the compiler does not need them. height = double. This is the actual nub of the program itself. the plus here means something completely different 2.WriteLine This is a call of a method. ( This is the start of the parameters for this method call. These two statements simply repeat the process of reading in the text of the height value and then converting it into a double precision value holding the height of the window. There are around 3. In the above expression I wanted to do some parts first. This makes the program clearer. We have seen it applied to add two integers together. but I think it makes it slightly clearer. just like the ReadLine method. This means that it is going to perform string concatenation rather than mathematical addition. This difference in behaviour is all because of the context of the operation that is being performed. We are adding the word feet on the end. The variable woodLength is tagged with metadata which says "this is a double precision floating point value. in this program the length of the wood required. giving the output: 5 But the line of code: Console. Here it is with operators.0 + 3. When the method is called the program first assembles a completed string out of all the components.0 ). Previously we have used woodLength as a numeric representation of a value. The C# compiler must therefore ask the woodLength data item to convert itself into a string so it can be used correctly in this position. adding (or concatenating) them to produce a single result. C# Programming © Rob Miles 2010 24 .03 The string "2.0 added on the end. Here it has a string on the left hand side. However.0 + 3. This would perform a numeric calculation (2. and so the program works as you would expect. use a plus with this and you concatenate".WriteLine ( "2.0" + 3. use a plus with this and you perform arithmetic". Whenever I print a value out I always put the units on the end.0 ). in the context it is being used at the moment (added to the end of a string) it cannot work like that. Consider: Console. Fortunately it can do this. It would then produce the output: 2.Simple Data Processing A First C# Program You will have to get used to the idea of context in your programs. The C# system uses the context of an operation to decide what to do.0" has the text of the value 3. It would ask the value 3 to convert itself into a string (sounds strange – but this is what happens. woodLength This is another example of context at work. between two double precision floating point numbers it means "do a sum". It is very important that you understand precisely what is going on here. This result value would then be asked to provide a string version of itself to be printed. It then passes the resulting string value into the method which will print it out on the console. This makes it much easier to ensure that the value makes sense.0) and produce a double precision floating point value. + " feet" Another concatenation here. Would regard the + as concatenating two strings. The variable heightString is tagged with information that says "this is a string. We have seen this with namespaces. ) The bracket marks the end of the parameter being constructed for the WriteLine method call. In the case of the previous +.WriteLine ( 2. You can think of all of the variables in our program being tagged with metadata (there is that word again) which the compiler uses to decide what to do with them. glassArea. It marks the end of the class GlazerCalc.Simple Data Processing A First C# Program . Items inside braces are indented so that it is very clear where they belong.width = double.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . Punctuation That marks the end of our program. woodLength.widthString = Console.heightString = Console. I do it because otherwise I am just about unable to read the program and make sense of what it does. A block of code starts with a { and ends with a }. heightString.ReadLine(). otherwise you will get what is called a compilation error. The program is essentially complete. This first close brace marks the end of the block of code which is the body of the Main method. We have added all the behaviours that we need.} } . If we want to (and we will do this later) we may put a number of methods into a class. } The second closing brace has an equally important job to the first.Console. For now however. note that just because the compiler reckons your program is OK is no guarantee of it doing what you want! Another thing to remember is that the layout of the program does not bother the compiler. However. And so we use the second closing brace to mark the end of the class itself.height = double.. A class is a container for a whole bunch of things. consider the effect of missing out a "(" character. I do not do this because I find such listings artistically pleasing. the following is just as valid: using System. one of the things you will find is that the compiler does not always detect the error where it takes place. The semi-colon marks the end of this statement. One of the things that you will have noticed is that there is an awful lot of punctuation in there.WriteLine ( "The length of the wood is " + woodLength + " feet" ) .ReadLine().string widthString. including methods.Parse(widthString). C# Programming © Rob Miles 2010 25 . When the compiler sees this it says to itself "that is the end of the Main method".Parse(heightString).Console. However.25 . This simply indicates that the compiler is too stupid to make sense of what you have given it! You will quickly get used to hunting for and spotting compilation errors. height.woodLength = 2 * ( width + height ) * 3. This is vital and must be supplied exactly as C# wants it. we only want the one method in the class.glassArea = 2 * ( width * height ) . } Now for some really important stuff. In C# everything exists inside a class. JustlikeIfindithardtoreadenglishwithouttheproperspacing I find it hard to read a program if it has not been laid out correctly.class GlazerCalc{static void Main(){double width. 1 Variables and Data In the glazing program above we decided to hold the width and the height of the windows that we are working on in variables that we described as double. Think of this as C# creating a box of a particular size. To handle real values the computer actually stores them to a limited accuracy. Too much accuracy may slow the machine down .Simple Data Processing Manipulating Data 2. you always have an exact number of these items.2 Manipulating Data In this section we are going to take a look at how we can write programs that manipulate data. how values can be stored. A variable is a named location where you can store something. We also need to consider the range of possible values that we need to hold so that we can choose the appropriate type to store the data. Before we can go much further in our programming career we need to consider just what this means. Because we know that it works in terms of ons and offs it has problems holding real values.e. specifically designed to hold items of the given type. These are real. which we hope is adequate (and usually is). The declaration also identifies the type of the thing we want to store.too little may result in the wrong values being used. i. for example the number of sheep in a field. 2. When you are writing a specification you should worry about the precision to which values are to be held. otherwise it is useless. apples in a basket. teeth on a cog. You can think of it as a box of a particular size with a name painted on the box. A computer is digital. You chose the name to reflect what is going to be stored there (we used sensible names like woodLength in the above program). This provides us with the ability to perform the data processing part of programs. retrieved and generally fiddled with. Programs also contain literal values. This means that when we want to store something we have to tell the computer whether it is an integer or a real. In the second case we can never hold what we are looking at exactly. Even if you measure a piece of string to 100 decimal places it is still not going to give you its exact length . You tell C# about a variable you want to create by declaring it. The type of the variable is part of the metadata about that variable. What the data actually means is something that you as programmer decide (see the above digression on data). These are referred to as reals. the speed of a car. Nasty real world type things. Programs operate on data. These are referred to as integers.2 Storing Numbers When considering numeric values there are two kinds of data: Nice chunky individual values. and what other types of data we can store in programs that we write. For each type of variable the C# language has a way in which literal values of that type are expressed. A programming language must give you a way of storing the data you are processing.you could always get the value more accurately. 2. A literal value is just a value in your program which you use for some purpose.2. for example the current temperature. the length of a piece of string. You also need to choose the type of the variable (particular size and shape of box) from the range of storage types which C# provides.2. they are integral. it operates entirely on patterns of bits which can be regarded as numbers. The box is tagged with some metadata (there is that word again) so that the system knows what can be put into it and how that box can be used. In the first case we can hold the value exactly. C# Programming © Rob Miles 2010 26 . I could use it in my program as follows: numberOfSheep = 23 . Remember that the language itself is unaware of any such considerations. Which could cause my program big problems. This means that if I do something stupid: sbyte tinyVal = 128. An example of an integer variable would be something which kept track of the number of sheep in a field: int numberOfSheep. When you edit your program source using Visual Studio (or another code editor that supports syntax highlighting) you will find that the names of types that are built into the C# language (such as int and float) are displayed in blue. Programmer’s Point: Check your own maths Something else which you should bear in mind is that a program will not always detect when you exceed the range of a variable.000 sheep and the number of sheep never goes negative you must add this behaviour yourself. The bigger the value the larger the number of bits that you need to represent it. int. C# provides a variety of integer types. in the range -2.147. integer literal values An integer literal is expressed as a sequence of digits with no decimal Point: 23 This is the integer value 23. If I put the value 255 into a variable of type byte this is OK. The only issue is one of range. C# Programming © Rob Miles 2010 27 .647 If you want to hold even larger integers than this (although I've no idea why you'd want this) there is a long version. depending on the range of values you would like to store: sbyte byte short ushort int uint long ulong char Note that we can go one further negative than positive. This creates a variable with could keep track of over two thousand million sheep! It also lets a program manipulate "negative sheep" which is probably not meaningful (unless you run a sheep bank of course and let people borrow them). In fact this may cause the value to "wrap round" to 0. This is because the numbers are stored using "2's complement" notation. can hold frighteningly large numbers in C#.648 to 2.483.Simple Data Processing Manipulating Data Storing integer values Integers are the easiest type of value for the computer to store. because 255 is the biggest possible value of the type can hold. If you want to make sure that we never have more than 1.147. not an integer. as shown above. Each value will map onto a particular pattern of bits. if I add one to the value in this variable the system may not detect this as an error.. If I am using one of the "shorter" types the literal value is regarded by the compiler as being of that type: sbyte tinyVal = 127. However. In this statement the 127 is regarded as an sbyte literal.483. Finally. An example of a float variable could be something which held the average price of ice cream: float averageIceCreamPriceInPence. C# provides a type of box which can hold a real number. If you want more precision (although of course your programs will be use up more computer memory and run more slowly) you can use a double box instead (double is an abbreviation for double precision). as float or as double.e.7E308 and a precision of 15 digits. They have a decimal point and a fractional part. hence the name float. If you put an f on the end it becomes a floating point literal value. not as good as most pocket calculators). decimal robsOverdraft. with real numbers the compiler is quite fussy about how they can and can't be combined. This means that you have to take special steps to make sure that you as programmer make clear that you want this to happen and that you can live with the consequences. C# Programming © Rob Miles 2010 28 . A standard float value has a range of 1. This uses twice the storage space of a double and holds values to a precision of 28-29 digits. An example of a double variable could be something which held the width of the universe in inches: double univWidthInInches. Depending on the value the decimal point floats around in the number. real literal values There are two ways in which you can store floating point numbers. A float literal can be expressed as a real number with an f after it: 2.0E-324 to 1. This is because when you move a value from a double precision variable into an ordinary floating point one some of the precision is lost. When it comes to putting literal values into the program itself the compiler likes to know if you are writing a floating point value (smaller sized box) or double precision (larger sized box).Simple Data Processing Manipulating Data (the maximum value that an sbyte can hold is 127) the compiler will detect that I have made a mistake and the program will not compile. It is used in financial calculations where the numbers are not so large but they need to be held to very high accuracy. if you want the ultimate in precision but require a slightly smaller range you can use the decimal type.4E48 with a precision of only 7 digits (i. This is takes up more computer memory but it has a range of 5.5f A double literal is expressed as a real number without the f: 3. Unlike the way that integers work.5E-45 to 3.4605284E15 This is a double precision literal value which is actually the number of meters in a light year. Storing real values "Real" is a generic term for numbers which are not integers.5 You can also use exponents to express double and float values: 9. This process is known as casting and we will consider it in detail a bit later. tend to use just integers (int) and floating point (float) variable types. If you are editing your program using an editor that supports syntax highlighting a character literal is shown in red. 2. This is a sequence of characters which starts with a special escape character. You can use them as follows: char beep = '\a' . Some clear the screen when you send the Form feed character.000 different character designs including a wide range of foreign characters. This is achieved by the use of an escape sequence. Some systems will make a beep when you send the Alert character to them. C# uses a character set called UNICODE which can handle over 65. This may seem wasteful (it is most unlikely I'll ever need to keep track of two thousand million sheep) but it makes the programs easier to understand.2. C# provides variables for looking after both of these types of information: char variables A char. A character is what you get when you press a key on a keyboard or display a single character on the screen. The escape character is the \ (backslash) character. Escape in this context means "escape from the normal hum-drum conventions of just meaning what you are and let's do something special". C# Programming © Rob Miles 2010 29 . It is what your program would get if you asked it to read a character off the keyboard and the user held down shift and pressed A.Simple Data Processing Manipulating Data Programmer’s Point: Simple variables are probably best You will find that I. at other times it will be a string. char literal values You express a character by enclosing it in single quotes: 'A' This means "the character A". An example of a character variable could be something which held the command key that the user has just pressed: char commandKey. Character Escape Sequences This leads to the question "How do we express the ' (single quote) character". and most programmers.3 Storing Text Sometimes the information we want to store is text. This can be in the form of a single character. C# Programming © Rob Miles 2010 30 . Note that I have to put leading zeroes in front of the two hex digits. you can express a character literal as a value from the Unicode character set. An example of a string variable could be something which holds the line that the user has just typed in: string commandLine. However. I do this by putting an @ in front of the literal: @"\x0041BCDE\a" If I print this string I get: \x0041BCDE\a This can be useful when you are expressing things like file paths. The bad news is that you must express this value in hexadecimal which is a little bit harder to use than decimal.Simple Data Processing Manipulating Data Note that the a must be in lower case. As an example however. C# uses the Unicode standard to map characters onto numbers that represent them. 41). string literal values A string literal value is expressed enclosed in double quotes: "this is a string" The string can contain the escape sequences above: "\x0041BCDE\a" If we print this string it would print out: ABCDE . if at all. The best news of all is that you probably don't need to do this kind of thing very often. A string variable can hold a line of text. string variables A type of box which can hold a string of text. or it can be very long. If you wish. Character code values We have already established that the computer actually manipulates numbers rather than actual letters. which is that you can use it to get string literals to extend over several lines: @"The quick brown fox jumps over the lazy dog" This expresses a string which extends over three lines. because there are special characters which mean "take a new line" (see above) it is perfectly possible for a single string to hold a large number of lines of text. In C# a string can be very short.and try to ring the bell. I can therefore put this in my program as: char capitalA = '\x0041' .e. for example "War and Peace" (that is the book not the three words). I happen to know that the Unicode value for capital a (A) is 65. If I am just expressing text with no escape characters or anything strange I can tell the compiler that this is a verbatim string. for example "Rob". The line breaks in the string are preserved when it is stored. This is represented in hexadecimal (base 16) as four sixteens and a single one (i. The good news is that this gives you access to a huge range of characters (as long as you know the codes for them). The verbatim character has another trick. 2.4 Storing State using Booleans A bool (short for boolean) variable is a type of box which can hold whether or not something is true. They introduce a lack of precision that I am not too keen on. As an example. you might think that being asked to work with the speed of a car you would have to store a floating point value. bool literal values These are easily expressed as either true or false: networkOK = true . when you are given the prospect of storing floating point information. char 29yesitsme . when you find out that the speed sensor only gives answers to an accuracy of 1 mile per hour. For example. Fred and fred are different identifiers. I find that with a little bit of ingenuity I can work in integers quite comfortably. one of which are not valid (see if you can guess which one and why): int fred . However. along with "always use the keyboard with the keys uppermost" is: Always give your variables meaningful names.e. One of the golden rules of programming. the best relationships are meaningful ones.5 Identifiers In C# an identifier is a name that the programmer chooses for something in the program. Also when considering how to store data it is important to remember where it comes from. This illustrates another metadata consideration. If you are storing whether or not a subscription has been paid or not there is no need to waste space by using a type which can hold a large number of possible values. Instead you just need to hold the states true or false. An example of a bool variable could be one which holds the state of a network connection: bool networkOK. C# has some rules about what constitutes a valid identifier: All identifiers names must start with a letter. This is really stupid. find out how it is being produced before you decide how it will be stored. Here are a few example declarations.5 pounds (needing the use of float) I will store the price as 150 pence.Simple Data Processing Manipulating Data 2. I tend to use floating point storage only as a last resort. float jim . C# Programming © Rob Miles 2010 31 . rather than store the price of an item as 1. this makes the job much simpler. Programmer’s Point: Think about the type of your variables Choosing the right type for a variable is something of a skill. According to the Mills and Boon romances that I have read. In the example above I've used the double type to hold the width and height of a window. Sometimes that is all you want. 2. The name of a variable is more properly called an identifier. We will see other places where we create identifiers. I would suspect that my glazing salesman will not be able to measure to accuracy greater than 1 mm and so it would make sense to only store the data to that precision. i.2. These are the only two values which the bool type allows. Upper and lower case letters are different. It does not take into account the precision required or indeed how accurately the window can be measured. After the letter you can have either letters or numbers or the underscore "_" character. Perhaps the name averageIceCreamPriceInPence is a bit over the top in this respect. An assignment gives a value to a specified variable. Gozzintas take the result on the right hand side of the assignment and drop it into the box on the left. The equals in the middle is there mainly to confuse us. I like to think of it as a gozzinta (see above). it does not mean equals in the numeric sense. These are assignment statements.2. first = 1 .Simple Data Processing Manipulating Data The convention in C# for the kind of variables that we are creating at the moment is to mix upper and lower case letters so that each word in the identifier starts with a capital: float averageIceCreamPriceInPence. Expressions can be as simple as a single value and as complex as a large calculation. 2.is a piece of programming naughtiness which would cause all manner of nasty errors to appear. We can then use the result as we like in our program. There are two parts to an assignment. C# does this by means of an assignment statement. second = 2 . second and third. . Remember that you can always do sensible things with your layout to make the program look OK: averageIceCreamPriceInPence = computedTotalPriceInPence / numberOfIceCreams. C# Programming © Rob Miles 2010 32 . does not know or care what you are doing). presumably because of the "humps" in the identifier which are caused by the capitals. operators and operands. These are each of integer type. which must be of a sensible type (note that you must be sensible about this because the compiler. and get the value out. The value which is assigned is an expression. Programmer’s Point: Think about the names of your variables Choosing variable names is another skill you should work at. Expressions An expression is something which can be evaluated to produce a result. for example consider the following: class Assignment { static void Main () { int first. the thing you want to assign and the place you want to put it. They are made up of two things. Within the Main function we have declared three variables. third . This is sometimes called camel case. which means that: 2 = second + 1. But I could live with it. first. as we already know. second. second = second + first .6 Giving Values to Variables Once we have got ourselves a variable we now need to know how to put something into it. The last three statements are the ones which actually do the work. They should be long enough to be expressive but not so long that your program lines get too complicated. } } The first part of the program should be pretty familiar by now. because of the difficulty of drawing one number above another on a screen we use this character instead Addition.g. generally speaking things tend to be worked out how you would expect them. just as in traditional maths all the multiplication and division is performed first in an expression. multiplication. They are usually literal values or the identifiers of variables. provided you make sure that you have as many open ones as close ones. This is not a complete list of all the operators available. Here are a few example expressions: 2 + 3 * 4 -1 + 3 (2 + 3) * 4 These expressions are worked out (evaluated) by C# moving from left to right.2. This can cause problems as we shall see now. Again. -1. but it will do for now. C# does this by giving each operator a priority. e. You can put brackets inside brackets if you want. third are identifiers and 2 is a literal value. Because these operators work on numbers they are often called the numeric operators. Being a simple soul I tend to make things very clear by putting brackets around everything. Note that we use exactly the same character as for unary minus. * / + unary minus. Note that this means that the first expression above will therefore return 14 and not 20. It is probably not worth getting too worked up about this expression evaluation as posh people call it. Most operators work on two operands. It worries about whether or not the operation I'm about C# Programming © Rob Miles 2010 33 . division.Simple Data Processing Manipulating Data Operands Operands are things the operators work on. 2. If you want to force the order in which things are worked out you can put brackets around the things you want done first. It is also possible to use operators in a way which causes values to be moved from one type to another. subtraction. It then looks for the next ones down and so on until the final result is obtained. In the program above first. as in the final example. the minus that C# finds in negative numbers. When C# works out an expression it looks along it for all the operators with the highest priority and does them first. A literal value is something which is literally there in the code.7 Changing the Type of Data Whenever I move a value from one type to another the C# compiler gets very interested in what I am doing. note the use of the * rather than the more mathematically correct but confusing x. I am listing the operators with the highest priority first. A literal value has a type associated with it by the compiler. second. one each side. For completeness here is a list of all operators. Operators Operators are the things which do the work: They specify the operation to be performed on the operands. just as you would yourself. But of course you should remember that some of them (for example +) can be used between other types of data as well. Unary means applying to only one item. followed by the addition and subtraction. what they do and their precedence (priority). In the program above + is the only operator. If I decide to switch to a smaller case I will have to take everything out of the large case and put it into the smaller one. This means that if you do things like this: int i . . . You cast a value by putting the type you want to see there in brackets before it. I. In the above code the message to the compiler is "I don't care that this assignment could cause the loss of information. I do not think of this as a failing in C#.would cause the compiler to complain (even though at the moment the variable x only holds an integer value). Casting We can force C# to regard a value as being of a certain type by the use of casting. This means that if I write: int i = 1 . In C# terms the "size" of a type is the range of values (the biggest and smallest) and the precision (the number of decimal places).5.. int i = x . You can regard casting as the compiler's way of washing its hands of the problem. The bigger case will take everything that was in the smaller case and have room for more. A cast takes the form of an additional instruction to the compiler to force it to regard a value in a particular way.5. and the range of floating point values is much greater than that for integers. Widening and Narrowing The general principle which C# uses is that if you are "narrowing" a value it will always ask you to explicitly tell it that this is what you want to do. If a program fails because data is lost it is not because the compiler did something silly. as the writer of the program. each type of variable has a particular range of possible values. Nothing in C# checks for mistakes like this. However: float x = 1. since the compiler knows that a double is wider than a float.. If you are widening there is no problem.999 . float f = (float) d . It considers every operation in terms of "widening and narrowing" values.. will take the responsibility of making sure that the program works correctly". for example: double d = 1.the cast is doomed to fail.the program will not notice but the user certainly will! C# Programming © Rob Miles 2010 34 . . It is up to you when you write your program to make sure that you never exceed the range of the data types you are using . However. float x = i. To understand what we mean by these terms we could consider suitcases. The value which gets placed in i will be invalid. As we saw above.Simple Data Processing Manipulating Data to perform will cause data to be lost from the program. i = (int) 123456781234567890. It gives you great flexibility.would cause an error as well. Note that this applies within a floating point values as well. For example: double d = 1. If I am packing for a trip I will take a case. at the cost of assuming you know what you are doing. float f = d . This works fine because the floating point type can hold all the values supported by the integer type. But it might not have room. if I change to a bigger case there is no problem. The compiler is concerned that you may be discarding information by such an assignment and treats it as an error. so I have to leave behind one of my shirts. This is "narrowing". because it involves a floating point value would however be evaluated to give a double precision floating point result. This process discards the fractional part.4f . It therefore would calculate this to be the integer value 0 (the fractional part is always truncated).999 (which would be compiled as a value of type double) and casts it to int. .2.0 by the string "stupid". and this includes how it allows literal values to be used.4 . it is not.4 is a double precision value when expressed as a literal. x = 3. This code looks perfectly legal. should give an integer result. C# Programming © Rob Miles 2010 35 . and the variable x has been declared as a floating point. However. These are just values you want to use in your calculations. consider the following: 1/2 1/2.999 . The code above takes 1.25 to convert the length value from meters to feet (there are about 3. Essentially. consider this: float x . i = 3. The C# compiler knows that it is daft to divide the value 3. even though the original number was much closer to 2. C# keeps careful track of the things that it is combining. This casts the double precision literal into a floating point value.8 Types of Data in Expressions When C# uses an operator. the more accurate answer of 0. . The second expression.will be treated with the contempt they richly deserve.25 feet in a meter). This means that: float x . decimal) into one without.0 You might think that these would give the same result. x = 3. This can lead to problems. if the two operands are integer it says that the result should be integer.4 . This is because the literal value 3. it makes a decision as to the type of the result that is to be produced. in our double glazing program we had to multiply the wood length in meters by 3.Simple Data Processing Manipulating Data A cast can also lose information in other ways: int i . x = (float) 3. For example.4 / "stupid" . i = (int) 1. This is so that statements like: int i . If the two are floating point it says that the result should be floating point. so that the assignment works. If I want to put a floating point literal value into a floating point variable I can use casting: float x . To make life easier the creators of C# have added a different way we can express a floating point literal value in a program. which involves only integers.would compile correctly. double. Not so. However. The compiler thinks that the first expression. You should remember that this truncation takes place whenever you cast from a value with a fractional part (float.5. 2. If you put an f after the value this is regarded as a floating point value. which means that the variable I will end up with the value 1 in it. Casting and Literal Values We have seen that you can put "literal" values into your program. this can make the program clearer. Console.2. so that we get 1. who runs a chemist shop. fraction = (float) i / (float) j .WriteLine ( "The length of the wood is " + woodLength + " feet" ) .25 .ReadLine().Simple Data Processing Manipulating Data The way that an operator behaves depends on the context of its use. "Ro" + "b" would give the result "Rob".Parse(heightString). and the number of bottles that he needs. store it in an appropriate type of location and then uses the stored values to calculate the result that the user requires: string widthString = Console. string heightString = Console. He enters the cost of the tablets and the number he wants. the only hard part is figuring out how many bottles that are needed for a particular number of tablets. glassArea = 2 * ( width * height ) . j = 2 .Parse(widthString). Console. If you want complete control over the particular kind of operator the compiler will generate for you the program must contain explicit casts to set the correct context for the operator. 2. class CastDemo { static void Main () { int i = 3. You can very easily modify your program to do this job. If you just divide the number of tablets by 100 an integer division will give you the wrong answer (for any number of tablets less than 100 your program will tell you that 0 bottles are needed). woodLength = 2 * ( width + height ) * 3. One way to solve this is to add 99 to the number of tablets before you C# Programming © Rob Miles 2010 36 . consider another friend of yours.e. i. height = double. Programmer’s Point: Casts can add clarity I tend to put the casts in even if they are not needed.ReadLine(). double width = double. He wants a program that will work out the total cost of tablets that he buys.WriteLine ( "fraction : " + fraction ) . The tablets are always sold in bottles of 100. Console.9 Programs and Patterns At this point we can revisit our double glazing program and look at the way that it works.5 printed out rather than 1. Later on we will see that the + operator. The interesting thing about this is that it is a pattern of behaviour which can be reused time and time again. can be used between strings to concatenate them together. The code that actually does the work boils down to just a few lines which read in the data. As an example. which normally performs a numeric calculation.WriteLine("The area of the glass is " + glassArea + " square metres" ) . It may not affect the result of the calculation but it will inform the reader of what I am trying to do. using System. float fraction . } } The (float) cast in the above tells the compiler to regard the values in the integer variables as floating point ones. print it out) which is common to many applications.ReadLine().Parse(pricePerBottleString). The different blocks should be indented and the statements spread over the page in a well formed manner. It should have good punctuation and grammar. A good program is well laid out. The interesting thing here is that the program for the chemist is actually just a variation on the program for the double glazing salesman.WriteLine( "The total price is " + salePrice ) . I think that while it is not a story as such. All the names in the text should impart meaning and be distinct from each other. They may have to make a decision based on the data which they are given. This makes the active part of the program as follows: int bottleCount = ((tabletCount + 99) / 100) . do something with it and then print out the result. In this section we are going to consider how we can give our programs that extra level of complexity. We can then put the rest of the code around this to make a finished solution: Remember that if you divide two integers the result is always rounded down and the fractional part discarded. int salePrice = bottleCount * pricePerBottle .ReadLine(). Part of the skill of a programmer is identifying the nature of a problem in terms of the best pattern to be used to solve it. I'm not completely convinced that this is true. works out some answers and then prints out the result you can make use of this pattern. However. string tabletCountString = Console. Console. 2. we will need to create programs which do things which are more complex that this.Simple Data Processing Writing a Program perform the division. I have found that some computer manuals are works of fiction. int bottleCount = ((tabletCount + 99) / 100) . int pricePerBottle = int. int tabletCount = int. int salePrice = bottleCount * pricePerBottle . process it. At no point should the hapless reader be forced to backtrack or brush up on knowledge that the writer assumes is there. They may need to repeat things until something is true. string pricePerBottleString = Console.3 Writing a Program The programs that we have created up until now have been very simple. Both conform to a pattern of behaviour (read data in. Any time that you are asked to write a program that reads in some data. They just read data in.Parse(tabletCountString). but programs are something else. C# Programming © Rob Miles 2010 37 . and look at the general business of writing programs. Console. a good program text does have some of the characteristics of good literature: It should be easy to read.3. It should look good on the page. forcing the number of bottles required to "round up" any number of tablets greater than 0.WriteLine ( "The number of bottles is " + bottleCount ) .1 Software as a story Some people say that writing a program is a bit like writing a story. The various components should be organised in a clear and consistent way. 2. They may need to read in a large amount of data and then process that in a number of different ways. If you chose sensible identifiers you should find that your program will express most of what it does directly from the code itself. Block Comments When the C# compiler sees the "/*" sequence which means the start of a comment it says to itself: “Aha! Here is a piece of information for greater minds than mine to ponder. A program without comments is a bit like an aeroplane which has an autopilot but no windows. Basically there are three types of program flow: 1. when it was last modified and why.2 Controlling Program Flow Our first double glazing program is very simple. If you change what you wrote you should add information about the changes that you made and why. Line Comments Another form of comment makes use of the // sequence. They help to make your program much easier to understand. This marks the start of a comment which extends to the end of that particular line of code. It is useful for putting a quick note on the end of a statement: position = position + 1 . 2. But don't go mad. // move on to the next customer I've annotated the statement to give the reader extra information about what it actually does. If you write something good you should put your name on it. it runs straight through from the first statement to the last. You will be very surprised to find that you quickly forget how you got your program to work. There is a chance that it might take you to the right place. 3. A big part of a well written program is the comments that the programmer puts there. I will ignore everything following until I see a */ which closes the comment. Programmer’s Point: Don't add too much detail Writing comments is a very sensible thing to do. and when it was last changed. and the name of the programmer who wrote it – even if it was you. 2.” As an example: /* This program works out glass and wood required for a double glazing salesman. straight line chosen depending on a given condition repeated according to a given condition C# Programming © Rob Miles 2010 38 . but it will be very hard to tell where it is going from the inside. Often you will come across situations where your program must change what it does according to the data which is given to it. // add one to goatCount This is plain insulting to the reader I reckon. and then stops. */ Be generous with your comments. You can also use comments to keep people informed of the particular version of the program .Simple Data Processing Writing a Program It should be clear who wrote it. to in logical expressions. Relational operators work on operands, just like numeric ones. However any expression involving them can only produce one of two values, true or false. Relational operators available are as follows: C# Programming © Rob Miles 2010 2010 2010 41 class GlazerCalc { static void Main() { double width. widthString = Console. There is a convention that you always give constant variables names which are expressed in CAPITAL LETTERS.Parse(heightString). Console. heightString = Console. This both more meaningful (we are using PI not some anonymous value) and makes the program quicker to write. We can do this by making a variable which is constant.WriteLine ( "Width is too large. MIN_WIDTH = 0.75 .0. for some reason.Parse(widthString).WriteLine ( "Using minimum" ) . it can never be changed. This means that you can do things like: circ = rad * 2 * PI . const const const const double double double double MAX_WIDTH = 5.75 and 3. for example: const double MAX_WIDTH 5.0 . my maximum glass size becomes 4.0 . These come from the metadata I was so careful to gather when I wrote the specification for the program. MIN_HEIGHT = 0.Write ( "Give the width of the window : " ). i. This is so that when you read your program you can tell which things have been defined. If.WriteLine ( "Using maximum" ) . glassArea.e.Simple Data Processing Writing a Program values for heights and widths. what I would like to do is replace each number with something a bit more meaningful. const double PI=3.Write ( "Give the height of the window : " ).0 .but these are not packed with meaning and make the program hard to change.0 . } Console. height = double. 0.5 metres I have to look all through the program and change only the appropriate values.5 . Console. woodLength. Now I could just use the values 0. heightString. Anywhere you use a magic number you should use a constant of this form. I do not like the idea of "magic numbers" in programs.ReadLine(). height. C# Programming © Rob Miles 2010 42 . width = MAX_WIDTH .5. Console. if (width < MIN_WIDTH) { Console. and also much easier to change.141592654. width = double.ReadLine(). width = MIN_WIDTH . This makes your programs much easier to read.\n\n" ) . } if (width > MAX_WIDTH) { Console. 5. MAX_HEIGHT = 3. string widthString.WriteLine ( "Width is too small" ) . We can therefore modify our double glazing program as follows: using System. C# allows us to do this by providing looping constructions. do -.while loop In the case of our little C# program we use the do -. depending on precisely what you are trying to do. giving a proper number should cause our loop to stop.while construction which looks like this: C# Programming © Rob Miles 2010 43 . 2.\n\n" ) . glassArea = 2 * ( width * height ) .25 . This means that if we get the number correctly first time the loop will execute just once. In the case of our program we want to repeatedly get numbers in until while we are getting duff ones.WriteLine ( "Using height = MAX_HEIGHT . (the rest is finding out why the tool didn't do what you expected it to!).\n\n" ) . Console. maximum" ) .WriteLine ( "Using height = MIN_HEIGHT .3. However I would still not call it perfect.WriteLine( "Height Console. minimum" ) .Simple Data Processing Writing a Program if (height < MIN_HEIGHT) { Console.. i. C# has three ways of doing this. or a given number of times. However often you want to repeat something while a particular condition is true. You might think that I have pulled a fast one here. } } This program fulfils our requirements. What we would really like is a way that we can repeatedly fetch values for the width and height until we get one which fits. is too large. Most of the skill of programming involves picking the right tool or attachment to do the job in hand.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . Console. with the height having to be entered again. If our salesman gives a bad height the program simply limits the value and needs to be re-run. } if (height > MAX_HEIGHT) { Console. woodLength = 2 * ( width + height ) * 3. Note that we get three methods not because we need three but because they make life easier when you write the program (a bit like an attachment to our chainsaw to allow it to perform a particular task more easily).e. } is too small.WriteLine( "Height Console.WriteLine ( "The length of the wood is " + woodLength + " feet" ) .3 Loops Conditional statements allow you to do something if a given condition is true. e. energy futures and cosmology. i. Wet Your Hair Add Shampoo and Rub vigorously. A condition in this context is exactly the same as the condition in an if construction. class Forever { public static void Main () { do Console. for loop Often you will want to repeat something a given number of times. Note that the test is performed after the statement or block. i. Your electricity runs out. Rinse with warm water. This allows us to repeat a chunk of code until the condition at the end becomes false. The loop constructions we have given can be used to do this quite easily: C# Programming © Rob Miles 2010 44 . Just as it is possible with any old chainsaw to cut off your leg if you try really hard so it is possible to use any programming language to write a program which will never stop. (if you put the do in the compiler will take great delight in giving you an error message ..Simple Data Processing Writing a Program do statement or block while (condition) . raising the intriguing possibility of programs like: using System. } } This is a perfectly legal C# program. This is a chainsaw situation. You get bored with it. It reminds me of my favourite shampoo instructions: 1. I wonder how many people are still washing their hair at the moment? while loop Sometimes you want to decide whether or not to repeat the loop before you perform it.WriteLine ( "Hello mum" ) . 2. 4. How long it will run for is an interesting question. For our program this is exactly what we want. it will run until: 1. even if the test is bound to fail the statement is performed once. If you think about how the loop above works the test is done after the code to be repeated has been performed once. while ( true ). 2. Repeat.but you had already guessed that of course!). The universe implodes.e. the answer contains elements of human psychology. not a powerful chainsaw situation. 3. 3. we need to ask for a value before we can decide whether or not it is valid. i = 1 . i = i + 1 . } } } The setup puts a value into the control variable which it will start with. The update is the statement which is performed to update the control variable at the end of each loop. for ( i = 1 . C# provides a construction to allow you to set up a loop of this form all in one: for ( setup .loop to continue. } } } The variable which controls things is often called the control variable. class WhileLoopInsteadOfFor { public static void Main () { int i . And serve you right. If you are so stupid as to mess around with the value of the control variable in the loop you can expect your program to do stupid things. finish test . 4. Perform the update. and is usually given the name i. class ForLoop { public static void Main () { int i . Writing a loop in this way is quicker and simpler than using a form of while because it keeps all the elements of the loop in one place instead of leaving them spread about the program. Eventually it will reach 11. Repeat from step 2. 3. if you put i back to 0 within the loop it will run forever. The test is a condition which must be true for the for -. i = i + 1 ) { Console. This useless program prints out hello mum 10 times. at which point the loop terminates and our program stops. i < 11 . 5. It does this by using a variable to control the loop. or update it. Test to see if we have finished the loop yet and exit to the statement after the for loop if we have. Perform the statements to be repeated. update ) { things we want to do a given number of times } We could use this to re-write the above program as: using System. This means that you are less likely forget to do something like give the control variable an initial value. 2.e. The variable is given an initial value (1) and then tested each time we go around the loop. Note that the three elements are separated by semicolons.Simple Data Processing Writing a Program using System.WriteLine ( "Hello mum" ) . while ( i < 11 ) { Console. i. Put the setup value into the control variable. The precise sequence of events is as follows: 1. The control variable is then increased for each pass through the statements.WriteLine ( "Hello mum" ) . C# Programming © Rob Miles 2010 45 . . This is a standard programming trick that you will find very useful. For this reason the goto is condemned as a potentially dangerous and confusing device. In every case the program continues running at the statement after the last statement of the loop. bit we get to if aborted becomes true . more complex stuff . There is rarely need for such convoluted code. Note that we are using two variables as switches.. but can still lead to problems.. This happens when you have gone as far down the statements as you need to. This means that if my program is at the statement immediately following the loop. normally false becomes true when the loop has to be abandoned and the variable runningOK. increment and test.. You can do this with the break statement. The goto is a special one that lets execution jump from one part of the program to another. if (aborted) { break . C# provides the continue keyword which says something along the lines of: C# Programming © Rob Miles 2010 46 .Simple Data Processing Writing a Program Programmer’s Point: Don't be clever/stupid Some people like to show how clever they are by doing cunning things with the setup. Going back to the top of a loop Every now and then you will want to go back to the top of a loop and do it all again... they are actually used to represent states within the program as it runs. which can do things other than simple assignment. Your program would usually make some form of decision to quit in this way.. Programmer’s Point: Be careful with your breaks The break keyword smells a little like the dread goto statement. for example in the following program snippet the variable aborted. condition and update statements.. they do not hold values as such. Some programmers think they are very clever if they can do all the work "inside" the for part at the top and have an empty statement after it. The break construction is less confusing than the goto. there are a number of ways it could have got there. one for every break in the loop above. becomes false when it is time to finish normally. your program may decide that there is no need or point to go on and wishes to leap out of the loop and continue the program from the statement after it.. Breaking Out of Loops Sometimes you may want to escape from a loop whilst you are in the middle of it. In this respect we advise you to exercise caution when using it. normally true. This is a command to leave the loop immediately. I find it most useful so that I can provide a "get the heck out of here" option in the middle of something. i.. When you are writing programs the two things which you should be worrying about are "How do I prove this works?" and "How easy is this code to understand?" Complicated code does not help you do either of these things. } . I call these people "the stupid people". } ... while (runningOK) { complex stuff .. The break statement lets you jump from any point in a loop to the statement just outside the loop.. You can break out of any of the three kinds of loop.e.. This can make the code harder to understand. which programmers are often scared of. e... for ( item = 1 . To do this we have to combine two tests to see if the value is OK. Programmer’s Point: Get used to flipping conditions One of the things that you will have to come to terms with is the way that you often have to reverse the way you look at things. if you get a value which is larger than the maximum or smaller than the minimum ask for another.. do all the updating and stuff and go around if you are supposed to. if (Done_All_We_Need_This_Time) continue . C# Programming © Rob Miles 2010 47 .. item processing stuff . } The continue causes the program to re-run the loop with the next value of item if it is OK to do so. i.Simple Data Processing Writing a Program Please do not go any further down this time round the loop. item < Total_Items . Essentially we want to keep asking the user for a value until we get one which is OK. In the following program the bool variable Done_All_We_Need_This_Time is set true when we have gone as far down the loop as we need to.. .. Complete Glazing Program This is a complete solution to the problem that uses all the tricks discussed above.. Rather than saying "Read me a valid number" you will have to say "Read numbers while they are not valid". Go back to the top of the loop. You can regard it as a move to step 2 in the list above.. Our loop should continue to run if: width > MAX_WIDTH or width < MIN_WIDTH To perform this test we use one of the logical operators described above to write a condition which will be true if the width is invalid: if ( width < MIN_WIDTH || width > MAX_WIDTH ) .... Remember the notes about reversing conditions above when you write the code. additional item processing stuff ... This means that you will often be checking to find the thing that you don't want. item=item+1 ) { . rather than the thing that you do. More Complicated Decisions We can now think about using a loop to test for a valid width or height.. The ++ is called a unary operator.0 .Parse(widthString).0 . C# allows us to be terser if we wish. However.Write ( "Give the height of the window between " + MIN_HEIGHT + " and " + MAX_HEIGHT + " :" ). do { Console. both in terms of what we have to type and what the computer will actually do when it runs the program. height = double.Write ( "Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :" ). } while ( width < MIN_WIDTH || width > MAX_WIDTH ) . It causes the value in that operand to be increased by one. The purpose of the above statement is to add 1 to the variable window_count. woodLength = 2 * ( width + height ) * 3.g.would do the same thing. window_count = window_count + 1 In this case the operator is + and is operating on the variable window_count and the value 1. class GlazerCalc { static void Main() { double width.WriteLine( "The area of the glass is " + glassArea + " square metres" ) .75 .5 . You can see examples of this construction in the for loop definition in the example above. glassArea = 2 * ( width * height ) .WriteLine ( "The length of the wood is " + woodLength + " feet" ) . Console. const double MAX_WIDTH = 5.ReadLine(). woodLength. heightString. do { Console. e.3. Console. string widthString.Parse(heightString). heightString = Console. width = double. const double MIN_WIDTH = 0. because it works on just one operand. the line: window_count++ .operator which can be used to decrease (decrement) variables. } while ( height < MIN_HEIGHT || height > MAX_HEIGHT ).ReadLine().Simple Data Processing Writing a Program using System. widthString = Console.25 . glassArea. it is a rather long winded way of expressing this. const double MAX_HEIGHT = 3. There is a corresponding -.4 Operator Shorthand So far we have looked at operators which appear in expressions and work on two operands. C# Programming © Rob Miles 2010 48 . height. const double MIN_HEIGHT = 0. } } 2. We can express ourselves more succinctly and the compiler can generate more efficient code because it now knows that what we are doing is adding one to a particular variable. In order to show how this is done. You determine whether you want to see the value before or after the sum by the position of the ++ : i++ ++i Means “Give me the value before the increment” Means “Give me the value after the increment” As an example: int i = 2. C# provides a way of getting either value. The fact that you can produce code like: height = width = speed = count = size = 0 . j = ++i . all return the value after the operator has been performed. Programmer’s Point: Always strive for simplicity Don't get carried away with this. Nowadays when I am writing a program my first consideration is whether or not the program is easy to understand. This is perfectly legal (and perhaps even sensible) C#. I don't think that the statement above is very easy to follow – irrespective of how so much more efficient it is. I still don't do it. If you do this you are advised to put brackets around the statement which is being used as a value. particularly when we get around to deciding things (see later).would make j equal to 3. in that you do not know if you get the value before or after the increment. C# has some additional operators which allow us to shorten this to: house_cost += window_cost. Most of the time you will ignore this value. I will leave you to find them! Statements and Values One of the really funky things about C# is that all statements return a value. An assignment statement always returns the value which is being assigned (i. but sometimes it can be very useful. which you can use in another statement if you like. the bit on the right of the gozzinta). so that the value in house_cost is increased by window_cost. j . consider the following: i = (j=0). but again is rather long winded. C# Programming © Rob Miles 2010 49 .Simple Data Processing Writing a Program The other shorthand which we use is when we add a particular value to a variable. which is OK. It has the effect of setting both i and j to 0. this makes the whole thing much clearer for both you and the compiler! When you consider operators like ++ there is possible ambiguity. depending on which effect you want. . .e. The += operator combines addition and the assignment. We could put: house_cost = house_cost + window_cost. The other special operators.does not mean that you should. This is perfectly OK. += etc.. This value can then be used as a value or operand. Console. This would print out: i: 150 f: 1234. Note that doing this means that if the number is an integer it is printed out as 12. the WriteLine method will fail with an error. f ) . double f = 1234. double f = 1234. Specifying the number of printed digits I can specify a particular number of digits by putting in a given number of zeroes: int i = 150 . f.5 Neater Printing Note that the way that a number is printed does not affect how it is stored in the program.WriteLine ( "i: {0:0000} f: {1:00000. This would print out: i: 0150 f: 01234. Adjusting real number precision Placeholders can have formatting information added to them: int i = 150 . i. If you have run any of the above programs you will by now have discovered that the way in which numbers are printed leaves much to be desired. Console.56789 i: 150 f: 1234.3.WriteLine ( "i: {0:#.##0. f ). Of course if I do something mad. This would print out: i: 150 f: 1234.00}".##0} f: {1:##. i. and is also somewhat easier to use if you are printing a large number of values.Simple Data Processing Writing a Program 2.57 The 0 characters stand for one or more digits.56789 The {n} part of the string says ―parameter number n. for example {99}. Console. When placed after a decimal point they can be used to control the number of decimal places which are used to express a value.56789 . i. counting from 0‖. f ). This provides more flexibility. Integers seem to come out OK.57 Note that if I do this I get leading zeroes printed out.WriteLine ( "i: {1} f: {0}". f ) .00.WriteLine ( "i: {0:0} f: {1:0. which is useful if you are printing things like cheques.56789 . I have used the # character to get my thousands printed out with commas: C# Programming © Rob Miles 2010 50 .56789 .00}". but floating point numbers seem to have a mind of their own.00}". Console. double f = 1234. it just tells the printing method how it is supposed to be printed. Using Placeholders in Print Strings A placeholder just marks the place where the value is to be printed. Console. To get around this C# provides a slightly different way in which numbers can be printed. i. double f = 1234. In the second write statement I have swapped the order of the numbers. but since I've swapped the order of the parameters too the output is the same.56789 .WriteLine ( "i: {0} f: {1}". i ) . Really Fancy Formatting If you want really fancy levels of control you can use the # character. Consider: int i = 150 . A # in the format string means ―put a digit here if you have one‖: int i = 150 . even a piece of text. if I want the numbers left justified I make the width negative: int i = 150 .00}".-15:0. f ) . i.00 The integer value is printed in a column 10 characters wide.56789 . Printing in columns Finally I can add a width value to the print layout information.15:0.00}". Note also though that I have included a 0 as the smallest digit.10:0} f: {1.234. double f = 1234.-15:0.WriteLine ( "i: {0. 0.10:0} f: {1.56789 .-10:0} f: {1.Simple Data Processing Writing a Program i: 150 f: 1. The value 150 does not have a thousands digit so it and the comma are left out.WriteLine ( "i: {0.WriteLine ( "i: {0.00 Note that this justification would work even if you were printing a string rather than a number. Console. 0 ) .00}". i.00}". C# Programming © Rob Miles 2010 51 . This is so that when I print the value 0 I actually get a value printed. otherwise when I print zero I get nothing on the page.-10:0} f: {1. which makes printing in columns very easy. so if you want to print columns of words you can use this technique to do it. Console. You can specify the print width of any item. 0. f ) .15:0. Console.57 0. This is very useful if you want to print material in columns: int i = 150 . 0 ) . double f = 1234.57 f: 0.WriteLine ( "i: {0. This would produce the output: i: i: 150 f: 0 f: 1234.57 Note that the formatter only uses the # characters and commas that it needs. Console. This would produce the output: i: 150 i: 0 f: 1234. and the double is printed in a 15 character wide column. At the moment the output is right justified. Essentially you take a block of code and give it a name. WriteLine and ReadLine. As a silly example: C# Programming © Rob Miles 2010 52 . Again. Main is the method we write which is where our program starts. as with lots of features of the C# language. In this section we are going to consider why methods are useful and how you can create your own. C# lets us create other methods which are used when our program runs. 3. but they do help with the organisation of our programs. We have exactly the same piece of code to check widths and heights. We will need both of these when we start to write larger programs. Methods give us two new weapons: We can use methods to let us re-use a piece of code which we have written. To do this you need to define a method to do the work for you. Method and Laziness We have already established that a good programmer is creatively lazy. However. 3. If we added a third thing to read. Then you can refer to this block of code to do something for you. We can also use methods to break down a large task into a number of smaller ones. Your programs will contain methods that you create to solve parts of the problem and they will also use methods that have been provided by other people. methods don't actually make things possible. One of the tenets of this is that a programmer will try to do a given job once and once only. we would have to copy the code a third time. WriteLine and ReadLine were provided by the creators of C# to give us a way of displaying text and reading information from the user. This is not very efficient. Up until now all our programs have been in a single method. for example frame thickness. What we would like to do is write the checking code once and then use it at each point in the program. The method is the block of code which follows the main part in our program. This is what methods are all about. it makes the program bigger and harder to write.1.1 Methods We have already come across the methods Main. When the method starts the value supplied for the parameter is copied into it. } } The method silly has a single integer parameter.WriteLine ( "i is : " + i ) . we can use methods to save us from writing the same code twice. 3.2 Parameters At this point methods are useful because they let us use the same block of statements at many points in the program. The method is given the data to work on. As an example. } public static void Main () { silly ( 101 ) . This means that when the program runs we get output like this: i is : 101 i is : 500 3. } } In the main method I make two calls of doit. silly ( 500 ) . The result of running the above program would be: Hello Hello So. You have already used this feature. the methods ReadLine and Parse both return results that we have used in our programs: C# Programming © Rob Miles 2010 53 . they become more useful if we allow them to have parameters. In this case it contains a single statement which prints "Hello" on the console. class MethodDemo { static void silly ( int i) { Console. Within the block of code which is the body of this method we can use the parameter i as an integer variable. doit(). consider the code below: using System .1. Each time I call the method the code in the block which is the body of the method is executed.1. class MethodDemo { static void doit () { Console. However.3 Return values A method can also return a value to the caller.Creating Programs Methods using System .WriteLine ("Hello"). We simply put the code inside a method body and then call it when we need it. } public static void Main () { doit(). A parameter is a means of passing a value into a method call. double age = readValue ( "Enter your age: ". return i.Creating Programs Methods using System . // prompt for the user double low. but this is actually a rather pointless thing to do: sillyReturnPlus (5).ReadLine (). return result .4 A Useful Method Now we can start to write genuinely useful methods: static double readValue ( string prompt. } while ( (result < low) || (result > high) ). Console.WriteLine (prompt + " between " + low + " and " + high ). // will compile but do nothing useful 3.WriteLine ( "res is : " + res ) . We can use this method to read anything and make sure that value supplied is within a particular range. // lowest allowed value double high // highest allowed value ) { double result = 0.1. MIN_WIDTH. string resultString = Console. Console. result = double.WriteLine ( "i is : " + i ) . do { Console. It is actually OK to ignore the value returned by a method. in other words a call of sillyReturnPlus can take the place of an integer. } } The method sillyReturnPlus takes the value of the parameter and returns it plus one. class ReturnDemo { static int sillyReturnPlus ( int i) { i = i + 1. The value that a method returns can be used anywhere in a program where a variable of that type could be used. It can then be used to read values and make sure that they are in range. The second reads an age between 0 and 70.Parse(resultString). The first call of readValue gets the width of a window. 0.WriteLine ( "res is : " + res ) . MAX_WIDTH) . } The readValue method is told the prompt to use and the lowest and the highest allowed values. double windowWidth = readValue ( "Enter width of window: ". C# Programming © Rob Miles 2010 54 . res = sillyReturnPlus (5). See if you can work out what this code would display: res = sillyReturnPlus (5) + sillyReturnPlus (7) + 1. Console. 70) . } public static void Main () { int res. WriteLine ( "i is : " + i ) . Method Limitations A method is very good for getting work done. Consider: static void addOneToParam ( int i) { i = i + 1. This means that you can write calls like: test = 20 . Console. However. From what we have seen of methods. prints the result out and then returns: int test = 20 .WriteLine ( "test is : " + test ) . Moving code around and creating methods is called refactoring. but it can be a bit limited because of the way that it works. Console. C# Programming © Rob Miles 2010 55 .Creating Programs Methods Programmer’s Point: Design with methods Methods are a very useful part of the programmer's toolkit. Once you have worked out what the customer wants and gathered your metadata you can start thinking about how you are going to break the program down into methods. There are two reasons why this is a good idea: 1: 2: It saves you writing the same code twice. 3. If you do this you should consider taking that action and moving it into a method. It then passes this value into the call. The value of test is being used in the call of addOneToParam.1. This would print out: i is : 120 Pass by value is very safe. only the value of a parameter is passed into a call to a method. Often you find that as you write the code you are repeating a particular action. because nothing the method does can affect variables in the code which calls it. addOneToParam(test + 99). or write one which returns an age. If a fault is found in the code you only have to fix it in one place. This will be an important part of the Software Engineering we do later. The program works out the result of the expression to be passed into the method call as a parameter. addOneToParam(test). it is a limitation when we want to create a method which returns more than one value. The piece of C# above calls the method with the variable test as the parameter. For example. This is because. what do I mean by "passing parameters by value". unless you specify otherwise. As you will find out when you try. they can only return one value.5 Parameter Passing By Value So. When it runs it prints out the following: i is : 21 test is : 20 It is very important that you understand what is happening here. changing the value of a parameter does not change the value of the thing passed in. So I could write a method which returns the name of a person. if I want to write a method which reads in the name and the age of a person I have a problem. } The method addOneToParam adds one to the parameter. But I can’t write a method that returns both values at the same time as a method can only return one value. They form an important part of the development process. rather than passing in "20" in our above call the compiler will generate code which passes in "memory location 5023" instead (assuming that the variable test is actually stored at 5023). This memory location is used by the method. test = 20 .6 Parameter Passing By Reference It is very important that you understand how references work. Generally speaking you have to be careful with side effects. Programmer’s Point: Document your side-effects A change by a method to something around it is called a side effect of the method. Note that C# is careful about when a parameter is a reference. changes to the parameter change the variable whose reference you passed” If you find references confusing you are not alone. In this case the output is as follows: i is : 21 test is : 21 In this case the method call has made changes to the content of the variable. 3. The program will say ―Get the value from location 5023‖ rather than ―The value is 1‖. } Note that the keyword ref has been added to the information about the parameter. So. You have to put the word ref in the method heading and also in the call of the method. it is going to have the “side effect” of changing something outside the method itself (namely the value of the parameter passed by reference).1. This is the case when we want to read in the name and age of a user. we use them in real life all the time with no problems.WriteLine ( "i is : " + i ) . If you say ―Deliver the carpet to 23 High Street. Instead you want to just allow the method to change the variable. Console. Instead it just wants to deliver results to them. The code above makes a call to the new method. rather than the content of the variable. Using a reference in a program is just the same. Sometimes you don't want this. In other words: “If you pass by reference. However.WriteLine ( "test is : " + test ) . Inside the method. when someone calls our addOneToRefParam method. In this case I can replace the ref with the keyword out: C# Programming © Rob Miles 2010 56 . rather than using the value of the variable the reference is used to get the actual variable itself. addOneToRefParam(ref test). If you don't understand these you can't call yourself a proper programmer! Fortunately C# provides a way that. instead a reference to that variable is supplied instead.7 Passing Parameters as "out" references When you pass a parameter as a reference you are giving the method complete control of it. and also has the word ref in front of the parameter. The original value of the parameters is of no interest to the method.Creating Programs Methods 3. instead of the value. Effectively the thing that is passed into the method is the position or address of the variable in memory. Console. as someone reading your program has to know that your method has made changes in this way.‖ you are giving the delivery man a reference. Consider the code: static void addOneToRefParam ( ref int i) { i = i + 1.1. rather than sending the value of a variable into a method. In other words. age = readInt ( "Enter your age : ". It means that if I mark the parameters as out I must have given them a value for the program to compile. } static int readInt ( string prompt. do { string intString = readString (prompt) . Note that I must use the out keyword in the call of the method as well.ReadLine (). so that the user can't enter an empty string when a number is required. readPerson ( out name. In the code above I have written a couple of library methods which I can use to read values of different types: static string readString ( string prompt ) { string result . 3.8 Method Libraries The first thing that a good programmer will do when they start writing code is to create a set of libraries which can be used to make their job easier. Note how I have rather cleverly used my readString method in my readInt one. It makes sure that a programmer can't use the value of the parameter in the method. This is very useful.1. out age ) . The readInt method reads a number within a particular range. It also allows the compiler to make sure that somewhere in the method the output parameters are assigned values. 100 ) . out int age ) { name = readString ( "Enter your name : " ) . readString and readInt. I can call readPerson as follows: string name .Creating Programs Methods static void readPerson ( out string name. do { Console. Note that it uses two more methods that I have created. return result. as I am protected against forgetting to do that part of the job. } while ( result == "" ) . } The method readPerson reads the name and the age of a person. The readPerson method will read the person and deliver the information into the two variables.Write ( prompt ) . int high ) { int result . return result . This makes it harder for me to get the program wrong. result = int. result = Console. } while ( ( result < low ) || ( result > high ) ). int low. int age . 0. } The readString method will read text and make sure that the user does not enter empty text. We can use the methods as follows: C# Programming © Rob Miles 2010 57 .Parse(intString). Programmer’s Point: Languages can help programmers The out keyword is a nice example of how the design of a programming language can make programs safer and easier to write. Creating Programs Variables and Scope string name. The scope of a local variable is the block within which the variable is declared. Any block can contain any number of local variables. If the return value is 0 this means that the method returned correctly.2 Nested Blocks We have seen that in C# the programmer can create blocks inside blocks. This means that only statements in the inner block can use this variable. 100). When the execution of the program moves outside a block any local variables which are declared in the block are automatically discarded. 0. The methods that we have created have often contained local variables.2. This adds another dimension to program design. the variable result in the readInt method is local to the method block. but you must declare it before you use it. You need to consider whether or not the method should deal with the problem itself or pass the error onto the system which tried to use it.2. i. The C# compiler also looks after the part of a program within which a variable has an existence. In fact one thing I tend to do when working on a project is create little library of useful methods like these which I can use.1 Scope and blocks We have already seen that a block is a number of statements which are enclosed in curly brackets. age = readInt ( "Enter your age : ". 3. In other words the code: C# Programming © Rob Miles 2010 58 . name = readString( "Enter your name : " ). If the method involves talking to the user it is possible that the user may wish to abandon the method. or that the user does something that may cause it to fail. Each of these nested blocks can have its own set of local variables: { int i . If the method passes the error on to the code which called it you have to have a method by which an error condition can be delivered to the caller. int age. } } The variable j has the scope of the inner block.2 Variables and Scope We have seen that when we want to store a quantity in our program we can create a variable to hold this information. 3. As far as the C# language is concerned you can declare a variable at any point in the block. I could add methods to read floating point values as well. variables which are local to that block. If the method deals with the error itself this may lead to problems because the user may have no way of cancelling a command. I often solve this problem by having my methods return a code value.e. as well as making sure that it does the required job! We are going to discuss error management later 3. in that you also have to consider how the code that you write can fail. If the return value is non-zero this means that the method did not work and the value being returned is an error which identifies what went wrong. Programmer’s Point: Always consider the failure behaviours Whenever you write a method you should give some thought to the ways that it could fail. { int j . This is called the scope of a variable. The C# compiler makes sure that the correctly sized chunk of memory is used to hold the value and it also makes sure that we only ever use that value correctly. { int j . C# has an additional rule about the variables in the inner blocks: { int i . Variables Local to a Method Consider the following code: C# Programming © Rob Miles 2010 59 . } The variable i is declared and initialized at the start of the for loop and only exists for the duration of the block itself.3 Data Member in classes Local variables are all very well. In order to remove this possibility the compiler refuses to allow this.WriteLine ( "Hello" ) . { int i . { int j . This allows you to declare a control variable which exists for the duration of the loop itself: for ( int i = 0 . } . for example C++. For loop local variables A special kind of variable can be used when you create a for loop construction. It is however perfectly acceptable to reuse a variable name in successive blocks because in this situation there is no way that one variable can be confused with another. This is because inside the inner block there is the possibility that you may use the "inner" version of i when you intend to use the outer one. { int i . where this behaviour is allowed. } j = 99 . In order to keep you from confusing yourself by creating two versions of a variable with the same name. i = i + 1 ) { Console. i < 10 . as the variable j does not exist at this point in the program. } { int i .2.Creating Programs Variables and Scope { int i . but they disappear when the program execution leaves the block where they are declared. so this code is OK.would cause an error. } } This is not a valid program because C# does not let a variable in an inner block have the same name as one in an outer block. } } The first incarnation of i has been destroyed before the second. 3. We often need to have variables that exist outside the methods in a class. Note that this is in contrast to the situation in other languages. For now you just have to remember to put in the static keyword. } } The variable member is now part of the class MemberExample. if you were creating a program to play chess it would be sensible to make the variable that stores the board into a member of the class. For example. Console. otherwise your program will not compile. If a statement in OtherMethod tries to use local the program will fail to compile.WriteLine ("local is :" + local). } } The variable local is declared and used within the Main method.WriteLine ("member is now : " + member). display the board. and can’t be used anywhere else.WriteLine ("member is : " + member). This means declaring it outside the methods in the class: class MemberExample { // the variable member is part of the class static int member = 0 . } static void Main () { Console. Then the methods that read the player move. we will investigate the precise meaning of static later on.Creating Programs Variables and Scope class LocalExample { static void OtherMethod () { local = 99. static void OtherMethod () { member = 99. This is not something to worry about just now. Console. and so the Main method and OtherMethod can both use this variable. Static class members Note that I have made the data member of the class static. and calculate the computer move could all use the same board information. // this will not compile } static void Main () { int local = 0. OtherMethod(). Class variables are very useful if you want to have a number of methods ―sharing‖ a set of data. Variables which are Data Members of a Class If I want to allow two methods in a class to share a variable I will have to make the variable a member of the class. so that it is part of the class and not an instance of the class. The program above would print out: member is : 0 member is now : 99 This is because the call of OtherMethod would change the value of member to 99 when it runs. C# Programming © Rob Miles 2010 60 . C# Programming © Rob Miles 2010 61 . You decide how much money you are going to be paid.1000). ". You discuss sensible ranges (no player can score less than 0 or more than 1000 runs in a game). ". and what information it will print out. 0.1000). It turns out that you now know about nearly all the language features that are required to implement every program that has ever been written. like the background static noise on your radio when you tune it off station.1000).1 Why We Need Arrays Your fame as a programmer is now beginning to spread far and wide.3. ". Programmer’s Point: Plan your variable use You should plan your use of variables in your programs. ". given a set of player scores from a game he wants a list of those scores in ascending order. The next person to come and see you is the chap in charge of the local cricket team. If it helps you can think of static as something which is always with us. Our programs can also make decisions based on the values supplied by the user and also repeat actions a given number of times. You should decide which variables are only required for use in local blocks and which should be members of the class. to make this the perfect project. 0. ".1000). ". you agree on when the software must be finished and how you are going to demonstrate it to your new customer and you write all this down and get it signed. 0. 0. 0. 3. Finally.Creating Programs Arrays One common programming mistake is to confuse static with const. With all this sorted. 0. He would like to you write a program for him to help him analyse the performance of his players. score11 . The next thing you do is refine the specification and add some metadata.1000). and therefore not going anywhere. score6. score5. Only one thing is missing. ". Alternatively you can think of it as stationary. : ". What the customer wants is quite simple. score10.1000). all you have to do now is write the actual program itself. I am very careful to keep the number of member variables in a class to the minimum possible and use local variables if I only need to store the value for a small part of the code. ―This is easy‖ you think.1000). 0. Marking a variable with static means ―the variable is part of the class and is always present‖. ". calculate results and print them.1000). You draw out a rough version of what the program will accept. 0. ".3 Arrays We now know how to create programs that can read values in. score3. 0. 0. score7 score8.1000). Marking a variable as const means ―the value cannot be changed‖. : ". Arrays are one way to do this. When a game of cricket is played each member of the team will score a particular number of runs.1000). Now you can start putting the data into each variable. 3. and that is the ability to create programs which store large amounts of data. score9. The first thing to do is define how the data is to be stored: int score1. 0. score4. and we are going to find out about them next. and when. Bear in mind that if you make a variable a member of the class it can be used by any method in that class (which increases the chances of something bad happening to it). score2.1000). each large enough to hold a single integer. It then gets a piece of rope and ties the tag scores to this box. If you follow the rope from the scores tag you reach the array box.1000). Visual Basic numbers array elements starting at 1. This part is called the subscript. You can think of this as a tag which can be made to refer to a given array. Hmmmm. class ArrayDemo { public static void Main () { int [] scores = new int [11] .3. When an array is created all the elements in the array are set to 0. Consider the following: using System. This is very important. The bit which makes the array itself is the new int [11]. In the program you identify which element you mean by putting its number in square brackets [ ] after the array name.. i=i+1) { scores [i] = readInt ( "Score : ". i<11. we know that computers are very good at sorting this kind of thing. It then gets some pieces of wood and makes a long thin box with 11 compartments in it. If you find this confusing. 0. } } } The int [] scores part tells the compiler that we want to create an array variable. it probably doesn't use wood or rope. (as long as you don't fall off the end of the array). If you look at the part of the program which reads the values into the array you will see that we only count from 0 to 10.Creating Programs Arrays All we have to do next is sort them. C# provides us with a thing called an array. One thing adding to this confusion is the fact that this numbering scheme is not the same in other languages. Just deciding whether score1 is the largest value would take an if construction with 10 comparisons! Clearly there has to be a better way of doing this. It then paints the whole box red . An array allows us to declare a whole row of a particular kind of box. scores [i+1] . C# Programming © Rob Miles 2010 62 .2 Array Elements Each compartment in the box is called an element. after all. When C# sees this it says ―Aha! What we need here is an array‖. 3. Actually. This means that you specify the element at the start of the array by giving the subscript 0. In fact you can use any expression which returns an integer result as a subscript. ―The first element has the subscript 0‖ then the best way to regard the subscript is as the distance down the array you have to travel to get to the element that you need. but you should get a picture of what is going on here.because boxes which can hold integers are red. Array Element Numbering C# numbers the boxes starting at 0. This is awful! There seems to be no way of doing it. I’m sorry about this... Note that the thing which makes arrays so wonderful is the fact that you can specify an element by using a variable.. for ( int i=0. i..is quite OK. An attempt to go outside the array bounds of scores cause your program to fail as it runs. We can then use things called subscripts to indicate which box in the row that we want to use.... There is consequently no element scores [11].e. it just goes to show that not everything about programming is consistent. 2010 2010 2010 65 and the program will use the catch which matches the level of the code in the try block. Note that once the exception has been thrown there is no return to the code in the try block. which is managing the execution of your program inside the computer. try { age = int.Message).4. 3.4 Exception Nesting When an exception is thrown the run time system.WriteLine("Thank you"). Console. The code in this catch clause will display the exception details and then stop the program. which contains the message: Input string was not in a correct format. An exception is a type of object that contains details of a problem that has occurred. The Exception type has a property called Message which contains a string describing the error.WriteLine("Invalid age value"). If the call of Parse throws an exception the code in the catch block runs and will display a message to the user.Parse(ageString). try { age = int. The Exception object also contains other properties that can be useful. Console. i. the parse action takes place inside the try block. since it means that the message reflects what has actually happened. If your program does not contain a catch for the exception it will be caught by a catch which is part of the run time system.Creating Programs Exceptions and Errors int age.Parse(ageString). This is useful if the code inside the try block could throw several different kinds of exception. This is exactly how it works. } The catch now looks like a method call. The program above ignores the exception object and just registers to the exception event but we can improve the diagnostics of our program by catching the exception if we wish: int age.e. Programs can have multiple levels of try – catch.4. with the Exception e being a parameter to the method. } catch (Exception e) { // Get the error message out of the exception Console. However.WriteLine("Thank you"). When Parse fails it creates an exception object that describes the bad thing that has just happened (in this case input string not in the correct format). This message is obtained from the exception that was thrown. 3.WriteLine(e. Within the catch clause the value of e is set to the exception that was thrown by Parse. C# Programming © Rob Miles 2010 66 . } The code above uses Parse to decode the age string. Exceptions work in the same way. } catch { Console. if the parse fails the program will not display the message "Thank you". If a user types in an invalid string the program above will write the text in the exception.3 The Exception Object When I pass a problem up to my boss I will hand over a note that describes it. will look for the enclosing catch clause. once execution leaves that inner block the outer catch is the one which will be run in the event of an exception being thrown. 3. The faster you can get a fault to manifest itself the easier it is to identify the cause. and the program never returns to the try part of the program. The code in the catch clause could return from the method it is running within or even throw an exception itself. not try and handle things by returning a null reference or empty item. Programmer’s Point: Don’t Catch Everything Ben calls this Pokemon® syndrome: “Gotta catch’em all”. Statements inside the finally clause will run irrespective of whether or not the program in the try block throws an exception. Don’t feel obliged to catch every exception that your code might throw. Returning a placeholder will just cause bigger problems later when something tries to use the empty item that was returned. However. Fortunately C# provides a solution to this problem by allowing you to add a finally clause to your try-catch construction. releasing resources and generally tidying up. In these situations any code following your try – catch construction would not get the chance to run. we know that when an exception is thrown the statements in the catch clause are called. These actions include things like closing files. If someone asks your Load method to fetch a file that doesn’t exist the best thing it can do is throw a “file not found” exception. However.5 Adding a Finally Clause Sometimes there are things that your program must do irrespective of whether or not as exception is thrown. If code in the innermost block throws an exception the run time system will find the inner catch clause. try { // Code that } catch (Exception { // Code that } finally { // Code that // is thrown } might throw an exception outer) catches the exception is obeyed whether an exception or not C# Programming © Rob Miles 2010 67 .4. 3.6 Throwing an Exception Now that we know how to catch exceptions. 3. Throwing an exception might cause your program to end if the code does not run inside a try – catch construction.7 Exception Etiquette Exceptions are best reserved for situations when your program really cannot go any further.Creating Programs The Switch Construction In the above code the statements in the finally part are guaranteed to run.1 Making Multiple Decisions Suppose you are refining your double glazing program to allow your customer to select from a pre-defined range of windows. the next thing we need to consider is how to throw them. When you make a new exception you can give it a string that contains the message the exception will deliver. Programmer’s Point: Plan your Exception Handling When you design a program you should consider what events count as “showstoppers” and how you are going to deal with them. but there is really very little left to know about programming itself.5. either when the statements in the try part have finished.4. 3. For example if a user of the double glazing program enters a window height which is too large the program can simply print the message ―Height too large‖ and ask for another value. This means that errors at this level are not worthy of exception throwing. The statement above makes a new exception and then throws it. or just before execution leaves the catch part of your program. I reserve my exceptions for catastrophic events that my program really cannot deal with and must pass on to something else. When you come to write the program you will probably end up with something like: C# Programming © Rob Miles 2010 68 .4.. and you should too.5 The Switch Construction We now know nearly everything you need to know about constructing a program in the C# language. Each method asks the relevant questions and works out the price of that kind of item. 3. This turns out to be very easy: throw new Exception("Boom"). Most of the rest of C is concerned with making the business of programming simpler. You can even create your own custom exception types based on the one provided by the System use these in your error handling. A good example of this is the switch construction. You may find it rather surprising. If you are going to throw an exception this should be in a situation where your program really could not do anything else. 2 Selecting using the if construction When you come to perform the actual selection you end up with code which looks a bit like this: int selection . Our program can use this method to get the selection value and then pick the method that needs to be used. This is called the switch construction. if ( selection == 1 ) { handleCasement(). but is rather clumsy. } static void handleStandard () { Console.5. We already have a method that we can use to get a number from the user (it is called readInt and is given a prompt string and high and low limits).5. } static void handlePatio () { Console.WriteLine("Handle Casement"). 1. 3. If you write the above using it your program would look like this. } else { if ( selection == 2 ) { handleStandard(). } else { if ( selection == 3 ) { handlePatio() .WriteLine("Handle Standard").3 The switch construction Because you have to do this a lot C# contains a special construction to allow you to select one option from a number of them based on a particular value. At the moment they just print out that they have been called. } } } This would work OK. 3. the next thing you need to do is write the code that will call the one that the user has selected.WriteLine("Handle patio").Creating Programs The Switch Construction static void handleCasement () { Console. } else { Console. C# Programming © Rob Miles 2010 69 . Once you have the methods in place. You have to write a large number of if constructions to activate each option. 3 ) . } These methods are the ones which will eventually deal with each type of window.WriteLine ( "Invalid number" ). Later you will go on and fill the code in (this is actually quite a good way to construct your programs). selection = readInt ( "Window Type : ". when the break is reached the switch is finished and the program continues running at the statement after the switch. your users would not thank you for doing this. The break statement after the call of the relevant method is to stop the program running on and performing the code which follows. break . break . You can use the switch construction with types other than numbers if you wish: switch (command) { case "casement" : handleCasement (). default : Console. This gives the switch somewhere to go if the switch value doesn't match any of the cases available.WriteLine ( "Invalid number" ) . case 3 : handlePatio () . the compiler will give you an error if you make a mistake. in our case (sorry!) we put out an appropriate message. break . case "patio" : handlePatio () . Multiple cases You can use multiple case items so that your program can execute a particular switch element if the command matches one of several options: C# Programming © Rob Miles 2010 70 . since it means that they have to type in the complete name of the option. break . } The switch construction takes a value which it uses to decide which option to perform. It executes the case which matches the value of the switch variable. Of course this means that the type of the cases that you use must match the switch selection value although. break . However. case 2 : handleStandard () . Another other useful feature is the default option. in true C# tradition. break . break . case "standard" : handleStandard () . break . default : Console. and of course if they type a character wrong the command is not recognised.WriteLine ( "Invalid command" ) .Creating Programs The Switch Construction switch (selection) { case 1 : handleCasement (). In the same way as you break out of a loop. } This switch uses a string to control the selection of the cases. However.6 Using Files If you want your program to be properly useful you have to give it a way of storing data when it is not running.WriteLine ( "Invalid command" ) . We can write a C# program which creates a file on a Windows PC and then use the same program to create a file on a UNIX system with no problems. Instead you should put a call to a method as I have above. case "standard" : case "s" : handleStandard () .ToUpper()) { case "CASEMENT" : case "C" : . which can make the testing of the commands much easier: switch (command. case "patio" : case "P" : handlePatio () . so that streams can be used to read and write to files... What we want to do is use C# to tell the operating system to create files and let us access them. 3. If you want to perform selection based on strings of text like this I’d advise you to take a look at the ToUpper and ToLower methods provided by the string type.6. Data can flow up or down your stream. The operating system actually does the work. } The above switch will select a particular option if the user types the full part of the name or just the initial letter. in files. break .. break . 3.Creating Programs Using Files switch (command) { case "casement" : case "c" : handleCasement (). Programmer’s Point: switches are a good idea Switches make a program easier to understand as well as quicker to write. It is also easier to add extra commands if you use a switch since it are just a matter of putting in another case. break . break . default : Console. We know that you can store data in this way. These can be used to obtain a version of a string which is all in upper or lower case. and the C# library you are using will convert your request to use streams into instructions for the operating system you are using at the time: C# Programming © Rob Miles 2010 71 . that is how we have kept all the programs we have created so far. The good news is that although different operating systems use different ways to look after their files. the way in which you manipulate files in C# is the same for any computer. The stream is the thing that links your program with the operating system of the computer you are using.1 Streams and Files C# makes use of a thing called a stream to allow programs to work with files. I'd advise against putting large amounts of program code into a switch case. Files are looked after by the operating system of the computer. A stream is a link between your program and a data resource. C# has a range of different stream types which you use depending on what you want to do. Each time you write a line to the file it is added onto the end of the lines that have already been written. which would be bad. It means that you could use the two statements above to completely destroy the contents of an existing file. The above statement calls the WriteLine method on the stream to make it write the text ―hello world‖ into the file test. writer. If your program got stuck writing in an infinite loop it is possible that it might fill up the storage device. All of the streams are used in exactly the same way. file is created in place of what was there. empty.6. The variable writer will be made to refer to the stream that you want to write into. these are the StreamWriter and StreamReader types. This is exactly the same technique that is used to write information to the console for the user to read. C# Programming © Rob Miles 2010 72 . then the action will fail with an appropriate exception. by using new. A properly written program should probably make sure that any exceptions like this (they can also be thrown when you open a file) are caught and handled correctly. Most useful programs ask the user whether or not an existing file should be overwritten. In fact you can use all the writing features including those we explored in the neater printing section to format your output. since the Console class.Creating Programs Using Files C# program stream File in Windows A C# program can contain an object representing a particular stream that a programmer has created and connected to a file.txt for output and connect the stream to it. This is potentially dangerous. If this happens. The program performs operations on the file by calling methods on the stream object to tell it what to do. is implemented as a stream. which connects a C# program to the user.WriteLine("hello world"). and the write cannot be performed successfully.3 Writing to a Stream Once the stream has been created it can be written to by calling the write methods it provides. you will find out later how to do this.txt. the call of WriteLine will throw an exception. StreamWriter writer . All that happens is that a brand new. Note however that this code does not have a problem if the file test. If this process fails for any reason.6. perhaps your operating system is not able/allowed to write to the file or the name is invalid.txt already exists. 3.txt"). In fact you are already familiar with how streams are used. 3. The ReadLine and WriteLine methods are commands you can give any stream that will ask it to read and write data. When the new StreamWriter is created the program will open a file called test. writer = new StreamWriter("test.2 Creating an Output Stream You create a stream object just like you would create any other one. We are going to consider two stream types which let programs use files. When the stream is created it can be passed the name of the file that is to be opened. If you were in charge of cataloguing a huge number of items you would find it very helpful to lump items into groups.5 Streams and Namespaces If you rush out and try the above bits of code you fill find that they don’t work. There is something else that you need to know before you can use the StreamWriter type. The using keyword allows us to tell the compiler where to look for resources. close the file or suffer the consequences. The designers of the C# language created a namespace facility where programmers can do the same kind of thing with their resources. So.Console. i.Console. Any further attempts to write to the stream will fail with an exception.Close().e. using System. when we reflected on the need to have the statement using System. but on top of this there are a whole lot of extra resources supplied with a C# installation. However. part of operating resource. This statement tells the compiler to look in the System namespace for resources. It will also be impossible to move or rename the file. Once a file has been closed it can then be accessed by other programs on the computer.6. That is.4 Closing a Stream When your program has finished writing to a stream it is very important that the stream is explicitly closed using the Close method: writer. An open stream consumes a small.IO namespace. A C# installation actually contains many thousands of resources. We have touched on namespaces before. a ―space where names have meaning‖. In this situation some of the data that you wrote into the file will not be there. the Console class in the System namespace. this object is defined in the System. Once we have specified a namespace in a program file we no longer need to use the fully qualified name for resources from that namespace. Museum curators do this all the time. Like lots of the objects that deal with input and output. The full name of the Console class that you have been using to write text to the user is System. each of which must be uniquely identified. A namespace is. 3. If your program has a stream connected to a file other programs may not be able to use that file. The C# language provides the keywords and constructions that allow us to write programs. Whenever the compiler finds an C# Programming © Rob Miles 2010 73 . but significant. Namespaces are all to do with finding resources. Forgetting to close a file is bad for a number of reasons: It is possible that the program may finish without the file being properly closed. at the start of our C# programs.txt and take a look at what is inside it. and the Greek ones in another.Creating Programs Using Files 3.6. When the Close method is called the stream will write out any text to the file that is waiting to be written and disconnect the program from the file. Sorry about that. These resources are things like the Console object that lets us read and write text to the user. Now we need to find out more about them.WriteLine("Hello World"). In fact it is quite OK to use this full form in your programs: System. If your program creates lots of streams but does not close them this might lead to problems opening other files later on. The above uses the fully qualified name of the console resource and calls the method WriteLine provided by that resource. once the close has been performed you can use the Notepad program to open test. quite literally. They put all the Roman artefacts in one room. we’ve not had to use this form because at the start of our programs we have told the compiler to use the System namespace to find any names it hasn’t seen before. Console. This is the same error that you will get if you try to use the StreamWriter class without telling the compiler to look in the System. Fortunately the StreamReader object provides a property called EndOfStream that a program can use to determine when the end of the file has been reached. in that the program will create a stream to do the actual work. The above program connects a stream to the file Test. In this case the stream that is used is a StreamReader. reads the first line from the file.Vases) and so the IO namespace is actually held within the System namespace. Detecting the End of an Input File Repeated calls of ReadLine will return successive lines of a file.txt and display every line in the file on the console. this does not imply that you use all the namespaces defined within it.txt. If the file can’t be found then the attempt to open it will fail and the program will throw an exception. However.Close(). when the compiler sees the statement: Console. C# Programming © Rob Miles 2010 74 .IO. However.txt").6.WriteLine("Hello World"). display it on the screen and then close the stream.the compiler will look in the System namespace. fail to find an object called Console and generate a compilation error. In other words. The while loop will stop the program when the end of the file is reached. } reader. 3.it knows to look in the System namespace for that object so that it can use the WriteLine method on it. .IO namespace. Namespaces are a great way to make sure that names of items that you create don’t clash with those from other programmers. and so you must include the above line for file handling objects to be available. Console.WriteLine (line).ReadLine(). In other words.WriteLine("Hello World").Creating Programs Using Files item it hasn’t seen before it will automatically look in the namespaces it has been told to use.Close(). just because you use a namespace. reader = new StreamReader("Test.WriteLine(line). reader. while (reader. TextReader reader = new StreamReader("Test. If the programmer miss-types the class name: Consle. The above program will open up the file test. .ReadLine(). StreamReader reader.6 Reading from a File Reading from a file is very similar to writing. When the property becomes true the end of the file has been reached. to use the file handing classes you will need to add the following statement at the very top of your program: using System. It is possible to put one namespace inside another (just like a librarian would put a cabinet of Vases in the Roman room which he could refer to as Roman.EndOfStream == false) { string line = reader. We will see how you can create your own namespaces later on.txt"). if your program reaches the end of the file the ReadLine method will return an empty string each time it is called. string line = reader. txt is in the MyProgs folder too.txt) then the system assumes the file that is being used is stored in the same folder as the program which is running. You can create your own folders inside these (for example Documents\Stories). another for Pictures and another one for Music.txt". If you use Windows you will find that there several folders created for you automatically. Each file you create is placed in a particular folder. which is held in the folder data which is on drive C. The location of a file on a computer is often called the path to the file. if you are running the program FileRead.7 File Paths in C# If you have used a computer for a while you will be familiar with the idea of folders (sometimes called directories).6. If you don’t give a folder location when you open a file (as we have been doing with the file Test. the location of the folder and the name of the file itself. which is in turn held in the folder 2009. path = @"c:\data\2009\November\sales. One can be used for Documents. I’d advise you to make sure that your path separators are not getting used as control characters.txt. C# Programming © Rob Miles 2010 75 . If you want to use a file in a different folder (which is a good idea. The backslash (\) characters in the string serve to separate the folders along the path to the file. as data files are hardly ever held in the same place as programs run from) you can add path information to a filename: string path. If you have problems where your program is not finding files that you know are there. In other words. These are used to organise information we store on the computer. The above statements create a string variable which contains the path to a file called sales. This file is held in the folder November. Note that I have specified a string literal that doesn’t contain control characters (that is what the @ at the beginning of the literal means) as otherwise the \ characters in the string will get interpreted by C# as the start of a control sequence.Creating Programs Using Files 3.exe in the folder MyProgs then the above programs will assume that the file Test. The path a file can be broken into two parts. implement transactions that change the content of one or more items in the system) are common to many other types of programs. The program we are making is for a bank. We will be creating the entire bank application using C# and will be exploring the features of C# that make this easy. There are many thousands of customers and the manager has also told us that there are also a number of different types of accounts (and that new types of account are invented from time to time). search for information for a particular person. the "United Friendly and Really Nice Bank of Lovely People ™". Programmer’s Point: Look for Patterns The number of different programs in the world is actually quite small. It is unlikely that you will get to actually implement an entire banking system during your professional career as a programmer (although it might be quite fun – and probably rather lucrative). Of course if C# Programming © Rob Miles 2010 76 . The bank manager has told us that the bank stores information about each customer. This information includes their name. Other data items might be added later. However.1 Our Case Study: Friendly Bank The bulk of this section is based on a case study which will allow you to see the features of C# in a strong context. The system must also generate warning letters and statements as required. balance and overdraft value. account number. address. At the moment we are simply concerned with managing the account information in the bank. from video games to robots. 4. A lot of the things that our bank is going to do (store a large amount of information about a large number of individuals. from a programming point of view it is an interesting problem and as we approach it we will uncover lots of techniques which will be useful in other programs that we might write. This equally as important. 4. By setting out the scope at the beginning you can make sure that there are no unpleasant surprises later on. a statement of what the system will not do. These notes should put the feature into a useful context.2 Enumerated Types These sound really posh.Creating Solutions Our Case Study: Friendly Bank 4 Creating Solutions 4. otherwise known as the Friendly Bank. If anyone asks you what you learnt today you can say "I learnt how to use enumerated types" and they will be really impressed. by implication. Bank Notes At the end of some sections there will be a description of how this new piece of C# will affect how we create our bank system.1. as a customer will not usually have clear idea of what you are doing and may well expect you to deliver things that you have no intention of providing. You are taking the role of a programmer who will be using the language to create a solution for a customer. This is also.1 Bank System Scope The scope of a system is a description of the things that the system is going to do. but how these are managed is not a problem for me. Sample states Enumerated types are very useful when storing state information. I could do something with numbers if I like: Empty sea = 1 Attacked = 2 Battleship = 3 Cruiser = 4 Submarine = 5 Rowing boat = 6 However. States are not quite the same as other items such as the name of a customer or the balance of their account. I am sort of assembling more metadata here. For example. openSea = SeaState.Creating Solutions Enumerated Types they know about programming they'll just say "Oh. sometimes we want to hold a range of particular values or states. in that I have decided that I need to keep track of the sea and then I have worked out exactly what I can put in it. If we want to hold something which is either true or false we can use a bool. C# Programming © Rob Miles 2010. For example I must write: SeaState openSea .2. and must be managed solely in terms of these named enumerations.EmptySea. We know that if we want to hold an integer value we can use an int type. 4. Of course C# itself will actually represent these states as particular numeric values. Cruiser. this would mean that I have to keep track of the values myself and remember that if we get the value 7 in a sea location this is clearly wrong. It can only have the given values above. But if you think of "enumerated" as just meaning "numbered" things get a bit easier. However. Attacked. you mean you’ve numbered some states" and not be that taken with it. C# has a way in which we can create a type which has just a particular set of possible values. My variable openSea is only able to hold values which represent the state of the sea contents. Submarine. I have created a type called SeaState which can be used to hold the state of a particular part of the sea. These types are called "enumerated types": enum SeaState { EmptySea. To understand what we are doing here we need to consider the problem which these types are intended to solve. RowingBoat } .1 Enumeration and states Enumerated sounds posh. Battleship. OffTheMarket etc) then you should think in terms of using enumerated types to hold the values. Green. RedAmber. like keywords are.2 Creating an enum type The new enum type can be created outside any class and creates a new type for use in any of my programs: using System. Amber } . "New". This shows that these items are extra types I have created which can be used to create variables. "Active". Sold. or states (for example OnSale. It is important that you understand what is happening here. Frozen.Red. C# Programming © Rob Miles 2010 78 .2. UnderOffer. Every account will contain a variable of type AccountState which represents the state of that account. "Closed" and "Under Audit" as states for our bank account.Creating Solutions Enumerated Types Note that types I create (like SeaState) will be highlighted by the editor in a blue colour which is not quite the same as keywords. Previous we have used types that are part of C#. Active. 4. The program becomes simpler to write. If this is the case it is sensible to create an enumerated type which can hold these values and no others enum AccountState { New. enum TrafficLight { Red. Closed } . We now have a variable which can hold state information about an account in our bank. For example. Programmer’s Point: Use enumerated types Enumerated types are another occasion where everyone benefits if you use them. Now we have reached the point where we are actually creating our own data types which can be used to hold data values that are required by our application. You should therefore use them a lot. for example int and double. easier to understand and safer. UnderAudit. light = TrafficLight. we could have the states "Frozen". class EnumDemonstration { public static void Main () { TrafficLight light . For the bank you want to hold the state of an item as well as other information about the customer. } } Every time that you have to hold something which can take a limited number of possible values. but they are not actually part of the C# language. get in written form exactly what they expect your system to do. 4. This is all very well.Creating Solutions Structures 4. Establish precisely the specification.integer value The Friendly Bank have told you that they will only be putting up to 50 people into your bank storage so. If we were talking about a database (which is actually what we are writing). would be called a field.3.string customer address . string [] addresses = new string [MAX_CUST] . (Remember that array subscript values start at 0).3 Structures Structures let us organise a set of individual values into a cohesive lump which we can map onto one of the items in the problem that we are working on. A structure is a collection of C# variables which you want to treat as a single entity.. In our program we are working on the basis that balance[0] holds the balance of the first customer in our database. Consider how you will go about storing the data.e. 2. the lump of data for each customer would be called a record and an individual part of that lump.integer value account balance .1 What is a Structure? Often when you are dealing with information you will want to hold a collection of different things about a particular item.integer value overdraft limit .2 Creating a Structure C# lets you create data structures. However it would me much nicer to be able to lump your record together in a more definite way.3. 4. In C# a lump of data would be called a structure and each part of it would be called a field. after a while you come up with the following: const int MAX_CUST = 50. int [] accountNos = new int [MAX_CUST] . Negotiate an extortionate fee. What we have is an array for each single piece of data we want to store about a particular customer. Like any good programmer who has been on my course you would start by doing the following: 1. int [] overdraft = new int [MAX_CUST] . A sample structure From your specification you know that the program must hold the following: customer name . string [] names = new string [MAX_CUST] . and so on. overdraft [0] holds the overdraft of the first customer. for example the overdraft value. int [] balances = new int [MAX_CUST] . and you could get a database system working with this data structure. 3. i.string account number . AccountState [] states = new AccountState [MAX_CUST] . would refer to the integer field AccountNumber in the structured variable RobsAccount. public string Address . public int Overdraft .Creating Solutions Structures struct Account { public AccountState State. called Bank which can hold all the customers. 4. so that: Bank [25].3. (i. We can assign one structure variable to another. This defines a structure.3 Using a Structure A program which creates and sets up a structure looks like this: using System.AccountNumber . This would copy the information from the RobsAccount structure into the element at the start of the Bank array. public string Name .Name . for example: RobsAccount. When the assignment is performed all the values in the source structure are copied into the destination: Bank[0] = RobsAccount. public int Balance . UnderAudit. The second declaration sets up an entire array of customers. Active. Account [] Bank = new Account [MAX_CUST].would be the string containing the name of the customer in the element with subscript 25. just as we would any other variable type. which can hold the information for a single customer. which contains all the required customer information. } . (full stop) separating them. We refer to individual members of a structure by putting their name after the struct variable we are using with a . C# Programming © Rob Miles 2010 80 . Frozen. the AccountNumber value in RobsAccount) You can do this with elements of an array of structures too. // enum enum AccountState { New. Closed } . The first declaration sets up a variable called RobsAccount. Having done this we can now define some variables: Account RobsAccount . public int AccountNumber . called Account.e. 2010 2010 2010 83 in that it prints out the name "Rob".Creating Solutions Objects. Console. But when we create a reference we don't actually get one of the things that it refers to.Name = "Rob". class StructsAndObjectsDemo { public static void Main () { Account RobsAccount . We solve the problem by creating an instance of the class and then connecting our tag to it. RobsAccount.cs(12. } . Structures and References It then sets the name property of the variable to the string "Rob". .is an attempt to find the thing that is tied to this tag and set the name property to "Rob". } } The account information is now being held in a class. rather than a structure. "you are trying to follow a reference which does not refer to anything. If you have the tag you can then follow the rope to the object it is tied to. Creating and Using an Instance of a Class We can make a tiny change to the program and convert the bank account to a class: class Account { public string Name .Name = "Rob". and I could use them in just the same way.WriteLine (RobsAccount. Account. If we run this program it does exactly what you would expect. The account class is called. in effect. If the structure contained other items about the bank account these would be stored in the structure as well. This looks like a declaration of a variable called RobsAccount. Such references are allowed to refer to instances of the Account. The compiler therefore says.3): error CS0165: Use of unassigned local variable ' RobsAccount' So.Name ). and so it gives me an error because the line: RobsAccount. this is not what it seems. Since the tag is presently not tied to anything our program would fail at this point. The compiler knows this. The problem is that when we compile the program we get this: ObjectDemo. therefore I am going to give you a 'variable undefined' error". RobsAccount What you actually get when the program obeys that line is the creation of a reference called RobsAccount. what is going on? To understand what is happening you need to know what is performed by the line: Account RobsAccount. in that they can be tied to something with a piece of rope. quite simply. But in the case of objects. You can think of them as a bit like a luggage tag. This is achieved by adding a line to our program: C# Programming © Rob Miles 2010 84 . Consider the following code: C# Programming © Rob Miles 2010 85 . This is because an array is actually implemented as an object. you hold a tag which is tied onto an instance… Multiple References to an Instance Perhaps another example of references would help at this point.Name = "Rob". This is because the object instance does not have the identifier RobsAccount. Console. The two come hand in hand and are inseparable. not RobsAccount. RobsAccount. We use it to create arrays.Creating Solutions Objects. RobsAccount = new Account(). I'll repeat that in a posh font: “An object is an instance of a class” I have repeated this because it is very important that you understand this.WriteLine (RobsAccount. } . and that means that we must manage our access to a particular object by making use of references to it.2 References We now have to get used to the idea that if we want to use objects. we have to use references. Structures are kind of useful. 4. The new keyword causes C# to use the class information to actually make an instance. An object is an instance of a class. it is simply the one which RobsAccount is connected to at the moment. but you must remember that when you hold a reference you do not hold an instance. The thing that new creates is an object. Account RobsAccount Name: Rob We have seen this keyword new before. and what it can do. class StructsAndObjectsDemo { public static void Main () { Account RobsAccount . but for real object oriented satisfaction you have to have an object. Structures and References class Account { public string Name . Actually this is not that painful in reality. Note that in the above diagram I have called the object an Account. in that you can treat a reference as if it really was the object just about all of the time. } } The line I have added creates a new Account object and sets the reference RobsAccount to refer to it.Name ). A class provides the instructions to C# as to what is to be made.4. and so we use new to create it. Name ). Console. so you need to remember that changing the object that a reference refers to may well change that instance from the point of view of other objects.WriteLine (RobsAccount. The reference RobsAccount is made to refer to the new item. RobsAccount.Name = "Jim". RobsAccount = new Account(). sets the name property of it to Rob and then makes another account instance. Structures and References Account RobsAccount . Console. Account Temp . The question is.Name = "Jim".Name ). because they are the same object.Name ). this can be made clearer with a diagram: C# Programming © Rob Miles 2010 86 . The question is: What happens to the first instance? Again. Console. Temp = RobsAccount. This code makes an account instance. since that is the name in the object that RobsAccount is referring to.Name ).WriteLine (RobsAccount. what would the second call of WriteLine print out? If we draw a diagram the answer becomes clearer: Account RobsAccount Name: Jim Temp Both of the tags refer to the same instance of Account. This means that any changes which are made to the object that Temp refers to will also be reflected in the one that RobsAccount refers to. RobsAccount. RobsAccount = new Account(). which has the name set to Jim. Console. Temp.Creating Solutions Objects.WriteLine (RobsAccount. This indicates a trickiness with objects and references.Name = "Rob". RobsAccount = new Account(). RobsAccount. No References to an Instance Just to complete the confusion we need to consider what happens if an object has no references to it: Account RobsAccount .Name = "Rob".WriteLine (RobsAccount. There is no limit to the number of references that can be attached to a single instance. This means that the program would print out Jim. When you pay someone with one of these coins you don’t actually pick it up and give it to them. meaning another job for the garbage collector.Creating Solutions Objects. When I work with objects I worry about how much creating and destroying I am doing. They seem to make it harder to create and use objects and may be the source of much confusion. You should also remember that you can get a similar effect when a reference to an instance goes out of scope: { Account localVar . That is why we use references in our programs. The value of a ―coin‖ in the Yap currency is directly related to the number of men who died in the boat bringing the rock to the island. So why do we bother with them? To answer this we can consider the Pacific Island of Yap.4. Structures and References Account RobsAccount Name: Rob Account Name: Jim The first instance is shown ―hanging‖ in space. C# Programming © Rob Miles 2010 87 . Note that the compiler will not stop us from ―letting go‖ of items like this. } The variable localVar is local to the block. you must remember that creating and disposing of objects will take up computing power. Instead you just say ―The coin in the road on top of the hill is now yours‖. Consider a bank which contains many accounts. localVar = new Account(). This means that when the program execution leaves the block the local variable is discarded. called the ―Garbage Collector‖ which is given the job of finding such useless items and disposing of them. with nothing referring to it. The currency in use on this island is based around 12 feet tall stones which weigh several hundred pounds each. Programmer’s Point: Try to avoid the Garbage Collector While it is sometimes reasonable to release items you have no further use for. Just because the objects are disposed of automatically doesn’t mean that you should abuse the facility. In other words they use references to manage objects that they don’t want to have to move around. 4. Indeed the C# language implementation has a special process. As far as making use of data in the instance is concerned. it might as well not be there.3 Why Bother with References? References don’t sound much fun at the moment. If we wanted to sort them into alphabetical order of customer name we have to move them all around. This means that the only reference to the account is also removed. We can get over this. for example they might want to order it on both customer surname and also on account number. Sorting by use of a tree In the tree above each node has two references. each of which is ordered in a particular way: Sorting by using references If we just sort the references we don’t have to move the large data items at all.Creating Solutions Objects. the other to a node which is ―darker‖. Structures and References Sorting by moving objects around If we held the accounts as an array of structure items we would have to do a lot of work just to keep the list in order. References and Data Structures Our list of sorted references is all very good. one can refer to a node which is ―lighter‖. by structuring our data into a tree form. The bank may well want to order the information in more than one way too. and also speed up searching. Then C# Programming © Rob Miles 2010 88 . With references we just need to keep a number of arrays of references. New objects can be added without having to move any objects. If I want a sorted list of the items I just have to go as far down the ―lighter‖ side as I can and I will end up at the lightest. instead the references can be moved around. Without references this would be impossible. but if we want to add something to our sorted list we still have to move the references around. The thing that we are trying to do here is best expressed as: ―Put off all the hard work for as long as we can. for now we just need to remember that the reference and the object are distinct and separate. We will consider this aspect of object use later.Creating Solutions Designing With Objects I go up to the one above that (which must be the next lightest). Reference Importance The key to this way of working is that an object can contain references to other objects. it will not be possible to move them around memory if we want to sort them.5 Designing With Objects We are now going to start thinking in terms of objects. This means that the only way to manipulate them is to leave them in the same place and have lists of references to them. it is a programming document. Programmer’s Point: Data Structures are Important This is not a data structures document. Then I go down the dark side (Luke) and repeat the process. and if possible get someone else to do it. And if the manager comes along with a need for a new structure or view we can create that in terms of references as well.. But sometime in the future you are going to have to get your head around how to build structures using these things. This all comes back to the ―creative laziness‖ that programmers are so famous for.‖ Objects let us do this. don’t worry. The references are very small "tags" which can be used to locate the actual item in memory. Bank Notes: References and Accounts For a bank with many thousands of customers the use of references is crucial to the management of the data that they hold. The reason that we do this is that we would like a way of making the design of our systems as easy as possible. in which case the item is not in the structure. a bit like President Kennedy did all those years ago: C# Programming © Rob Miles 2010 89 . object based design turns this on its head. The accounts will be held in the memory of the computer and. Searching is also very quick. I just find the place on the tree that they need to be hung on and attach the reference there. If you don’t get all the stuff about trees just yet. The neat thing about this approach is also that adding new items is very easy. and it would also be possible to have several such lists. because of the size of each account and the number of accounts being stored. Just remember that references are an important mechanism for building up structures of data and leave it at that. This means that we can offer the manager a view of his bank sorted by customer name and another view sorted in order of balance. 4. as well as the data payload. Sorting a list of references is very easy. in that I can look at each node and decide which way to look next until I either find what I am looking for or I find there is no reference in the required direction. And once we have decided on the actions that the account must perform.Balance = 0. This will let me describe all the techniques that are required without getting bogged down too much. RobsAccount. Programmer’s Point: Not Everything Should Be Possible Note that there are also some things that we should not be able to do with our bank account objects. Instead we ask it to do these things for us.Balance = 99.5. In this section we are going to implement an object which has some of the behaviours of a proper bank account. along with what should be done. metadata and testing. For the sake of simplicity. Each time I create an instance of the class I get all the members as well. The account number of an account is something which is unique to that account and should never change. for now I’m just going to consider how I keep track of the balance of the accounts. since this is specially designed to hold financial values. we don’t have to worry precisely how they made it work – we just have to sit back and take the credit for a job well done. What a bank account object should be able to do is part of the metadata for this object. We can get this behaviour by simply not providing a means by which it can be changed. The first thing is to identify all the data items that we want to store in it. } The Account class above holds the member that we need to store about the balance of our bank accounts. C# Programming © Rob Miles 2010 90 . 4. The design of our banking application can be thought of in terms of identifying the objects that we are going to use to represent the information and then specifying what things they should be able to do. my fellow Americans: ask not what your country can do for you—ask what you can do for your country‖ (huge cheers) We don’t do things to the bank account. That way we can easily find out if bad things are being done. We might even identify some things as being audited. It is important at design time that we identify what should not be possible. we can consider our bank account in terms of what we want it to do for us. I’ve used the decimal type for the account balance. RobsAccount = new Account(). This means that any programmer writing the application can do things like: RobsAccount. We have already seen that it is very easy to create an instance of a class and set the value of a member: Account RobsAccount . we then might be able to get somebody else to make it do these things. Members of a class which hold a value which describes some data which the class is holding are often called properties.Creating Solutions Designing With Objects ―And so. the next thing we need to do is devise a way in which each of the actions can be tested. The really clever bit is that once we have decided what the bank account should do. If our specification is correct and they implement it properly. in that an object will keep track of what has been done to it. The reason that this works is that the members of the object are all public and this means that anybody has direct access to them. This brings us back to a couple of recurring themes in this document. We have seen that each of the data items in a class is a member of it and stored as part of it.1 Data in Objects So. class Account { public decimal Balance. The posh word for this is encapsulation. C# Programming © Rob Miles 2010 91 . whatever else happens.I will get an error when I try to compile the program: PrivateDemo.2 Member Protection inside objects If objects are going to be useful we have to have a way of protecting the data within them.3): error CS0122: 'PrivateMembers. thanks for the vote of confidence folks. For example.balance = 0. The first thing we need to do is stop the outside world from playing with our balance value: class Account { private decimal balance. This means that the outside world no longer has direct access to it. now you can’t change it at all‖. 4. Ideally I want to get control when someone tries to change a value in my objects. in our bank program we want to make sure that the balance is never changed in a manner that we can't control. } balance = balance .and take away all my money.cs(13.5. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . Consider the program: class Account { private decimal balance = 0. but only using code actually running in the class. return true. Changing private members I can tell what you are thinking at this point. Instead it is now private. It turns out that I can change the value. If I write the code: RobsAccount. my part of the program does not go wrong. If we are going to provide a way of stopping this from happening we need to protect the data inside our objects. Well.Account.amount .balance' is inaccessible due to its protection level The balance value is now held inside the object and is not visible to the outside world. } } . You are thinking ―What is the point of making it private. and stop the change from being made if I don’t like it.Creating Solutions Designing With Objects . I want all the important data hidden inside my object so that I have complete control over what is done with it. } The property is no longer marked as public. . This technology is the key to my defensive programming approach which is geared to making sure that. since we want people to interact with our objects by calling methods in them. The method WithdrawFunds is a member of the Account class and can therefore access private members of the class.WriteLine ( "Cash Withdrawn" ) . In fact.). If you don’t care about possible corruption of the member and you want your program to run as quickly as possible you can make a data member public. In the code above the way that I am protecting the balance value is a reflection of how the customer wants me to make sure that this value is managed properly. These (for example the ubiquitous i) always start with a lower case letter. So perhaps now is a good time. public Methods You may have noticed that I made the WithdrawFunds method public. C# Programming © Rob Miles 2010 92 .Creating Solutions Designing With Objects class Bank { public static void Main () { Account RobsAccount. task you can make it private. They would call their balance value m_balance so that class members are easy to spot. and expect developers to adhere to these. If you want to write a method which is only used inside a class and performs some special. because I reckon that the name of the member is usually enough. make it private if it is a method member (i. This makes it easy for someone reading my code. The metadata that I gather about my bank system will drive how I provide access to the members of my classes. if ( RobsAccount. But I make the first letter of private members lower case (as in the case of the balance data member of our bank account). } } } This creates an account and then tries to draw five pounds out of it.WriteLine ( "Insufficient Funds" ) . the rules can be broken on special occasions. since the initial balance on my account is zero. The convention also extends to variables which are local to a block. because they can see from the name of a class member whether or not it is public or private. most development companies have documents that set out the coding conventions they use. RobsAccount = new Account(). Programmer’s Point: Metadata makes Members and Methods I haven’t mentioned metadata for at least five minutes. but opinions differ on this one.e. it holds data) of the class. This means that code running outside the class can make calls to that method. secret. This will of course fail.e. Some people go further and do things like put the characters m_ in front of variables which are members of a class. In general the rules are: if it is a data member (i. This has got to be the case. The most important thing in this situation is that the whole programming team adopts the same conventions on matters like these. but it shows how I go about providing access to members in an account. it does something) make it public Of course.WithdrawFunds (5) ) { Console. } else { Console. I don’t usually go that far. Creating Solutions Designing With Objects 4. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . If it does not my program is faulty.3 A Complete Account Class We can now create a bank account class which controls access to the balance value: public class Account { private decimal balance = 0. for example: Account test = new Account(). C# Programming © Rob Miles 2010 93 . } public void PayInFunds ( decimal amount ) { balance = balance + amount .5.PayInFunds(50). I have created three methods which I can use to interact with an account object. At the end of this set of statements the test account should have 50 pounds in it.WriteLine ( "Pay In test failed" ). } balance = balance . I can pay money in.PayInFunds(50). They then search out the programmer who caused the failure and make him or her pay for coffee for the next week. The method GetBalance is called an accessor since it allows access to data in my business object. test. find out how much is there and withdraw cash. I could write a little bit of code to test these methods: Account test = new Account(). Of course I must still read the output from all the tests.amount . which is tedious. } } The bank account class that I have created above is quite well behaved. if ( test. Later we will consider the use of unit tests which make this much easier.GetBalance() != 50 ) { Console. My tests count the number of errors that they have found. and if you don’t notice it then you might think your code is OK. test. } My program now tests itself. Programmer’s Point: Make a Siren go off when your tests fail The above test is good but not great. in that it does something and then makes sure that the effect of that action is correct. so that it is impossible to ignore a failing test. return true. It just produces a little message if the test fails. If the error count is greater than zero they print out a huge message in flashing red text to indicate that something bad has happened. Some development teams actually connect sirens and flashing red lights to their test systems. } public decimal GetBalance () { return balance. You have to read that message. It is very important that you learn what static means in the context of C# programs. The other kind of program that is very hard to test in this way is any kind of game. Programmer’s Point: Some things are hard to test Test development is a good way to travel.4 Test Driven Development I love test driven development. When you fix bugs in your program you need to be able to convince yourself that the fixes have not broken some other part (about the most common way of introducing new faults into a program is to mend a bug). We have used it lots in just about every program that we have ever written: C# Programming © Rob Miles 2010 94 . I can be fairly confident that the user interface will be OK too. 4. The only solution in this situation is to set out very clearly what your tests are trying to prove (so that the human testers know what to look for) and make it very easy to change the values that will affect the gameplay. For example it should be easy to adjust how much damage a hit from an alien causes to your spacecraft. You don't do the testing at the end of the project. However. Some types of programs are really hard to test in this way. This is mainly because the quality of gameplay is not something you can design tests for. place develop using tests.e. Far better to test the code as you write it. when you have the best possible understanding of what it is supposed to do.6. Many projects are doomed because people start programming before they have a proper understanding of the problem. 3.Creating Solutions Static Items 4. If the bugs are in an old piece of code you have to go through the effort of remembering how it works. If you have a set of automatic tests that run after every bug fix you have a way of stopping this from happening.5. because although it is easy to send things into a program it is often much harder to see what the program does in response. If I ever write anything new you can bet your boots that I will write it using a test driven approach. You can write code early in the project which will probably be useful later on. As long as my object tests are passed.1 Static class members The static keyword lets us create members which are not held in an instance. since you might be using code that you wrote some time back. And there is a good chance that the tests that you write will be useful at some point too. Anything with a front end where users type in commands and get responses is very hard to test like this. Only when someone comes back and says “The game is too hard because you can’t kill the end of level boss without dying” can you actually do something about it. and the speed of all the game objects. So. the code that provides the user interface where the customer enters how much they want to withdraw will be very simple and connect directly to the methods provided by my objects. In the case of our bank account above. we can also create members which are held as part of the class. 2. i. 4. This is usually the worst time to test. My approach in these situations is to make the user interface part a very thin layer which sits on top of requests to objects to do the work. but it does not solve all your problems. You will thank me later. but in the class itself. This solves three problems that I can see: 1. they exist outside of any particular instance. Writing the tests first is actually a really good way of refining your understanding.6 Static Items At the moment all the members that we have created in our class have been part of an instance of the class. This means that whenever we create an instance of the Account class we get a balance member. It is part of the class AccountTest. 4. This is how my program actually gets to work. I solve the problem by making the interest rate member static: C# Programming © Rob Miles 2010 95 . and so this method must be there already. RobsAccount. Console. I think this is time for more posh font stuff: Static does not mean “cannot be changed”. } } The AccountTest class has a static member method called Main. and if I missed one account. This would be tedious. Members of a class which have been made static can be used just like any other member of a class. We know that this is the method which is called to run the program.GetBalance()). The customer has told us that one of the members of the account class will need to be the interest rate on accounts. (of course if I was doing this properly I'd make this stuff private and provide methods etc. In the program we can implement this by adding another member to the class which holds the current interest rate: public class Account { public decimal Balance . This means that to implement the change I'd have to go through all the accounts and update the rate. If the interest rate changes it must change for all accounts. for it is important: “A static member is a member of the class. RobsAccount. The snag is. Static does not mean "cannot be changed".WriteLine ("Balance:" + test. public decimal InterestRateCharged .PayInFunds (50). not part of an instance of the class.6.InterestRateChanged = 10. } Now I can create accounts and set balances and interest rates on them.Balance = 100. test. possibly expensive. Consider the interest rates of our bank accounts. If I made fifty AccountTest instances. but I'm keeping things simple just now).Creating Solutions Static Items class AccountTest { public static void Main () { Account test = new Account(). I've been told that the interest rate is held for all the accounts. not a member of an instance of the class” I don't have to make an instance of the AccountTest class to be able to use the Main method. Account RobsAccount = new Account(). In terms of C# the keyword static flags a member as being part of the class. otherwise it cannot run. Either a data member or a method can be made static. in that when it starts it has not made any instances of anything. I will write that down again in a posh font.2 Using a static data member of a class Perhaps an example of static data would help at this point. they would all share the same Main method. There might be a time where the age limit changes. and you don't want to have to update all the objects in your program. "With great power comes great responsibility". we can't call the method until we have an Account instance. For example.Balance = 100.Creating Solutions Static Items public class Account { public decimal balance . as Spiderman's uncle said. But you can also use them when designing your system.InterestRateChanged = 10. We have been doing this for ages with the Main method. } else { return false. } The interest rate is now part of the class. The snag is that. It would then return true or false depending on whether these are acceptable or not: public bool AccountAllowed ( decimal income. I can now call the method by using the class name: C# Programming © Rob Miles 2010 96 . int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. Account. 4. } } This checks the age and income. You should be careful about how you provide access to static data items. So they should always be made private and updated by means of method calls. public static decimal interestRateCharged . It would take in their age and income. } } Now the method is part of the class. We can solve this by making the method static: public static bool AccountAllowed ( decimal income. RobsAccount.. you must be over 17 and have at least 1000 pounds income to be allowed an account. This means that I have to change the way that I get hold of it: Account RobsAccount = new Account(). we might have a method which decides whether or not someone is allowed to have a bank account. But of course. not part of any instance.3 Using a static method in a class We can make methods static too. at the moment. not an instance of the class. A change to a single static value will affect your entire system.6. int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. Things like the limits of values (the largest age that you are going to permit a person to have) can be made static. } else { return false. 21 ) ) { Console.21): error CS0120: An object reference is required for the nonstatic field.AccountAllowed ( 25000.WriteLine ( "Allowed Account" ). Using member data in static methods The Allowed method is OK. The compiler is unhappy because in this situation the method would not have any members to play with. how about this: The members minIncome and minAge are held within instances of the Account class.43): error CS0120: An object reference is required for the nonstatic field. method. in that I now have members of the class which set out the upper limits of the age and income. a static method can run without an instance (since it is part of the class).cs(19.minIncome' AccountManagement. We can fix this (and get our program completely correct) by making the income and age limits static as well: C# Programming © Rob Miles 2010 97 .minAge' As usual. However it is a bad program. } } } This is a better design. the compiler is telling us exactly what is wrong. but of course I have fixed the age and income methods into it. or property 'Account. } else { return false.Creating Solutions Static Items if ( Account. What the compiler really means is that "a static method is using a member of the class which is not static". since the class above will not compile: AccountManagement. int age) { if ( ( income >= minIncome) && ( age >= minAge) ) { return true. However. private int minAge = 18. If that doesn’t help. } This is nice because I have not had to make an instance of the account to find out if one is allowed. I might decide to make the method more flexible: public class Account { private decimal minIncome = 10000. public static bool AccountAllowed(decimal income. method.cs(19. or property 'Account. using language which makes our heads spin. The constructor method is a member of the class and it is there to let the programmer get control and set up the contents of the shiny new object. The limit values should not be held as members of a class. public static bool AccountAllowed(decimal income. so that it can execute without an instance. One of the rules of the C# game is that every single class must have a constructor method to be called when a new instance is created. for a change. when you are building your system you should think about how you are going to make such methods available for your own use. accounts for five year olds have a different interest rate from normal ones". being friendly here. not an instance of a class. therefore. Bank Notes: Static Bank Information The kind of problems that we can use static to solve in our bank are: static member variable: the manager would like us to be able to set the interest rate for all the customer accounts at once. Programmer’s Point: Static Method Members can be used to make Libraries Sometimes in a development you need to provide a library of methods to do stuff. This is because the C# compiler is. ―We’ve been making objects for a while and I’ve never had to provide a constructor method‖. since we want them to be the same for all instances of the class. A single static member of the Account class will provide a variable which can be used inside all instances of the class. int age) { if ( ( income > minIncome) && ( age > minAge) ) { return true. If you look closely at what is happening you might decide that what is happening looks quite a bit like a method call. But because there is only a single copy of this value this can be changed and thereby adjust the interest rate for all the accounts. This is actually exactly what is happening. for example sin and cos. you say. At this point we know we can’t use static because we need to hold different values for some of the instances. I must make it static. making them static is what we should have done in the first place.Creating Solutions The Construction of Objects public class Account { private static decimal minIncome . the compiler instead quietly creates a default one for you and uses that. Again.7 The Construction of Objects We have seen that our objects are created when we use new to bring one into being: test = new Account(). 4. ―But wait a minute‖. I can't make this part of any Account instance because at the time it runs an account has not been generated. When an instance of a class is created the C# system makes a call to a constructor method in that class. in that in this situation all we want is the method itself. this makes perfect sense. Any value which is held once for all classes (limits on values are another example of this) is best managed as a static value. C# Programming © Rob Miles 2010 98 . It makes sense to make these methods static. private static int minAge . Rather than shout at you for not providing a constructor method. In the C# system itself there are a huge number of methods to perform maths functions. } } } If you think about it. static member method: the manager tells us that we need a method to determine whether or not a given person is allowed to have an account. } else { return false. The time it becomes impossible to use static is when the manager says "Oh. In other words I want to do: robsAccount = new Account( "Rob Miles". "Hull".7. but it does show how the process works. This means that when my program executes the line: robsAccount = new Account().WriteLine ( "We just made an account" ). but it does not return anything..the program will print out the message: We just made an account Note that this is not very sensible. It is called when we perform new. It is public so that it can be accessed from external classes who might want to make instances of the class. } } This constructor is not very constructive (ho ho) but it does let us know when it has been called. 0 ). Feeding the Constructor Information It is useful to be able to get control when an Account is created. .2 Our Own Constructor For fun. in that it will result in a lot of printing out which the user of the program might not appreciate. If you don’t supply a constructor (and we haven’t so far) the compiler creates one for us. all I have to do is make the constructor method to accept these parameters and use them to set up the members of the class: C# Programming © Rob Miles 2010 99 . which we will discuss later. we could make a constructor which just prints out that it has been called: public class Account { public Account () { Console. address. As an example. but in this case it is simply solving the problem without telling you. 4. If I create my own constructor the compiler assumes that I know what I’m doing and stops providing the default one.7. It accepts no parameters. It turns out that I can do this very easily. This can cause problems.Creating Solutions The Construction of Objects You might think this is strange. in that normally the compiler loses no time in telling you off when you don’t do something. and initial balance of an account holder when the account is created. but it would be even nicer to be able to feed information into the Account when I create it.1 The Default Constructor A constructor method has the same name as the class. I might want to set the name. the address to Hull and the initial balance to zero. 4. public class Account { public Account () { } } This is what the default constructor looks like. This could create a new account and set the name property to Rob Miles. since I want to use the "default" one of zero. address = inAddress.7. In the context of the constructor of a class. Something a bit like this: C# Programming © Rob Miles 2010 100 . In that situation you have to either find all the calls to the default one and update them. This can cause confusion if we have made use of the default constructor in our program and we then add one of our own. } } The constructor takes the values supplied in the parameters and uses them to set up the members of the Account instance that is being created. balance = inBalance.27): error CS1501: No overload for method 'Account' takes '0' arguments What the compiler is telling me is that there is no constructor in the class which does not have any parameters. If I try to do this: robsAccount = new Account(). what this means is that you can provide several different ways of constructing an instance of a class. because it can tell from the parameters given at the call of the method which one to use. private decimal balance. In this respect it behaves exactly as any other method call. nothing in the account.3 Overloading Constructors Overload is an interesting word. // constructor public Account (string inName. "Hull").Creating Solutions The Construction of Objects class Account { // private member data private string name. the only way I can now make an Account object is by supplying a name. Just like me. The default constructor is no longer supplied by the compiler and our program now fails to compile correctly. but has a different set of parameters" The compiler is quite happy for you to overload methods.e. In the context of a C# program it means: "A method has the same name as another. For example. private string address.the compiler will stop being nice to me and produce the error: AccountTest. decimal inBalance) { name = inName. In other words. hem hem. address and starting balance.e. If your code does this the compiler simply looks for a constructor method which has two strings as parameters. I've missed off the balance value. Of course you don't have to do this because your design of the program was so good that you never have this problem. . the compiler only provides a default constructor if the programmer doesn't provide a constructor. many (but not all) of your accounts will be created with a balance value of zero. i. In the context of the "Star Trek" science fiction series it is what they did to the warp engines in every other episode. 4. i. and nothing else.cs(9. string inAddress. or create a default constructor of your own for these calls to use. Note that adding a constructor like this has one very powerful ramification: You must use the new constructor to make an instance of a class. This means that we would like to be able to write robsAccount = new Account("Rob Miles". string inAddress) { name = inName. even if you don't put a bug in your code. balance = 0. 7. } I've made three constructors for an Account instance. To do this I have had to duplicate code. . string inAddress) { name = inName. The first is supplied with all the information. and sets the address to "Not Supplied". balance = 0. Because it is bad. address = inAddress. C# provides a way in which you can call one constructor from another. int julianDate ) SetDate ( string dateInMMDDYY ) A call of: SetDate ( 23. } Overloading a method name In fact. for example you could provide several ways of setting the date of a transaction: SetDate ( int year. balance = inBalance. you can overload any method name in your classes. decimal inBalance) { name = inName. just use the block copy command in the text editor and you can take the same piece of program and use it all over the place. If you need to change this piece of code you have to find every copy of the code and change it. 2005 ). The scary thing is that it is quite easy to do. It is regarded as "dangerous extra work".Creating Solutions The Construction of Objects public Account (string inName. } public Account (string inName. balance = 0.would be matched up with the method which accepts three integer parameters and that code would be executed. address = inAddress. the second is not given a balance and sets the value to 0. But you should not do this. 4. Consider: C# Programming © Rob Miles 2010 101 . The third is not given the address either. This can be useful if you have a particular action which can be driven by a number of different items of data. string inAddress. So. } public Account (string inName) { name = inName.7. int month. int day ) SetDate ( int year. address = inAddress. you still might find yourself having to change it because the specification changes. address = "Not Supplied". This happens more often than you'd think. Good programmers hate duplicating code.4 Constructor Management If the Account class is going to have lots of constructor methods this can get very confusing for the programmer: public Account (string inName. 0 ) { } The keyword this means "another constructor in this class". The syntax of these calls is rather interesting. Failure is not an option. This is sensible. because it reflects exactly what is happening. attempts to withdraw negative amounts of money from a bank account should be rejected. address = inAddress.PayInFunds (1234567890). on to the "proper" constructor to deal with. "Not Supplied". This means that the actual transfer of the values from the constructor into the object itself only happens in one method. In fact. For example.Creating Solutions The Construction of Objects public Account (string inName. 4. For example. the highlighted bits of the code are calls to the first constructor. The "this" constructor runs before the body of the other constructor is entered. So we know that when we create a method which changes the data in an object we have to make sure that the change is always valid. But what is to stop the following: RobsAccount = new Account ("Rob". Constructors cannot fail. You should create one "master" constructor which handles the most comprehensive method of constructing the object. In fact it is outside the block completely. decimal inBalance) { name = inName. Then you should make all the other constructor methods use this to get hold of that method. And this is a problem: Whenever we have written methods in the past we have made sure that their behaviour is error checked so that the method cannot upset the state of our object. They simply pass the parameters which are supplied. Programmer’s Point: Object Construction Should Be Planned The way in which objects are constructed is something that you should plan carefully when you write your program. 0 ) { } public Account ( string inName ) : this (inName. since the call of this does all the work. Constructors are a bit like this.7. "Hull". so the PayInFunds method will refuse to pay the money in. inAddress. There will be an upper limit to the amount of cash you can pay in at once. The whole basis of the way that we have allowed our objects to be manipulated is to make sure that they cannot be broken by the people using them. If you try to do something stupid with a method call it should refuse to perform the action and return something which indicates that it could not do the job. in the code above. C# Programming © Rob Miles 2010 102 .5 A constructor cannot fail If you watch a James Bond movie there is usually a point at which agent 007 is told that the fate of the world is in his hands. 1234567890). balance = inBalance. and the other constructor methods just make calls to it. in that the call to the constructor takes place before the body of the constructor method. we would not let the following call succeed: RobsAccount. As you can see in the code sample above. string inAddress. along with any default values that we have created. string inAddress ) : this (inName. } public Account ( string inName. the body of the constructor can be empty. The really clever way to do this is to make the constructor call the set methods for each of the properties that it has been given. Writing code which will handle all the possible failure conditions in a useful way is much trickier. This can be done. } if ( SetAddress ( inAddress) == false ) { throw new Exception ( "Bad address" + inAddress) . I type in my name wrong and it complains about that. at the expense of a little bit of complication: public Account (string inName. C# Programming © Rob Miles 2010 103 . } } This version of the constructor assembles an error message which describes everything which is wrong with the account. This poses a problem. Writing code to do a job is usually very easy. Whatever happens during the constructor call.e. and if any of them returns with an error the constructor should throw the exception at that Point: public Account (string inName. The only problem here is that if the address is wrong too. Each new thing which is wrong is added to the message and then the whole thing is put into an exception and thrown back to the caller. } if ( SetAddress ( inAddress) == false ) { errorMessage = errorMessage + " Bad addr " + inAddress. } } If we try to create an account with a bad name it will throw an exception. It looks as if we can veto stupid values at every point except the one which is most important. What I want is a way in which I can get a report of all the invalid parts of the item at once. string inAddress) { string errorMessage = "". constructors are not allowed to fail. This means that the user of the constructor must make sure that they catch exceptions when creating objects. i. } if ( errorMessage != "" ) { throw new Exception ( "Bad account" + errorMessage) .Creating Solutions The Construction of Objects Like James Bond. if ( SetName ( inName ) == false ) { errorMessage = errorMessage + "Bad name " + inName. string inAddress) { if ( SetName ( inName ) == false ) { throw new Exception ( "Bad name " + inName) . and it complains about my address. which is not a bad thing. when the object is first created. the user of the method will not know this until they have fixed the name and then called the constructor again. it will complete and a new instance will be created. Then I put my name right. It is normally when I'm filling in a form on the web. I hate it when I'm using a program and this happens. It is a fact of programming life that you will (or at least should) spend more time worrying about how things fail than you ever do about how they work correctly. Constructors and Exceptions The only way round this at the moment is to have the constructor throw an exception if it is unhappy. Programmer’s Point: Managing Failure is Hard Work This brings us on to a kind of recurring theme in our quest to become great programmers. which is what we want. the graphics adapter is usually a separate device which is plugged into the main board. For this to work properly the people who make main boards and the people who make graphics adapters have had to agree on an interface between two devices. During the specification process you need to establish if the code is ever going to be created in multiple language versions. some parts are not "hard wired" to the system. C# Programming © Rob Miles 2010 104 . Software components are exactly the same. Bank Notes: Constructing an Account The issues revolving around the constructor of a class are not directly relevant to the bank account specification as such. You should be familiar with the way that. The next thing to do is consider how we take a further step back and consider expressing a solution using components and interfaces. Posh people call this "abstraction". since they really relate to how the specification is implemented. and not what the system itself actually does. if you write the program as above this might cause a problem when you install the code in a French branch of the bank. If it is you will need to manage the storage and selection of appropriate messages. Fortunately there are some C# libraries which are designed to make this easier. So. For example. Any main board which contains a socket built to the standard can accept a graphics card. we just say "We need an account here" and then move on to other things. This is the progress that we have made so far: representing values by named locations (variables) creating actions which work on the variables (statements and blocks) putting behaviours into lumps of code which we can give names to. That said.8. if the manager says something like "The customer fills in a form. because it means that I can buy a new graphics adapter at any time and fit it into the machine to improve the performance. and how to design systems using them.1 Components and Hardware Before we start on things from a software point of view it is probably worth considering things from a hardware point of view. and from the point of view of what the Account class needs to do. which signals are outputs and so on. This takes the form of a large document which describes exactly how the two components interact. 4. Later we will come back and revisit the problem in a greater level of detail. for example which signals are inputs.. In this section you will find out the difference between an object and a component.Creating Solutions From Object to Component Programmer’s Point: Consider the International Issues The code above assembles a text message and sends it to the user when something bad happens. This is good.8 From Object to Component I take the view that as you develop as a software writer you go through a process of "stepping back" from problems and thinking at higher and higher levels. from the point of view of hardware. enters their name and address and this is used to create the new account" this gives you a good idea of what parameters should be supplied to the constructor. 4. This is a good thing. components are possible because we have created standard interfaces which describe exactly how they fit together. However. in a typical home computer. a system designed without components is exactly like a computer with a graphics adapter which part of the main board. When we are creating a system we work out what each of the parts of it need to do. Our first pass at a bank account interface could be as follows: public interface IAccount { void PayInFunds ( decimal amount ). and compiled in the same way. From the balance management point of view this is all we need. This might happen even after we have installed the system and it is being used. } This says that the IAccount interface is comprised of three methods. This will earn you zero marks. An interface is simply a set of method definitions which are lumped together. I am instead just saying what should be done. In C# we express this information in a thing called an interface. For example. These are usually either text based (the user types in commands and gets responses) or graphical (the user clicks on ―buttons‖ on a screen using the mouse). An interface on the other hand just specifies how a software component could be used by another software component. And quite right too. If you don’t do this your programs will compile fine. Another convention is that the name of an interface should start with the letter I. By describing objects in terms of their interfaces however. since the compiler has no opinions on variable names. in this case what a class must do to be considered a bank account. one to pay money in. An interface is placed in a source file just like a class. another to withdraw it and a third which returns the balance on the account. what it is they have to do. we can use anything which behaves like an Account in this position. It is not possible for me to improve the graphics adapter because it is "hard wired" into the system. instead of starting off by designing classes we should instead be thinking about describing their interfaces. Interfaces and Design So. If everything has been hard wired into place this will be impossible. It sets out a number of methods which relate to a particular task or role. The user interface is the way a person using our program would make it work for them. Please don’t be tempted to answer an exam question about the C# interface mechanism with a long description of how windows and buttons work. 4.Creating Solutions From Object to Component Why we Need Software Components? At the moment you might not see a need for software components. Programmer’s Point: Interface names start with I We have seen that there are things called coding conventions. decimal GetBalance ().e. However. it is unfortunately the case that with our bank system we may have a need to create different forms of bank account class. i.8. and then we create those parts.2 Components and Interfaces One point I should make here is that we are not talking about the user interface to our program. C# Programming © Rob Miles 2010 105 . Well. but you may have trouble sleeping at night. It is not obvious at this stage why components are required. we might be asked to create a "BabyAccount" class which only lets the account holder draw out up to ten pounds each time. bool WithdrawFunds ( decimal amount ). Note that at the interface level I am not saying how it should be done. which set down standards for naming variables. here are two: C# Programming © Rob Miles 2010 106 .Creating Solutions From Object to Component 4. irrespective of what it really is: public class CustomerAccount : IAccount { private decimal balance = 0. You can think of me in a whole variety of ways. The only difference is the top line: public class CustomerAccount : IAccount { . If the class does not contain a method that the interface needs you will get a compilation error: error CS0535: 'AccountManagement. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . Implementing an interface is a bit like a setting up a contract between the supplier of resources and the consumer. } public decimal GetBalance () { return balance.IAccount.8. it has a corresponding implementation. 4. This means that the class contains concrete versions of all the methods described in the interface.CustomerAccount' does not implement interface member 'AccountManagement. we have now got something which can be regarded in two ways: as a CustomerAccount (because that is what it is) as an IAccount (because that is what it can do) People do this all the time.amount . so that it can be thought of as an account component. } } The code above does not look that different from the previous account class.PayInFunds(decimal)' In this case I missed out the PayInFunds method and the compiler complained accordingly. If a class implements an interface it is saying that for every method described in the interface. The highlighted part of the line above is where the programmer tells the compiler that this class implements the IAccount interface..3 Implementing an Interface in C# Interfaces become interesting when we make a class implement them. } public void PayInFunds ( decimal amount ) { balance = balance + amount .4 References to Interfaces Once we have made the CustomerAccount class compile. } balance = balance . I am going to create a class which implements the interface. In the case of the bank account.. return true.8. And you can use the same methods with any other lecturer (i.(the set of account abilities) rather than CustomerAccount (a particular account class). } public decimal GetBalance () { return balance. From the point of view of the university. rather than Rob Miles the individual. return true. It turns out that this is quite easy: IAccount account = new CustomerAccount(). this means that we want to deal with objects in terms of IAccount. and if it does. rather than the particular type that they are. person who implements that interface).amount .e.Creating Solutions From Object to Component Rob Miles the individual (because that is who I am) A university lecturer (because that is what I can do) If you think of me as a lecturer you would be using the interface that contains methods like GiveLecture. So. but they behave slightly differently because we want all withdrawals of over ten pounds to fail: public class BabyAccount : IAccount { private decimal balance = 0. account. contains the required methods). merely a large number of people who can be referred to as having that particular ability or role. The compiler will check to make sure that CustomerAccount does this. In C# terms this means that we need to be able to create reference variables which refer to objects in terms of interfaces they implement. the compilation is successful. I can create a BabyAccount class which implements the IAccount interface. } if (balance < amount) { return false . The account variable is allowed to refer to objects which implement the IAccount interface. and starting to think about them in terms of what they can do. } } C# Programming © Rob Miles 2010 107 .5 Using interfaces Now that we have our system designed with interfaces it is much easier to extend it. It is simply a way that we can refer to something which has that ability (i. In the case of our bank.PayInFunds(50). Note that there will never be an instance of IAccount interface. which has to manage a large number of interchangeable lecturers. it is much more useful for it to think of me as a lecturer. public bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false . } public void PayInFunds ( decimal amount ) { balance = balance + amount . There is no such physical thing as a "lecturer". 4.e. This is the same in real life. } balance = balance . This implements all the required methods.8. with interfaces we are moving away from considering classes in terms of what they are. When we create the account objects we just have ask if a standard account or a baby account is required. what I really want is a way that I can regard an object in terms of its ability to print.. However. Each of these items will be implemented in terms of a component which provides a particular interface (IWarning.7 Designing with Interfaces If you apply the "abstraction" technique properly you should end up with a system creation process which goes along the lines of: gather as much metadata as you can about the problem. public class BabyAccount : IAccount. You should also have spotted that interfaces are good things to hang tests on. Each interface is a new way in which it can be referred to and accessed. for example warning letters.. IPrintToPaper { . The field of Software Engineering is entirely based on this process. There are also graphical tools that you can use to draw formal diagrams to represent this information. The IAccount interface lets me regard a component purely in terms of its ability to behave as a bank account. If you have a set of fundamental behaviours that all bank accounts must have (for example C# Programming © Rob Miles 2010 108 . For example.Creating Solutions From Object to Component The nice thing about this is that as it is a component we don’t have to change all the classes which use it. before you write any code at all.8.8. I don't want to have to provide a print method in each of these. but using the new kind of account in our existing system is very easy. This is actually very easy. This means that a BabyAccount instance behaves like an account and it also contains a DoPrint method which can be used to make it print out. I create the interface: public interface IPrintToPaper { void DoPrint (). 4. I may want to regard a component in a variety of ways. 4. The rest of the system can then pick up this object and use it without caring exactly what it is. ISpecialOffer for example). This would be reasonable if all I ever wanted to print was bank accounts. special offers and the like.. the bank will want the account to be able to print itself out on paper. what is important to the customer. so that we can make sure that withdrawals of more than ten pounds do fail. However. You might think that all I have to do is add a print method to the IAccount interface. } Now anything which implements the IPrintToPaper interface will contain the DoPrint method and can be thought of in terms of its ability to print. there will be lots of things which need to be printed. We will of course have to create some tests especially for it. A class can implement as many interfaces as it needs.6 Implementing Multiple Interfaces A component can implement as many interfaces as are required. The design of the interfaces in a system is just this. Each GUID is unique in the world. interface IAccount { int GetAccountNumber (). This is a very important value. in that it will be fixed for the life of the account and can never be changed. No two accounts should ever have the same number. These are data items which are created based on the date. So this requirement ends up being expressed in the interface that is implemented by the account class. We don't care what the method GetAccountNumber actually does. Nothing in C# allows you to enforce a particular behaviour on a method. we sometimes use this to good effect when building a program. The interface mechanism gives us a great deal of flexibility when making our components and fitting them together. For example. the manager has told us that each bank account must have an account number. Inheritance lets a class pick up behaviours from the class which is its parent. In fact. } This method returns the integer which is the account number for this instance. has resulted in the creation of a set of methods in the C# libraries to create things called Globally Unique Identifiers or GUIDs. which really need to be unique in the world. in that we can create "dummy" components which implement the interface but don't have the behaviour as such. It is a way that we can pick up behaviours from classes and just modify the bits we need to make new ones. it just means that a method with that name exists within the class. If a class is descended from a particular parent class this C# Programming © Rob Miles 2010 109 .9 Inheritance Inheritance is another way we can implement creative laziness.Creating Solutions Inheritance paying in money must always make the account balance go up) then you can write tests that bind to the IAccount interface and can be used to test any of the bank components that are created. that is down to how much you trust the programmer that made the class that you are using. Once we have set out an interface for a component we can then just think in terms of what the component must do. and how good your tests are. From the point of view of interface design this means that the account number will be set when the account is created and the account class will provide a method to let us get the value (but there will not be a method to set the account number). It can also be used at the design stage of a program if you have a set of related objects that you wish to create. This is the real detail in the specification. Just because a class has a method called PayInFunds does not mean that it will pay money into the account. but we have not actually described how this should be done. They state that we have a need for behaviours. By placing it in the interface we can say that the account must deliver this value. The need for things like account numbers. It means that once we have found out what our bank account class needs to hold for us we can then go on to consider what we are going to ask the accounts to do. as long as it always returns the value for a particular account. In this respect you can regard it as a mechanism for what is called code reuse. We could use these in our Account constructor to create a GUID which allows each account to have a unique number. and more a promise. Programmer’s Point: Interfaces are just promises An interface is less of a binding contract. I have to add comments to give more detail about what the method does. but they do not necessarily state how they are made to work. time and certain information about the host computer. not precisely how it does it. 4. You can regard an interface as a statement by a class that it has a set of behaviours because it implements a given interface. Baby accounts are only allowed to draw up to 10 pounds out at a time.e. It turns out that we can do this in C# using inheritance.1 Extending a parent class We can see an example of a use for inheritance in our bank account project. but not all. and only once. This means that the PayInFunds method from the CustomerAccount class is used at this point. Try not to do this. We have solved this problem from a design point of view by using interfaces. I can now write code like: BabyAccount b = new BabyAccount(). they implement the interface). We can even create brand new accounts at any time after the system has been deployed.IAccount { } The key thing here is the highlighted part after the class name. but not exactly the same.PayInFunds(50). it gets everything from its parent. make it a method. But this does make things a bit tiresome when we write the program. You might think that after such a huge number of years in the job I get everything right every time. instances of the BabyAccount class have abilities which they pick up from their parent class. b. BabyAccount can do. the parent class does. although BabyAccount does not have a PayInFunds method. So. Then I change most. What we really want to do is pick up all the behaviours in the CustomerAccount and then just change the one method that needs to behave differently. In fact. A great programmer writes every piece of code once. We need to create a BabyAccount class which contains a lot of code which is duplicated in the CustomerAccount class.Creating Solutions Inheritance means that it has a set of behaviours because it has inherited them from its parent. Wrong. In short: Interface: "I can do these things because I have told you I can" Inheritance: "I can do these things because my parent can" 4. Customer accounts can draw out as much as they want. I write some code and find that I need something similar. in another part of the program. So I use block copy. And a lot of the mistakes that I make are caused by improper use of block copy. "This is not a problem" you probably think "I can use the editor block copy to move the program text across". the BabyAccount class has no behaviours of its own. of the new code and find that my program doesn't work properly.9. This means that everything that CustomerAccount can do. When I create the BabyAccount class I can tell the compiler that it is based on the CustomerAccount one: public class BabyAccount : CustomerAccount. These can be introduced and work alongside the others because they behave correctly (i. C# Programming © Rob Miles 2010 110 . But: Programmer’s Point: Block Copy is Evil I still make mistakes when I write programs. I have put the name of the class that BabyAccount is extending. This works because. We have already noted that a BabyAccount must behave just like a CustomerAccount except in respect of the cash withdrawal method. By separating the thing that does the job from the description of the job (which is what an interface lets you do) we can get the whole banking system thinking in terms of IAccount and then plug in accounts with different behaviours as required. at the moment. If you need to use it in more than one place. This means that code like: BabyAccount b = new BabyAccount(). public class CustomerAccount : IAccount { private decimal balance = 0. b.9. return true. The call of PayInFunds will use the method in the parent (since that has not been overridden) but the call of WithdrawFunds will use the method in BabyAccount. This is called overriding a method. } } The keyword virtual means ―I might want to make another version of this method in a child class‖. The next thing we need to be able to do is change the behaviour of the one method that we are interested in. C# Programming © Rob Miles 2010 111 . you definitely can’t. The C# compiler needs to know if a method is going to be overridden.WithdrawFunds(5). To make the overriding work correctly I have to change my declaration of the method in the CustomerAccount class. You don’t have to override the method. } } The keyword override means "use this version of the method in preference to the one in the parent".PayInFunds(50). This is because it must call an overridden method in a slightly different way from a "normal" one. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . Virtual Methods Actually.Creating Solutions Inheritance 4. but if you don’t have the word present. } if (balance < amount) { return false .amount . In other words. } balance = balance .amount . In the BabyAccount class I can do it like this: public class BabyAccount : CustomerAccount. return true.2 Overriding methods We now know that we can make a new class based on an existing one.IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . We want to replace the WithdrawFunds method with a new one. the above code won't compile properly because the compiler has not been told that WithDrawFunds might be overridden in classes which are children of the parent class. b. there is one other thing that we need to do in order for the overriding to work. } balance = balance . 4. Fortunately the designers of C# have thought of this and have provided a way that you can call the base method from one which overrides it..3 Using the base method Remember that programmers are essentially lazy people who try to write code only once for a given problem. We carefully made it private so that methods in other classes can’t get hold of the value and change it directly. You use virtual to mark a method as able to be overridden and override to actually provide a replacement for the method. it looks as if we are breaking our own rules here. in that it stops the BabyAccount class from being able to change the value. in that it means that the balance value has to be made more exposed that we might like. In other words. Well. this protection is too strict. } I’m not terribly happy about doing this. It also has access to all the protected members of the classes above it.9. public class CustomerAccount : IAccount { protected decimal balance = 0. A class hierarchy is a bit like a family tree. This makes the member visible to classes which extend the parent. This calls for more metadata to be gathered from the customer and used to decide which parts of the behaviour need to be changed during the lift of the project.. We have already noted that we don’t like this much. for now making this change will make the program work. And we would have written this down in the specification. Of course this should be planned and managed at the design stage. This is because the balance value in the CustomerAccount class is private. I can use this to make the WithDrawFunds method in my BabyAccount much simpler: C# Programming © Rob Miles 2010 112 . Bank Notes: Overriding for Fun and Profit The ability to override a method is very powerful. However. methods in the BabyAccount class can see and use a protected member because they are in the same class hierarchy as the class containing the member. in that the WithDrawFunds method in the BabyAccount class contains all the code of the method in the parent class. Protection of data in class hierarchies It turns out that the code above still won’t work. Every class has a parent and can do all the things that the parent can do. the balance is very important to me and I’d rather that nobody outside the CustomerAccount class could see it. Later we will see better ways to manage this situation. It means that we can make more general classes (for example the CustomerAccount) and customise it to make them more specific (for example the BabyAccount)... We would have made the WithDrawFunds method virtual because the manager would have said ―We like to be able to customise the way that some accounts withdraw funds‖. To get around this problem C# provides a slightly less restrictive access level called protected. .Creating Solutions Inheritance This makes override and virtual a kind of matched pair. The word base in this context means ―a reference to the thing which has been overridden‖. However. This is because in this situation there is no overriding. and then it is fixed for all the classes which call back to it. If I leave it out (and leave out the override too) the program seems to work fine. This makes it more difficult to pick up behaviours from parent classes. It is important that you understand what I’m doing here. } } The problem with this way of working is that you are unable to use base. C# Programming © Rob Miles 2010 113 . } return base. the one that the method overrides. in the top level class. By making this change I can put the balance back to private in the CustomerAccount because it is not changed outside it. If you play around with C# you will find out that you don’t actually seem to need the virtual keyword to override a method.e.WithdrawFunds(amount). IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . The use of the word base to call the overridden method solves both of these problems rather beautifully.4 Making a Replacement Method This bit is rather painful.amount . but don’t worry too much since it actually does make sense when you think about it. and why I’m doing it: I don’t want to have to write the same code twice I don’t want to make the balance value visible outside the CustomerAccount class. return true. i.Creating Solutions Inheritance public class BabyAccount : CustomerAccount. If I need to fix a bug in the behaviour of the WithDrawFunds method I just fix it once.IAccount { public new bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . } } The very last line of the WithDrawFunds method makes a call to the original WithDrawFunds method in the parent class. Note that there are other useful spin-offs here. } balance = balance . 4. you have just supplied a new version of the method (in fact the C# compiler will give you a warning which indicates that you should provide the keyword new to indicate this): public class BabyAccount : CustomerAccount. } if (balance < amount) { return false .9. Because the method call returns a bool result I can just send whatever it delivers. This goes well with a design process which means that as you move down the ―family tree‖ of classes you get more and more specific. the customer will not have particularly strong opinions on how you use things like sealed in your programs.. In fact. It means that a programmer can just change one tiny part of a class and make a new one with all the behaviours of the parent. 4. If you want to have a policy of allowing programmers to make custom versions of classes in this way it is much more sensible to make use of overriding since this allows a well-managed way of using the method that you over-rid.9.5 Stopping Overriding Overriding is very powerful. For a programming course at this level it is probably a bit heavy handed of me to labour this point just right now. No matter how much cash is drawn out.Creating Solutions Inheritance Programmer’s Point: Don’t Replace Methods I am very against replacing methods rather than overriding them.e.. Bank Notes: Protect Your Code As far as the bank application is concerned. it always returns a balance value of a million pounds! A naughty programmer could insert this into a class and give himself a nice spending spree. One of the unfortunate things about this business is that you will have to allow for the fact that people who use your components might not all be nice and trustworthy.IAccount { . What this means is that we need a way to mark some methods as not being able to be overridden. This means that the class cannot be extended.. } This is the banking equivalent of the bottle of beer that is never empty. C# does this by giving us a sealed keyword which means ―You can’t override this method any more‖. I’m wondering why I mentioned this at all. public sealed class BabyAccount : CustomerAccount. However. it cannot be used as the basis for another class. This is never going to need a replacement. The rules are that you can only seal an overriding method (which means that we can’t seal the GetBalance virtual method in the CustomerAccount class) and you can still replace a sealed method.. is that you can mark a class as sealed. Consider the GetBalance method. This means that you should take steps when you design the program to decide whether or not methods should be flagged as virtual and also make sure that you seal things when you can do so. i. Unfortunately this is rather hard to use. C# Programming © Rob Miles 2010 114 . which has a bit more potential. overriding/replacing is not always desirable. And yet a naughty programmer could write their own and override or replace the one in the parent: public new decimal GetBalance () { return 1000000. } The compiler will now stop the BabyAccount from being used as the basis of another account. just remember that when you create a program this is another risk that you will have to consider. Another use for sealed. But they will want to have confidence in the code that you make. and if it didn’t all make sense there is no particular need to worry.. I can use it to force a set of behaviours on items in a class hierarchy. This C# Programming © Rob Miles 2010 115 . balance = inBalance. They must make sure that at each level in the creation process a constructor is called to set up the class at that level. I think of these things as a bit like the girders that you erect to hold the floors and roof of a large building. The result of this is that programmers must take care of the issue of constructor chaining.9. the first a string and the second a decimal value. Constructor Chaining When considering constructors and class hierarchies you must therefore remember that to create an instance of a child class an instance of the parent must first be created. In other words. "Hull"). the proper version of the customer account constructor is as follows: public CustomerAccount (string inName. The keyword base is used to make a call to the parent constructor.6 Constructors and Hierarchies A constructor is a method which gets control during the process of object creation. to create a CustomerAccount you must first create an Account. It is used by a programmer to allow initial values to be set into an object: robsAccount = new CustomerAccount("Rob Miles". In this situation the constructor in the child class will have to call a particular constructor in the parent to set that up before it is created.Creating Solutions Inheritance 4. 4.9. However. inBalance) { } The base keyword is used in the same way as this is used to call another constructor in the same class. decimal inBalance) { name = inName. This means that a constructor in the parent must run before the constructor in the child. For example. It is of course very important that you have these designs written down and readily available to the development team. It is part of the overall architecture of the system that you are building. The code above will only work if the CustomerAccount class has a constructor which accepts two strings. In other words. it is also possible to use overriding in a slightly different context. In other words. They tell programmers who are going to build the components which are going to implement the solution how to create those components. You might think that I could solve this by writing a constructor a bit like this: public CustomerAccount (string inName. the name and the address of the new customer.7 Abstract methods and classes At the moment we are using overriding to modify the behaviour of an existing parent method. in the context of the bank application we might want to provide a method which creates a warning letter to the customer that their account is overdrawn. Programmer’s Point: Design your class construction process The means by which your class instances are created is something you should design into the system that you build. decimal inBalance) : base ( inName. The constructor above assumes that the Account class which CustomerAccount is a child of has a constructor which accepts two parameters. } But this class is an extension of the Account class. And the account is the class which will have a constructor which sets the name and the initial balance. to make a CustomerAccount I have to make an Account. If there are some things that an account must do then we can make these abstract and then get the child classes to actually provide the implementation. This can be useful because it means you don’t have to repeatedly implement the same methods in each of the components that implement a particular interface. The methods in the second category must be made abstract. This is true.. so you can only pick up the behaviours of one class. It is not possible to make an instance of an abstract class. This means that at the time we create the bank account system we know that we need this method. We could just provide a ―standard‖ method in the CustomerAccount class and then rely on the programmers overriding this with a more specific message but we then have no way of making sure that they really do provide the method. If you want to make an instance of a class based on an abstract parent you must provide implementations of all the abstract methods given in the parent. This leads us to a class design a bit like this: C# Programming © Rob Miles 2010 116 . you may have to repeat methods as well. The problem is that you can only inherit from one parent. abstract classes are different in that they can contain fully implemented methods alongside the abstract ones. This means that the method body is not provided in this class. An instance of Account would not know what to do it the RudeLetterString method was ever called. but we don’t know precisely what it does in every situation. Abstract classes and interfaces You might decide that an abstract class looks a lot like an interface. An abstract class can be thought of as a kind of template.. in that an interface also provides a ―shopping list‖ of methods which must be provided by a class. } The fact that my new Account class contains an abstract method means that the class itself is abstract (and must be marked as such). C# provides a way of flagging a method as abstract. If you want to implement interfaces as well. If you think about it this is sensible. Perhaps at this point a more fully worked example might help. public abstract string RudeLetterString(). } public virtual decimal GetBalance () { return balance. decimal GetBalance (). public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . } balance = balance . } } public class BabyAccount : Account { public override bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false .Creating Solutions Inheritance public interface IAccount { void PayInFunds ( decimal amount ). string RudeLetterString(). } public override string RudeLetterString() { return "Tell daddy you are overdrawn". } public abstract class Account : IAccount { private decimal balance = 0. } public void PayInFunds ( decimal amount ) { balance = balance + amount . } } C# Programming © Rob Miles 2010 117 .WithdrawFunds(amount). bool WithdrawFunds ( decimal amount ). } return base. } } public class CustomerAccount : Account { public override string RudeLetterString() { return "You are overdrawn" .amount . return true. for example all the different kinds of bank account you might need to deal with. This might seem useful. 4. current account etc. However.8 Designing with Objects and Components For the purpose of this part of the text you now have broad knowledge of all the tools that can be used to design large software systems. Then I have added customised methods into the child classes where appropriate. methods) which a component can be made to implement.9. Note how I have moved all the things that all accounts must do into the parent Account class. A concrete example of this would be something like IPrintHardCopy. If their accounts are software components too (and they should be) then all we have to do is implement the required interfaces at each end and then our systems understand each other. as we can consider something as an ―account‖ rather than a BabyAccount. then the best way to do this is to set up a parent class which contains abstract and non-abstract methods. Use Interface References One important consideration is that even if you make use of an abstract parent class I reckon that you should still make use of interfaces to reference the data objects themselves. get their account objects (whatever they are called) to implement the interface and. This gives you a degree of flexibility that you can use to good effect. hey presto. Interfaces let me describe a set of behaviours which a component can implement. allowing them to present different faces to the systems that use them. The child classes can make use of the methods from the parent and override the ones that need to be provided differently for that particular class. Abstract: lets you create a parent class which holds template information for all the classes which extend it. Broadly: Interface: lets you identify a set of behaviours (i. deposit account. If you want to create a related set of items. References to abstract classes References to abstract classes work just like references to interfaces. That is because. even though I now have this abstract structure I still want to think of the account objects in terms of their ―accountness‖ rather than any particular specific type. including credit card. Bank Notes: Making good use of interface and abstract If our bank takes over another bank and wants to share account information we might need a way to use their accounts. In other words the other bank must create the methods in the IAccount interface. This would be much more difficult if my entire system thought in terms of a parent Account class – since their classes would not fit into this hierarchy at all. Objects can implement more than one interface. I much prefer it if you manage references to abstract things (like accounts) in terms of their interface instead.Creating Solutions Inheritance This code repays careful study. Then our printer can just regard each of the instances that implement this interface purely in this way. If you have an understanding of what an interface and abstract classes are intended to achieve this will stand you in very good stead for your programming career. A reference to an Account class can refer to any class which extends from that parent.e. I can now use their accounts. Lots of items in my bank system will need to do this and so we could put the behaviour details into the interface for them to implement in their own way. Once a component can implement an interface it can be regarded purely in terms of a component with this ability. C# Programming © Rob Miles 2010 118 . Note also though that I have left the interface in place. Any component which implements the interface can be thought of in terms of a reference of that interface type. 9. issues that relate to how we use objects in our programs. If I write the code: int i = 99.this is equivalent to writing: public class Account : object { The object class is a part of C#. In other words. It is in fact a child of the object class. This has a couple of important ramifications: Every object can do what an object can do. (in fact we have seen that the whole basis of building programs is to decide what the objects should do and then make them do these things). in that we know how they can be used to design and implement large software systems.9 Don’t Panic This is all deep stuff. Now it is time to find out how this is achieved.Creating Solutions Object Etiquette 4. We have also seen that you can extend a parent object to create a child which has all the abilities of the parent. Interfaces let me describe what each component can do.10 Object Etiquette We have considered objects "in the large".1 Objects and ToString We have taken it as read that objects have a magical ability to print themselves out. The important point to bear in mind is that the features are all provided so that you can solve one problem: Create software which is packaged in secure. 4.10. These features of C# are tied up with the process of software design which is a very complex business. What we need to do now is take a look at some smaller. Now we are going to see how these abilities of objects are used in making parts of the C# implementation itself work. interchangeable components. and also how we can give our own objects the same magical ability. don’t worry. C# Programming © Rob Miles 2010 119 . It turns out that this is all provided by the "objectness" of things in C#. We know that an object can contain information and do things for us. The Object class When you create a new class this is not actually created from nowhere. This will print out: 99 The integer somehow seems to know how to print itself out. if I write: public class Account { . A reference to an object type can refer to any class. and everything is a child of the object class. plus the new ones that we add. Console. but very important. 4. If you don’t get it now. And that is it. Class hierarchies let me re-use code inside those components.WriteLine(i). the object.WriteLine(o. } C# Programming © Rob Miles 2010 120 . . 25). whenever you design a class you should provide a ToString method which provides a text version of the content of that class. public override string ToString() { return "Name: " + name + " balance: " + balance.WriteLine(a).would print out: Name: Rob balance: 25 So. } } In the tiny Account class above I've overridden the ToString method so that it prints out the name and balance value. the first point is the one which has the most importance here. Console.WriteLine(o).would print out: System. . This means that we can override it to make it behave how we would like: class Account { private string name. The ToString method The system knows that ToString exists for every object. Console. In other words: object o = new object(). and so if it ever needs the string version of an object it will call this method on the object to get the text.Creating Solutions Object Etiquette For the purpose of this part of the notes. you can use the base mechanism to do this. decimal inBalance) { name = inName. This means that the code: Account a = new Account("Rob". Getting the string description of a parent object If you want to get hold of a string description of the parent object. If you look inside the actual code that makes an object work you will find a method called ToString. The nice thing about ToString is that it has been declared virtual. from the point of view of good etiquette.and the results would be exactly the same. } public Account (string inName. private decimal balance. The object implementation of ToString returns a string description of the type of that object.ToString() + " Parent : " + parentName. .ToString()). This is sometimes useful if you add some data to a child class and want to print out the content of the parent first: public override string ToString() { return base.Object You can call the method explicitly if you like: Console. It means that all classes that are made have a number of behaviours that they inherit from their ultimate parent. balance = inBalance. y = 2. We know that objects are managed by named tags which refer to unnamed items held in memory somewhere.Creating Solutions Object Etiquette The method above is from a ChildAccount class. which means that the equals test will fail. 4. This is because I'm not that concerned about protecting them. The nice thing about this is that if the behaviour of the parent class changes. We can express this position as a coordinate or point. } This is my point class. Even though I have put the spaceship and the missile at the same place on the screen the word Bang is not printed.y = 2. with an x value and a y value. We then might want to test to see if two items have collided. I can now create instances of Point and use them to manage my game objects: Point spaceshipPosition = new Point(). spaceshipPosition.e. The code above uses the ToString method in the parent object and then tacks the name of the parent on the end before returning it. To do this we must override the standard Equals behaviour and add one of our own: C# Programming © Rob Miles 2010 121 . missilePosition.x = 1. take a look at the test that is being performed. the ChildAccount class does not have to change. This class extends the CustomerAccont and holds the name of the child's parent. i. class Point { public int x. When we perform an equals test the system simply checks to see if both references refer to the same location.2 Objects and testing for equals We have seen that when object references are compared a test for equals does not mean the same as it does for values. Programmer’s Point: Make sure you use the right equals As a programmer I must remember that when I'm comparing objects to see if they contain the same data I need to use the Equals method rather than the == operator. spaceshipPosition. they are not located at the same address in memory. This is because although the two Point objects hold the same data. since it will just make use of the upgraded method. In the game the various objects in it will be located at a particular place on the screen. If you find that things that contain the same data are not being compared correctly.WriteLine("Bang"). if ( spaceshipPosition == missilePosition ) { Console.x = 1. Point missilePosition = new Point().10. new members are added or the format of the string changes. To see how this might cause us problems we need to consider how we would implement a graphical computer game (makes a change from the bank for a while). public int y. Some of the nastiest bugs that I've had to fix have revolved around programmers who have forgotten which test to use. but I do want my program to run quickly. missilePosition. The problem is that the above program code does not work. Adding your own Equals method The way that you solve this problem is to provide a method which can be used to compare the two points and see if they refer to the same place. } Note that I've made the x and y members of the Point class public. there is a very good reason why you might find an equals behaviour very useful. If the bank ever contains two identical accounts this would cause serious problems. If they are both the same the method returns true to the caller. However. why should I waste time writing code to compare them in this way?” However. if ( ( p. Bank Notes: Good Manners are a Good Idea It is considered good manners to provide the Equals and ToString methods in the classes that you create. This means that I can write code like: if ( missilePosition. It is also very useful to make appropriate use of this when writing methods in classes. We need to do this because we want to get hold of the x and y values from a Point (we can't get them from an object). Note that this reference is supplied as a reference to an object. You will expect all programmers to write to these standards if they take part in the project.WriteLine("Bang").. The object is cast into a Point and then the x and y values are compared. In fact.x == x ) && ( p. When you start to create your bank account management system you should arrange a meeting of all the programmers involved and make them aware that you will be insisting on good mannered development like this. C# Programming © Rob Miles 2010 122 . for a professional approach you should set out standards which establish which of these methods you are going to provide. Programmer’s Point: Equals behaviours are important for testing The customer for our bank account management program is very keen that every single bank account that is created is unique. These will allow your classes to fit in with others in the C# system. } } The Equals method is given a reference to the thing to be compared. } else { return false. the Equals method is sometimes used by C# library methods to see if two objects contain the same data and so overriding Equals makes my class behave correctly as far as they are concerned.Creating Solutions Object Etiquette public override bool Equals(object obj) { Point p = (Point) obj. The first thing we need to do is create a reference to a Point. The fact that everything in the system is required to be unique might lead you to think that there is no need to provide a way to compare two Account instances for equality. In this situation an equals behaviour is important. Note that I didn't actually need to override the Equals method. } This test will work. and so I reckon you should always provide one.y == y ) ) { return true. because the Equals method actually compares the content of the two points rather than just their references.Equals(spaceshipPosition) ) { Console. I could have written one called TheSame which did the job. Each time the Count method is called the counter is made one larger. then don't worry about it for now.Creating Solutions Object Etiquette 4. In other words. } } We can add a this. Consider: public class Counter { public int Data=0. I can use the class as follows: Counter c = new Counter(). (dot) means "follow the reference to the object and then use this member of the class". If I have a member of my class which contains methods. Perhaps the best way to get around the problem is to remember that when I use the word this I mean "a reference to the currently executing instance of a class". the "proper" version of the Counter class is as follows: public class Counter { public int Data=0. Console. this as a reference to the current instance I hate explaining this. Confusion with this I reckon that using this is a good idea. in front of each use of a member of the class. I end up writing code like this: C# Programming © Rob Miles 2010 123 . public void Count () { this.Count(). in this situation we are not passing an account into the bank.Data + 1. A new bank account could add store itself in a bank by passing a reference to itself to a method that will store it: bank.WriteLine("Count : " + c. If this hurts your head. Passing a reference to yourself to other classes Another use for this is when an instance class needs to provide a reference to itself to another class that wants to use it.Data = this.Store(this). Of course. instead we are passing a reference to the account. The data is a counter. When a method in a class accesses a member variable the compiler automatically puts a this. When the Store method is called it is given a reference to the currently executing account instance. and I want to use one of those methods.Data). This calls the method and then prints out the data. if we like to make it explicit that we are using a member of a class rather than a local variable. public void Count () { Data = Data + 1. The Store method accepts this and then stores this somehow.3 Objects and this By now you should be used to the idea that we can use a reference to an object to get hold of the members of that object. } } The class above has a single data member and a single method member. However it might take a bit of getting used to. We know that in this context the . I want to use the word this to mean this. but this also has a special meaning within your C# programs.10. It means that people reading my code can tell instantly whether I am using a local variable or a member of the class. c. 4. You can sort out the case of the text. never allowing a thing to be changed by making a new one each time it is required. You might ask the question: "Why go to all the trouble?" It might seem all this hassle could be saved by just making strings into value types. It is very important that you understand what happens when you transform a string. Consider the situation where you are storing a large document in the memory of the computer. trim spaces off the start and end and extract sub-strings using these methods. So. This saves memory and it also makes searching for words much faster.Creating Solutions The power of strings and chars this. take a look at section 4. A string can be regarded as either an object (referred to by means of a reference) or a value (referred to as a value). The thing that s1 is referring to is unchanged. C# Programming © Rob Miles 2010 124 . The methods will return a new string. because C# regards an instance of a string type in a special way. 4. 4. This hybrid behaviour is provided because it makes things easier for us programmers. In other words. However it does mean that we have to regard strings as a bit special when you are learning to program. It calls it immutable. If you think you know about objects and references.1. after the assignment s1 and s2 no longer refer to the same object. This is because. To find out more about this.WriteLine(s1 + " " + s2). This is because it gives you a lot of nice extra features which will save you a lot of work. This is because programmers want strings to behave a bit like values in this respect. when the system sees the line: s2 = "different". although strings are objects. . is how the system implements immutable. These are exposed as methods which you can call on a string reference.2 Immutable strings The idea is that if you try to change a string.11. no. s2 = "different". string s2=s1. A bat can be regarded as either an animal or a bird in many respects.SetName("Rob"). This behaviour. string s1="Rob".4. This means "I have a member variable in this class called account. so changing s2 should change the object that s1 refers to as well.it makes a new string which contains the text "different" and makes s2 refer to that.account. you should be expecting s1 to change when s2 is changed.11 The power of strings and chars It is probably worth spending a few moments considering the string type in a bit more detail. Well. transformed in the way that you ask. By using references we only actually need one string instance with the word ―the‖ in it. they don't actually behave like objects all the time. This does not happen though.11. I regard them as a bit like bats. the C# system instead creates a new string and makes the reference you are "changing" refer to the changed one. Call the SetName method on that member to set the name to 'Rob'". The second statement made the reference s2 refer to the same object as s1. Console. All the occurrences in the text can just refer to that one instance.1 String Manipulation Strings are rather special. because they seem to break some of the rules that we have learnt. Substring(2).Length). } If s1 and s2 were proper reference types this comparison would only work if they referred to the same object.WriteLine ( "Length: " + s1. .WriteLine("Still the same"). s1=s1. In this respect strings are just like arrays. The Length property gives the number of characters in the string.Creating Solutions The power of strings and chars 4.5 String Length All of the above operations will fail if you try to do something which takes you beyond the length of the string. . 4. You can leave out the second parameter if you like. You do this by calling methods on the reference to get the result that you want: s1=s1.6 Character case Objects of type string can be asked to create new.11.11. you can't change the characters: name[0] = 'R'. in which case all the characters up to the end of the string are copied: string s1="Miles".3 String Comparison The special nature of strings also means that you can compare strings using equals and get the behaviour you want: if ( s1 == s2 ) { Console.Equals(s2) ) { Console.11. modified. versions of themselves in slightly different forms. But in C# the comparison works if they contain the same text.would cause a compilation error because strings are immutable. You can pull a sequence of characters out of a string using the SubString method: string s1="Rob".would leave "les" in s1. C# Programming © Rob Miles 2010 125 .11.WriteLine("The same").(remember that strings are indexed starting at location 0).4 String Editing You can read individual characters from a string by indexing them as you would an array: char firstCh = name[0]. You can use an equals method if you prefer: if ( s1.Substring(1. However. } 4. 4. s1=s1. It is also possible to use the same methods on them to find out how long they are: Console.2).ToUpper(). This would set the character variable firstCh to the first character in the string. This would leave the string "ob" in s1. The first parameter is the starting position and the second is the number of characters to be copied. The reason you are suffering is that strings are really design to hold strings. They are a bit like the switch keyword.IsDigit(ch) char. tab or newline You can use these when you are looking through a string for a particular character.IsLower(ch) char.Trim(). You should look this up if you have a need to do some proper editing. It works a lot like a string.11. which lets us select things easily. but C# provides them because they make programs slightly easier to write and simpler to read. These are static methods which are called on the character class and can be used to test characters in a variety of ways: char.IsUpper(ch) char. s1=s1. We don't need properties.7 Trimming and empty strings Another useful method is Trim. If you don't trim the text you will find equals tests for the name will fail. 4.11.9 String Twiddling with StringBuilder If you really want to twiddle with the contents of your strings you will find the fact that you can't assign to individual characters in the string a real pain. No other characters in the string are changed.11.Creating Solutions Properties The ToUpper method returns a version of the string with all the letters converted to UPPER CASE. 4. This is useful if your users might have typed " Rob " rather than "Rob". If you trim a string which contains only spaces you will end up with a string which contains no characters (i. but you can assign to characters and even replace one string with another.Text namespace.12 Properties Properties are useful.8 Character Commands The char class also exposes some very useful methods which can be used to check the values of individual characters. its length is zero). This removes any leading or trailing spaces from the string.IsLetter(ch) char. For proper string editing C# provides a class called StringBuilder. There are TrimStart and TrimEnd methods to just take off leading or trailing spaces if that is what you want.IsPunctuation(ch) char. C# Programming © Rob Miles 2010 126 . 4. It is also very easy to convert between StringBuilder instances and strings. There is a corresponding ToLower method as well. 4.IsLetterOrDigit(ch) char.e. not provide a way that they can be edited. It is found in the System. 4.2 Creating Get and Set methods To get control and do useful things we can create get and set methods which are public.GetAge() ). but we need to make the member value public. public int GetAge() { return this.WriteLine ( "Age is : " + s. The problem is that we have already decided that this is a bad way to manage our objects. the bank may ask us to keep track of staff members. Console. An age property for the StaffMember class would be created as follows: C# Programming © Rob Miles 2010 127 . } } } We now have complete control over our property. } public void SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this. but we have had to write lots of extra code. This is very naughty.age. s.12.12.3 Using Properties Properties are a way of making the management of data like this slightly easier.Age = -100210232. I can do it like this: public class StaffMember { public int Age. For example. s.age = inAge. We have seen that we can use a member variable to do this kind of thing. These provide access to the member in a managed way. just by giving the name of the member. There is nothing to stop things like: s. One of the items that they may want to hold is the age of a member of staff.12. } The class contains a public member.Creating Solutions Properties 4.1 Properties as class members A property is a member of a class that holds a value. We then make the Age member private and nobody can tamper with it: public class StaffMember { private int age.SetAge(21). I can access a public member of a class directly. 4. I can get hold of this member in the usual way: StaffMember s = new StaffMember().Age = 21. Programmer’s who want to work with the age value now have to call methods: StaffMember s = new StaffMember(). but because the Age member is public we cannot stop it. } } } The age value has now been created as a property. Console. They are packaged as a list of methods which a class must contain if it implements the interfaces. it returns the age in months. I can do other clever things too: public int AgeInMonths { get { return this.Age ). s. The really nice thing about properties is that they are used just as the class member was: StaffMember s = new StaffMember().ageValue*12. called AgeInMonths. This gives us all the advantages of the methods.Creating Solutions Properties public class StaffMember { private int ageValue. } } This is a new property. 4. since it does not provide a set behaviour. You do this by leaving out the statements which are the body of the get and set behaviours: interface IStaff { int Age { get.Age = 21. These equate directly to the bodies of the get and set methods that I wrote earlier.4 Properties and interfaces Interfaces are a way that you can bring together a set of behaviours. Write only properties are also possible if you leave out the get.12. When the Age property is given a value the set code is run. However.ageValue = value. public int Age { set { if ( (value > 0) && (value < 120) ) { this.ageValue. The keyword value means ―the thing that is being assigned‖. You can also provide read-only properties by leaving out the set behaviour. This means that you can provide several different ways of recovering the same value. It is also possible to add properties to interfaces. It can only be read. When the Age property is being read the get code is run. but they are much easier to use and create. } } C# Programming © Rob Miles 2010 128 . } } get { return this.WriteLine ( "Age is : " + s. Note how there are get and set parts to the property. set. based on the same source value as was used by the other property. but it has no way of telling the user of the property that this has happened. A SetAge method on the other hand could return a value which indicates whether or not it worked: public bool SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this. } C# Programming © Rob Miles 2010 129 . which is not a good way to go on. I suppose that it would be possible to combine a set method and a get property. This is OK. If there is a situation where a property assignment can fail I never expose that as a property.Creating Solutions Building a Bank This is an interface that specifies that classes which implement it must contain an Age property with both get and set behaviours. Properties Run Code When you assign a value to a property you are actually calling a method. But there are a few things that you need to be aware of when deciding whether or not to use them: Property Assignment Failure We have seen that the set behaviour can reject values if it thinks they are out of range. But it can also be made very confusing. What we now need is a way of storing a large number of accounts. This looks very innocent.13 Building a Bank We are now in a situation where we can create working bank accounts. but could result in a thousand lines of code running inside the set property. and they are used throughout the classes in the . This container class will provide methods which allow us to find a particular account based on the name of the holder. 4. With our Age property above the code: s.age = inAge. the person performing the assignment would not be aware of this.NET libraries. since there is no way that the property can return a value which indicates success or failure. However. We can express the behaviour that we need from our bank in terms of an interface: interface IBank { IAccount FindAccount (string name). Unfortunately there is no way you can tell that from the code which does the assignment: s. This gives us a way of creating new types of account as the bank business develops.Age = 121. . 4. It is possible to use this to advantage. We can use interfaces to define the behaviour of a bank account component. } A programmer setting the age value can now find out if the set worked or failed.would fail. but I reckon that would be madness. in that an object can react to and track property changes. bool StoreAccount (IAccount account). return true.Age = 99.12.5 Property problems Properties are really neat. The only way that a property set method could do this would be to throw and exception. } return false. they are all set to null. We never place an account "in" the array. The method to add an account to our bank has to find the first empty location in the array and set this to refer to the account that has been added: C# Programming © Rob Miles 2010 130 .Creating Solutions Building a Bank A class which implements these methods can be used for the storage of accounts. What we have created is an array of references. The light coloured elements are set to null. The element at the start of the array contains a reference to the account instance.1 Storing Accounts in an array The class ArrayBank is a bank account storage system which works using arrays. public ArrayBank( int bankSize ) { accounts = new IAccount[bankSize]. We have not created any accounts at all. When we add an account to the bank we simply make one of the references refer to that account instance. } Note that it is very important that you understand what has happened here. accounts Name : "Rob" Balance : 0 The diagram shows the state of the accounts array after we have stored our first account. instead we put a reference to that account in the array. printing out a message if the storage worked. IAccount account = new CustomerAccount("Rob". Each reference in the array can refer to an object which implements the IAccount interface. } The code above creates a bank and then puts an account into it.WriteLine ( "Account stored OK" ). if (friendlyBank. I can put an account into it and then get it back again: IBank friendlyBank = new ArrayBank (50). In the code above we are creating a bank with enough room for references to 50 accounts. But at the moment none of the references refer anywhere. 0). When you create an instance of an ArrayBank you tell it how many accounts you want to store by means of the constructor.13. The constructor creates an array of the appropriate size when it is called: private IAccount [] accounts . 4.StoreAccount(account)) { Console. } } return false.2 Searching and Performance The solution above will work fine. Each time we add a new account the searching gets slower as the FindAccount method must look through more and more items to find that one. If it finds one it sets this to refer to the account it has been asked to store and then returns true.13. On a bank with only fifty accounts this is not a problem. for (position=0 . C# Programming © Rob Miles 2010 131 . In the array based implementation of the bank this is achieved by means of a simple search: public IAccount FindAccount ( string name ) { int position=0 . If it finds an element which contains a null reference it skips past that onto the next one.GetName() == name ) { return accounts[position]. position++) { if (accounts[position] == null) { accounts[position] = account. otherwise it returns a reference to the account that it found. 4. } This code works its way through the accounts array looking for an entry with a name which matches the one being looked for. If it does not find a null element before it reaches the end of the array it returns false to indicate that the store has failed. position<accounts. it becomes very slow as the size of the bank increases.Length . 4. but if there are thousands of accounts this simple search will much to slow.13. } if ( accounts[position]. When we want to work on an account we must first find it.FindAccount("Rob"). for (position = 0. If it reaches the end of the array without finding a match it returns null. This will either return the account with the required name. } } return null. position++) { if ( accounts[position] == null ) { continue.3 Storing Accounts using a Hash Table Fortunately for us we can use a device called a "hash table" which allows us to easily find items based on a key This is much faster than a sequential search.Length. position<accounts. since it uses a technique which will take us straight to the required item. The bank interface provides a method called FindAccount which will find the account which matches a particular customer name: IAccount fetchedAccount = arrayBank. However.Creating Solutions Building a Bank public bool StoreAccount (IAccount account) { int position = 0. and could be used as the basis of a bank. } This method works through the array looking for an element containing null. return true. or null if the account cannot be found. C# Programming © Rob Miles 2010 132 .Add(account. look up the ASCII code for each letter and then add these values up. When we want to find a given item we use the hash to take us to the starting position for the search and then look for the one with the matching name. We want to return a reference to an instance which implements the IAccount interface. rather than always looking from the beginning of the array in our simple array based code above. we could take all the letters in the account name string. } } The Hashtable class can be found in the System. In short. It also allows you to use a reference to the key (in this case the name) to locate an item: return bankHashtable[name] as IAccount. The as operator has the advantage that if bankHashtable[name] does not return an account.GetName(). The as operator is a form of casting (where we force the compiler to regard an item as being of a particular type). return true. 4. We can do clever things with the way we combine the values to reduce the chances of this happening. the as operator will generate a null reference.4 Using the C# Hashtable collection Fortunately for us the designers of the C# have created a hash table class for us to use. at run time the bank hash table returns the wrong thing) our program will fail with an exception. Clashes can be resolved by adding a test when we are storing an account. If a cast fails (i. the hash function gives us a starting point for our search. or returns something of the wrong type. the name "Rpa" would give the same total (82+112+97) and refer to the same location.e. but we can't completely avoid clashes.Creating Solutions Building a Bank The idea is that we do something mathematical (called "hashing) to the information in the search property to generate a number which can then be used to identify the location where the data is stored. This is poetically referred to as a "hash clash". The name "Rob" could be converted to 82+111+98 = 291. If we find the location we would like to use is not null we simply work our way down looking for the first free location on from that point. Since this is just what the caller of our FindAccount method is expecting this can be returned back directly. } public bool StoreAccount(IAccount account) { bankHashtable. This will store items for us based on a particular object which is called the key. account). Of course this hash code is not foolproof. It provides a method called Add which is given the value of the key and a reference to the item to be stored on that hash code.Collections namespace. public IAccount FindAccount(string name) { return bankHashtable[name] as IAccount. For example. It turns out to be very easy to create a bank storage mechanism based on this: class HashBank : IBank { Hashtable bankHashtable = new Hashtable(). It is used in preference to the code: return (IAccount) bankHashtable[name].13. We could look in location 291 for our account. We have to use the "as" part of this coded as the collection will return a reference to an object. This greatly speeds up access to the data. which is the name of the account holder. and there may well be more than one. When gathering metadata about a system you will often need to consider which of the properties of an item will be key fields. In a real bank the key will be more complex. C# Programming © Rob Miles 2010 133 . Bank Notes: Key properties are important The action that is being performed here is exactly the same as what happens when you use your cash card to draw some money from the bank. In our simple bank we only have a single key. so that they can search for an account holder by name. address or account number depending on the information they have available. we can very easily change the way that the account storage part of the program works without changing anything else. The cash machine uses information on the card as a key to find your account record so that it can check your balance value and then update it when the money has been withdrawn.Creating Solutions Building a Bank It is interesting to note that because we have implemented our bank behaviour using an interface. because the array size was set at 10. C# Programming © Rob Miles 2010 134 . I think the root of Generics is probably "general". It lets us create something very useful. in that the idea of them is that you specify a general purpose operation and then apply it in different contexts in a way appropriate to each of them. at least amongst those who can't spell very well. although there are overloaded constructors that let you give this information and help the library code along a bit: ArrayList storeFifty = new ArrayList(50). Fortunately the C# libraries provide a number of solutions. They sound a bit scary. Creating an ArrayList It is very easy to create an ArrayList: ArrayList store = new ArrayList().001st customer to the bank is not actually a cause for celebration. but we aren't that keen on that because it means that for smaller banks the program might be wasting a lot of memory. but it can hold more or less as required.Advanced Programming Generics and Collections 5 Advanced Programming 5.1. in that it lives in the same Systems.Add(robsAccount). telling people you learned about "generics" probably conjures up images of people with white coats and test tubes. Perhaps the best way to talk about generics is to see how they can help us solve a problem for the bank. If it doesn't. not the thing itself. then it might be worth re-reading those bits of the book until they make sense. The class provides an Add method: Account robsAccount = new Account ().1 The ArrayList class The ArrayList is a cousin of the HashTable we have just seen. in that what it actually does is add a reference. where adding the 10. This statement probably doesn't tell you much about them or what they do. We are not putting an Account into the arraylist. starting with the simple ArrayList. This leads to a "straw that breaks the camel's back" problem. It is important to remember what is going on here. If this sounds a bit like abstraction and inheritance you are sort of on the right track. We have just seen that we can store Account references in an Array. But I digress. and some very clever code in the library makes sure that this works.000 and our program crashes. One way to solve this problem is to use a really big array. But we know that when an array is created the programmer must specify exactly how many elements it contains. Adding Items to an ArrayList Adding items to an ArrayList is also very easy. Note that you don't have to set the size of the ArrayList. In this respect the word Add can be a bit misleading. store. but it does indicate that they are very useful. we are instead making one element of the arraylist refer to that account. We can always add new elements to the ArrayList. The ArrayList called storeFifty is initially able to store 50 references.Collections namespace. 5.1 Generics and Collections Generics are very useful. an array that can grow in size. } C# Programming © Rob Miles 2010 135 . cast it into an Account class and then pay fifty pounds into it. This puts a reference to a KitchenSink instance into our bank storage. it is just no longer on that list. To get a properly typesafe Account storage we have to take a look at generics in detail a bit later.PayInFunds(50). a. it is not necessarily destroyed. It would be very nice if we could just get hold of the account from the arraylist and use it. if I ran the code above when store did not contain robsAccount) this does not cause an error. Unfortunately this won't work.WriteLine("The bank is empty"). If you think about it. You will no doubt remember from the discussion of object hierarchies that an object reference can refer to an instance of any class (since they are all derived from object) and so that is the only kind of reference that the arraylist works with.Remove(robsAccount). an item "in" an arraylist is never actually in it. It will have a list of all the customers. Account a = store[0]. If you remove an item the size of the arraylist is decreased. The designers of the ArrayList class had no idea precisely what type of object a programmer will want to use it with and so they had to use the object reference. This will cause problems (and an exception) if we ever try to use it as an Account. Note that if the reference given is not actually in the arraylist (i. So. This would get the element at the start of the arraylist.Add(k). If the store contained more than one reference to robsAccount then each of them could be removed individually. just like your name can appear on multiple lists in the real world. but with a tricky twist. This means that I can't be sure that an arraylist you give me has nothing other than accounts in it: KitchenSink k = new KitchenSink(). Accessing Items in an ArrayList Items in arraylists can be accessed in just the same way as array elements. Finding the size of an ArrayList You can use the property Count to find out how many items there are in the list: if (store. because a program can use a cast to change the type of the item the arraylist returns: Account a = (Account) store[0]. a.Count == 0) { Console. the list actually contains a reference to that item. If you write this code you will get a compilation error. store. Removing Items from an ArrayList It is not really possible to remove things from an array. When an item is removed from an arraylist. this is the only thing that it could hold.e. This is given a reference to the thing to be removed: store. This removes the first occurrence of the reference robsAccount from the store arraylist. along with a list of "special" customers and perhaps another list of those who owe it the most money. This is not actually a huge problem. The reason for this is that an arraylist holds a list of object references.Advanced Programming Generics and Collections Remember that it would be perfectly possible to have robsAccount in multiple arraylists. but the arraylist class provides a really useful Remove behaviour.PayInFunds(50). A slightly larger problem is that an arraylist is not typesafe. It might be that the bank has many lists of customers. It is newer than the ArrayList class. They also throw exceptions if you try to access elements that are not in the array. not any particular class.1. with the advantage that it is also typesafe. if (a. float or Account array the job that it does is exactly the same. that is not what the designers of C# did. the fundamental behaviours of arrays are always the same. Whether you have an int. the only problem that you have is that an arraylist will always hold references to objects. However. It does this by using references to objects. If you wish you can use arraylists in place of arrays and have the benefits of storage that will grow and shrink as you need it. To understand how it works you have to understand a bit of generics. ArrayLists and Arrays Arraylists and arrays look a lot the same. and because it is not quite as much a part of the language as an array is. You could of course write this behaviour yourself. but this can lead to programs which are dangerous. However. C# can make sure that an array always holds the appropriate type of values. They both let you store a large number of items and you can use subscripts (the values in square brackets) to get hold of elements from either. string. if you give me an ArrayList there is no way I can be sure that accounts are all it contains. but having it built into the class makes it much easier. there is just no way that you can take an Account reference and place it in element in an array of integers.WriteLine("Rob is in the bank").Advanced Programming Generics and Collections Checking to see if an ArrayList contains an item The final trick I'm going to mention (but there are lots more things an arraylist can do for you) is the Contains method. And because each array is declared as holding values of a particular type. Generics and Behaviours If you think about it. so that it because as much a part of C# as the array is. Instead they introduced a new language feature. If you give me an array of Accounts I can be absolutely sure that everything in the array is an account. generics. This is all to the good. it has to use a compromise to allow it to hold references to any kind of item in a program.2 The List class The List class gives you everything that an arraylist gives you. and provides you with some means to work with them. 5. And I only really find out when I start trying to process elements as Accounts and my program starts to go wrong. being based on the generic features provided by a more recent version of the C# language. The way that the system works. The abilities an array gives you with an array of integers are exactly the same as those you have with an array of Accounts. It holds a bunch of things in one place. It doesn't matter what the thing I'm dealing with is. this can be fixed when you move over to the List class. The ArrayList was added afterwards. } The Contains method is given a reference to an object and returns true if the arraylist contains that reference. This is simply a quick way of finding out whether or not an arraylist contains a particular reference. but the ArrayList breaks things a bit. One way to solve this problem would have been to find a way of making the ArrayList strongly typed. It could contain a whole bunch of KitchenSink references for all I know. we can sort that out when we actually want to work with something. C# Programming © Rob Miles 2010 136 . in that there is nothing to stop references of any type being added to an arraylist.Contains(robsAccount)) { Console. Generics let me write code that deal with objects as "things of a particular type". However. What the list stores is not important when making the list. cakes or even cars. Something like: "Divide the number of marbles by the number of friends and then distribute the remainder randomly". since the acountList variable is declared as holding a list of Account references. we might want to use the name of an account holder as a way of locating a particular account. robsAccount). The sharing algorithm could have been invented without worrying about the type of the thing being shared. This allows the key to your hashtable. We can now add items into our dictionary: accountDictionary.1. However.Generic namespace and works like this: List<Account> accountList = new List<Account>(). Because we have told the compiler the type of things the list can hold it can perform type validation and make sure that nothing bad happens when the list is used: KitchenSink k = new KitchenSink(). In this respect. The List class lives in the System. we have a string as the key and an Account reference as the value. You now have a system that lets you share marbles. For example. using a Dictionary has the advantage that we can only add Account values which are located by means of a string. Since the compiler knows that AccountList holds Account references. In other words. The type between the < and > characters is how we tell the list the kind of things it can store. In other words statements like this would be rejected. 5.Add(k).Account> accountDictionary = new Dictionary<string. and the items it stores.PayInFunds(50). generics can be regarded as another form of abstraction. accountList.Account>(). There is no need to cast the item in the list as the type has already been established. cousin called List. Generics and the List In the case of generics. If you wanted to share out marbles amongst you and your friends you could come up with way of doing that. it can be a general sharing behaviour that is then applied to the things we want to share.3 The Dictionary class Just as ArrayList has a more powerful. We can create a dictionary to hold these key/value pairs as follows: Dictionary<string. how about an example.Add("Rob". Count. this means that you can write code like this: accountList[0]. just as long as you have a way of telling it what to store. You could take your universal sharing algorithm and use it to share most anything. However. the behaviour you want is that of a list.Advanced Programming Generics and Collections This sounds a bit confusing. you could also use it to share out sweets. This looks just like the way the HashTable was used (and it is). We could create a List that can hold integers in a similar way: List<int> scores = new List<int>(). to be made typesafe. The above statement creates a list called acountList which can hold references to Accounts. The above statements would cause a compilation error. generically enhanced. so the HashTable has a more powerful cousin called Dictionary. C# Programming © Rob Miles 2010 137 . You can do everything with a List (Add. The C# features that provide generics add a few new notations to allow you to express this. Remove) that you can with an ArrayList.Collections. What the system works on is not particularly important. and will not accept the kitchen sink. which makes them the perfect way to store a large number of items of a particular type. How these features are used to create generic classes is a bit beyond the scope of this text. 5. k). } The Dictionary class is simply wonderful for storing keys and values in a typesafe manner.1. a lot easier. We can express the required account behaviour in terms of the following interface: public interface IAccount { void PayInFunds ( decimal amount ). Programmer’s Point: Use Dictionary and List You don't really have to know a lot about generics to be able to spot just how useful these two things are.Add("Glug". This means that our data storage requirements are that we should load all the accounts into memory when the program starts.PayInFunds(50). The account that we are going to work with only has two members but the ideas we are exploring can be extended to handle classes containing much larger amounts of data. make a List. If you want to be able to find things on the basis of a key. accountDictionary. Every time you need to hold a bunch of things. particularly library routines. but you are strongly advised to find out more about generics as it can make writing code. and I recommend it strongly to you. bool WithdrawFunds ( decimal amount ). } All the accounts in the bank are going to be managed in terms of objects which implement this interface to manage the balance and read the name of the account owner. decimal GetBalance (). We can create a class called CustomerAccount which implements the interface and contains the required methods.2 Storing Business Objects For our bank to really work we have to have a way of storing the bank accounts and bringing them back again.ContainsKey("Rob")) { Console. The programmers who wrote these things are very clever folks . You can get around this by asking the dictionary if it contains a particular key: if (d. Then we can move on to consider the code which will save a large number of them.4 Writing Generic Code The List and Dictionary classes were of course written in C# and make use of the generic features of the language. and then save them when the program completes. The only problem with this use of a dictionary is that if there is no element with the key "Rob" the attempt to find one will result in a KeyNotFoundException being thrown. To start with. It also has a constructor which allows the initial name and balance values to be set when the account is created. Don't have any concerns about performance. A further advantage is that we do not need to cast the results: d["Rob"]. string GetName(). If we want to our program to be able to process a large number of accounts we know that we have to create an array to manage this.WriteLine("Rob is in the bank"). This would find the element with the hash key "Rob" and then pay fifty pounds into it. 5. use a Dictionary. we'll consider how we save one account.Advanced Programming Storing Business Objects KitchenSink k = new KitchenSink(). C# Programming © Rob Miles 2010 138 . this is the only way that we can save an account. but it is just here to illustrate how the data in the class can be saved and restored. private string name. } public decimal GetBalance () { return balance.Advanced Programming Storing Business Objects public class CustomerAccount : IAccount { public CustomerAccount( string newName. 5.2. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false. since any save mechanism would need to save data in the account which is private and therefore only visible to methods inside the class. if you think about it. In fact. } public string GetName() { return name. decimal initialBalance) { name = newName. so it is not what I would call "production" code. balance = initialBalance.amount . We can add a Save method to our CustomerAccount class: C# Programming © Rob Miles 2010 139 . } } Note that this version of the class does not perform any error checking of the input values. } public void PayInFunds ( decimal amount ) { balance = balance + amount . } private decimal balance = 0.1 Saving an Account The best way to make achieve the saving behaviour is to make an account responsible for saving itself. return true. } balance = balance . Close(). A way to get around this is to write a static method which will create an account given a filename: public static CustomerAccount Load(string filename) { CustomerAccount result = null. } catch { return false.2.Advanced Programming Storing Business Objects public bool Save ( string filename ) { try { System.Parse(balanceText).IO. try { textIn = new System. textOut. } This method is given the name of the file that the account is to be stored int. When we save an account we have an account which we want to save.WriteLine(name).ReadLine(). result = new CustomerAccount(nameText.Save ("outputFile.TextWriter textOut = new System.balance). string nameText = textIn. } This would ask the account referred to by Rob to save itself in a file called "outputFile. The Load method above takes great pains to ensure that if anything bad happens it does a number of things: It does not throw any exceptions which the caller must catch. } finally { if (textIn != null) textIn. textOut. } This method opens a file. } return true. decimal balance = decimal.ReadLine(). System. C# Programming © Rob Miles 2010 140 . Note that I have written the code so that if the file output fails the method will return false. fetches the balance value and then creates a new CustomerAccount with the balance value and name.IO.2 Loading an Account Loading is slightly trickier than saving. So I could do things like: if (Rob.TextReader textIn = null. 5. string balanceText = textIn.StreamWriter(filename). to indicate that the save was not successful.IO.txt".WriteLine(balance).WriteLine ("Saved OK").txt")) { Console.Close() . } return result. When we load there will not be an account instance to load from.StreamReader(filename). textOut. } catch { return null.IO. It writes out the name of the customer and the balance of the account. and is something you should aim for when writing code you are going to sell. since that makes sure that a failure is brought to the attention of the system much earlier. Using streams A better solution is to give the file save method a stream to save itself.txt" ). you can argue this either way. but this would be confusing and inefficient. Actually. However. It makes sure that the file it opens is always closed.IO. rather than a filename. with large numbers of file open and close actions being required (bear in mind that our bank may contain thousands of accounts). A stream is the thing that the C# library creates when we open a connection to a file: System. If the factory fails (because the file cannot be found or does not contain valid content) it will return a null result. And they will probably try and blame me for the problem (which would be very unfair).2. We could create a new file for each account.TextWriter textOut = new System. in that it creates an instance of a class for us. } Programmer’s Point: There is only so much you can do Note that if an incompetent programmer used my Load method above they could forget to test the result that it returns and then their program would follow a null reference if the customer is not found. textOut. which we can test for: if (test == null) { Console.WriteLine(balance).WriteLine(name). The way around this is to make sure that you document the null return behaviour in big letters so that users are very aware of how the method behaves. your part doesn’t break.IO. We can create a save method which accepts the stream reference as a parameter instead of a filename: public void Save(System.WriteLine( "Load failed" ). at the moment we can only store one account in a file.TextWriter textOut) { textOut.3 Multiple Accounts The above code lets us store and load single accounts.Advanced Programming Storing Business Objects It returns null to indicate that the load failed if anything bad happens. This kind of method is sometimes called a ―factory‖ method.txt. 5. You can also get code analysis tools which are bit like "compilers with attitude" (a good one is called FxCop). you just have to make sure that. whatever happens. This is what I would call a "professional" level of quality. The reference textOut refers to a stream which is connected to the file Test. This means that their program will fail in this situation. We can use this as follows: test = CustomerAccount. as I grow older I become more inclined to make my programs throw exceptions in situations like this.StreamWriter( "Test.Load( "test.txt" ). } This save method can be called from our original file save method: C# Programming © Rob Miles 2010 141 . These scan programs for situations where the results of methods are ignored and flag these up as potential errors. the best place to do it is at the pub.IO. At the end of the day though there is not a great deal you can do if idiots use your software. However. try { textOut = new System.TextWriter textOut = null. } catch { return false.IO. decimal balance = decimal. Save(textOut). Saving and loading bank accounts Now that we have a way of saving multiple accounts to a single stream we can write a save method for the bank. not just files on a disk.ReadLine(). Note that this is an example of overloading in that we have two methods which share the same name. public static CustomerAccount Load( System.ReadLine(). } finally { if (textOut != null) { textOut. balance).IO.Parse(balanceText). This will open a stream and save all the accounts to it: C# Programming © Rob Miles 2010 142 . The load method for our bank account can be replaced by one which works in a similar way. } return result. try { string name = textIn. For example. It reads the name and the balance from this stream and creates a new CustomerAccount based on this data. } } return true.StreamWriter(filename). } catch { return null. you can create a stream which is connected to a network port. string balanceText = textIn. The C# input/output system lets us connect streams to all manner of things.Close(). Programmer’s Point: Streams are wonderful Using streams is a very good idea. result = new CustomerAccount(name. This means that if you make your business objects save and load themselves using streams they can then be sent over network connections with no extra work from you.Advanced Programming Storing Business Objects public bool Save ( string filename ) { System. } This method creates a stream and then passes it to the save method to save the item.IO.TextReader textIn) { CustomerAccount result = null. } This method is supplied with a text stream. TextReader textIn) { HashBank result = new HashBank().ReadLine().4 Handling different kinds of accounts The code above will work correctly if all we want to save and load are accounts of a particular type.IO. in that only the CurrentAccount class is responsible for the content. and supplies each item in turn.Count).Add(account.WriteLine(bankHashtable. Note that we are using a new C# loop construction here. Bank Notes: Large Scale Data Storage What we have done is created a way that we can store a large number of bank account values in a single file.Values) { account. This is very useful when dealing with collections of data. i++) { CustomerAccount account = CustomerAccount. The Load method for the entire bank is as follows: public static HashBank Load(System. A production version of the program would check that each account was loaded correctly before adding it to the hash table. } return result. However. I don't expect you to understand this at first reading. Note that before it writes anything it writes out the number of customers in the bank..GetName(). } This reads the size of the bank and then reads each of the accounts in turn and adds it to the hash table. in that everything is written in terms of the CurrentAccount class. The reason that it is here is for completeness. foreach (CustomerAccount account in bankHashtable.Load(textIn). account).bankHashtable. in this case the Values property of the bankHashtable.IO.2. Health Warning This is complicated stuff. This can be obtained via the Count property of the Hashtable. We do this is so that when the bank is read back in the load method knows how many accounts are required.TextWriter textOut) { textOut. 5. It works its way through a collection. for (int i = 0. foreach. we have seen that our customer needs the program to be able to handle many different kinds of account. i < count.Parse(countString). We have done this without sacrificing any cohesion. We could just write out the data and then let the load method stop when it reaches the end of the file.Advanced Programming Storing Business Objects public void Save(System. We have also been very careful to make sure that whenever we save and load data we manage the way that this process can fail. Note that this load method does not handle errors. string countString = textIn. } } This is the Save method which would be added to our Hashtable based bank. result. int count = int.Save(textOut). This material is provided to give you an idea of C# Programming © Rob Miles 2010 143 . but this would not allow us to detect if the file had been shortened. It gets each account out of the hash table and saves it in the given stream. and overrides the WithdrawFunds method to provide the new behaviour. Note that I have created a constructor which is supplied with the name of the account holder. decimal initialBalance. the starting balance and the name of the parent. As an example. This makes use of the constructor in the parent to set the balance and name. a special account for young people which limits the amount that can be withdrawn to no more than 10 pounds. but it assumes a very good understanding of class hierarchies. } public override bool WithdrawFunds(decimal amount) { if (amount > 10) { return false. } return base. The customer has also asked that the BabyAccount class contains the name of the "parent" account holder. initialBalance) { parentName = inParentName.Advanced Programming Storing Business Objects how you really could make a working bank. I can create a BabyAccount as follows: BabyAccount babyJane = new BabyAccount ("Jane". } public BabyAccount( string newName.WithdrawFunds(amount). This turns out to be very easy. The good news is that when you do understand this stuff you really can call yourself a fully-fledged C# programmer. string inParentName) : base(newName. This would create a new BabyAccount instance and set the reference babyJane to refer to it. Saving a child class When we want to save a BabyAccount we also need to save the information from the parent class. and then sets the parent name. parentName. 20. method overriding/overloading and constructor chaining. "John"). It contains an additional property. some of which will be based on others. } } This is a complete BabyAccount implementation. Banks and Flexibility We know that when our system is actually used in a bank there will be a range of different kinds of account class. as long as we use the save method which sends the information to a stream: C# Programming © Rob Miles 2010 144 . we have previously discussed the BabyAccount. We could implement such behaviour by creating an account which extends the CustomerAccount class and adds the required behaviours and properties: public class BabyAccount : CustomerAccount { private string parentName. public string GetParentName() { return parentName. In the code above there is a constructor for the BabyAccount class which accepts the three data items that the BabyAccount holds and then sets the instance up with these values.ReadLine(). but when it runs it will not work correctly. Loading a child class We could create a static load method for the BabyAccount which reads in the information and constructs a new BabyAccount: public static BabyAccount Load( System. it first calls the overridden method in the parent to save the CustomerAccount data. This is very good design. I'm not particularly keen on this approach. string parent = textIn.TextReader textIn) { BabyAccount result = null. textOut. I can therefore write code like this: C# Programming © Rob Miles 2010 145 . } This constructor sets up the new CustomerAccount instance by reading the values from the stream that is supplied with. string balanceText = textIn. What we really want to do is make the CustomerAccount responsible for loading its data and the BabyAccount just look after its content. balance. We know that a constructor is a method which gets control when an instance of a class is being created. result = new BabyAccount (name.. } However. balance = decimal. } return result. } This method overrides the Save method in the parent CustomerAccount. Then it performs the save behaviour required by the BabyAccount class.ReadLine(). as it means that if the data content and save behaviour of the parent class changes we don't need to change the behaviour of the child. If I forget to do this the program will compile.ReadLine().Advanced Programming Storing Business Objects public override void Save(System.IO. parent). What we do is create constructors for the CustomerAccount and BabyAccount classes which read their information from a stream that is supplied to them: public CustomerAccount(System.Save(textOut).Parse(balanceText). try { string name = textIn. and it can be passed information to allow it to do this. The way to do this is to go back to the construction process. A constructor can be used to set up the data in the instance.Parse(balanceText).IO. However.WriteLine(parentName). } catch { return null. in a similar way to the way the save method uses the base keyword to save the parent object.ReadLine().ReadLine().IO. decimal balance = decimal.TextWriter textOut) { base. string balanceText = textIn.TextReader textIn) { name = textIn. This method breaks one of the rules of good design. result = new CustomerAccount(textIn). decimal GetBalance ().Values) { textOut.TextReader textIn) : base (textIn) { parentName = textIn.TextWriter textOut) { textOut. If the behaviour of the CustomerAccount constructor changes we do not have to change the BabyAccount at all.IO. account. this is reasonable behaviour. since the account container will not have to behave differently depending on what kind of account it is saving.IO.WriteLine(account. textIn.Count). it just has to call the save method for the particular instance. However. This creates a new CustomerAccount from the stream. bool Save(string filename).GetType(). void Save(System. in that when we are loading the accounts we don't actually have an instance to call any methods on. Note that these constructors do not do any error checking. This is very useful when we store our collection of accounts. they just throw exceptions if something goes wrong. The save method for our bank could look like this: public void Save(System. bool WithdrawFunds ( decimal amount ). This is a good idea.IO.Save(textOut).IO. The solution to this problem is to identify the type of each instance in the steam when we save the classes. bearing mind we are reading from a stream of data. but it could be updated to include them: public interface IAccount { void PayInFunds ( decimal amount ).Close(). You might think it would be sensible to add load methods to the IAccount interface. there is a problem here. Bearing in mind that the only way that a constructor can fail is to throw an exception anyway.Advanced Programming Storing Business Objects System. } } C# Programming © Rob Miles 2010 146 . things get a little trickier. Also.StreamReader(filename). Interfaces and the save operation When we started this account development we set out an interface which describes all the things which an instance of an account should be able to do.IO.Name).TextReader textIn = new System. } We can now ask any item which implements the IAccount interface to save itself to either a file or a stream.TextWriter textOut). Now I can create a constructor for the BabyAccount which uses the constructor of the parent class: public BabyAccount(System. so that we can ask instances of a particular kind of account to load themselves. At the start this did not include the save behaviours. Loading and factories When it comes to loading our classes back.ReadLine(). string GetName(). } This removes the dependency relationship completely.WriteLine(bankHashtable. we don't actually know what kind of item we are loading. foreach (CustomerAccount account in bankHashtable. for (int i = 0. This writes out the name of the class. The neatest way to do this is to create a factory which will produce instances of the required class: class AccountFactory { public static IAccount MakeAccount( string name. It makes use of the method GetType().Add(account.Advanced Programming Storing Business Objects This looks very like our original method. It involves writing code which will search for C# classes which implement particular interfaces and creating them automatically. result.bankHashtable. In other words. IAccount account = AccountFactory. string countString = textIn. the name of the class to be created and a stream to read from. However this kind of stuff is beyond the scope of this text. } } } This class only contains a single method. except that it uses the factory to make account instances once it has read the name of the class from the stream. which is static. } return result. If we ever add a new type of account we need to update the behaviour of the factory so that it contains a case to deal with the new account type.IO.IO. creates one. } Again.TextReader textIn) { switch (name) { case "CustomerAccount": return new CustomerAccount(textIn).ReadLine(). Factory Dependencies Note that we now have a genuine dependency between our system and the factory class. It uses the name to decide which item to make. i++) { string className = textIn.TextReader textIn) { HashBank result = new HashBank().Parse(countString). this looks very like our original load method.GetName(). if the account is of type CustomerAccount the program will output: CustomerAccount Rob 100 The output now contains the name of the type of each class that has been written.MakeAccount(className. This means that when the stream is read back in this information can be used to cause the correct type of class to be created. C# Programming © Rob Miles 2010 147 .ReadLine(). which has been highlighted. int count = int. account). The bank load method can use this factory to create instances of accounts as they are loaded: public static HashBank Load(System. except that it has an additional line. and then returns that to the caller. textIn). System. If the name is not recognized it returns null. which can be called on an instance of a class to get the type of that class. There is in fact a way of removing the need to do this. i < count. default: return null. case "BabyAccount": return new BabyAccount(textIn). Having got the type we can then get the Name property of this type and print that. The method is given two parameters. Programmer’s Point: Production Code From now on all the code examples are going to be given in the context of production code. The job of the business object is to make sure that the data that it holds is always correct. However. The new name must be a valid one. The way that we manage the saving of items (by using a method in the class) loading (by using a constructor) is not symmetrical. We now also know how to save the information in a class instance. 5. This might make the examples a bit more complex that you might like..3. If it is going to reject names it would be very useful to the user if they could be told why a given name was not valid.Advanced Programming Business Objects and Editing Bank Notes: Messy Code You might think that the solutions above are rather messy. When you want to move from objects to storage and back you will find that you hit these issues and this solution is as good as any I've found. there is more to it than just changing one string for another. are just those that "real" programmers are up against. A good software engineer would provide something like this: C# Programming © Rob Miles 2010 148 . and also perform this for a large number of items of a range of different types. This means that the account must be able to reject names it doesn't like. Now we need to consider how we can make our account management system genuinely useful. there is no dishonour in this way of working. and the problems you are grappling with. 5. It is important that this is always stored safely but people may want to change their name from time to time. This means that the business object must provide a way that the name can be changed. This is code which I would be happy to have supplied in a product. Managing a bank account name As an example.1 The role of the Business Object We have taken a very strict line in our banking system to stop any of the bank account components from actually talking to the user. so the validation process should provide feedback as to why it did not work. It is not their job to talk to users. they are strictly concerned with keeping track of the information in the bank account of the customer.3 Business Objects and Editing We have seen how to design a class which can be used to hold information about the customers in our bank. but I reckon this is worth doing since it is important you start to understand that what you are writing now. However. This is because classes like CustomerAccount are what is called business objects. consider the name of the bank account holder. I provide the validate method so that users of my class can check their names to make sure that they are valid. } string trimmedName = name. once we have these methods.Trim(). public string GetName() { return this. } public bool SetName ( string inName ) { string reply . The reasons why a name is invalid are of course part of the metadata for the project. reply = ValidateName(inName). the natural thing to do is create tests for them: C# Programming © Rob Miles 2010 149 . the string is rejected.Advanced Programming Business Objects and Editing private string name. } return "". } this. since I also use the method myself when I validate the name. or just contains spaces. Testing Name Handling Of course. I’ve also made this method static so that names can be validated without needing to have an actual instance of the account. There may be several reasons why a name is not valid. if ( trimmedName.Length > 0 ) { return false.Length == 0 ) { return "No text in the name". This does not involve me in much extra work. } public static string ValidateName ( string name ) { if ( name == null ) { return "Name parameter null".Trim(). if ( reply. return true. The validate method returns a string which gives an error message if the string is rejected.name. The validate method is called by the set method so that my business object makes sure that an account never has an invalid name.name = inName. The validate method will reject a name string which is empty. It trims off all the spaces before and after the name text and then checks to see if the length of the resulting string is empty. } The name is stored as a private member of the account class. another to set it and another to validate it. at the moment I've just given two. There is a method to get the name. If it is. The programmer has provided three methods which let the users of my Account class deal with names. errorCount++.Advanced Programming Business Objects and Editing int errorCount=0. if (reply != "Name parameter null") { Console. } if ( a. errorCount++. And that is the matter of error handling. 50). if (reply != "No text in the name") { Console. Then I make sure that I can set the name on an account.WriteLine("Empty name test failed").WriteLine("Pete GetName failed"). You should consider issues like this as part of the metadata in your project. if (!a. Programmer’s Point: Use Numbers Not Messages There is one issue which I have not addressed in my sample programs which stops them from being completely perfect. string reply. errorCount++. Editing the Name We now have a business object that provides methods which let us edit the name value. } reply = CustomerAccount.WriteLine("Null name test failed"). errorCount++. errorCount++. The fact that the system must work in France and Germany is something you need to be aware of right at the start.GetName() != "Jim" ) { Console. All I would need is a lookup table to convert the message number to an appropriate string in the currently active language.GetName() != "Pete" ) { Console. } if (errorCount > 0 ) { SoundSiren().ValidateName(" "). reply = CustomerAccount. } These are all the tests I could think of. At the moment the errors supplied by my validation methods are strings.SetName("Jim")) { Console.WriteLine("Blank string name test failed"). errorCount++. } reply = CustomerAccount.WriteLine("Pete trim SetName failed"). Finally I check that the space trimming for the names works correctly.WriteLine("Jim SetName failed").ValidateName(null). } if ( a.SetName(" Pete ")) { Console.ValidateName(""). if (reply != "No text in the name") { Console. This is because they are much easier to compare in tests and it also means that my program could be made to work in a foreign language very easily. } if (!a. I can now write code to edit this property: C# Programming © Rob Miles 2010 150 . First I test ValidateName to make sure that it rejects both kinds of empty string.WriteLine("Jim GetName failed"). In a genuine production environment the errors would be numeric values. } CustomerAccount a = new CustomerAccount("Rob". errorCount++. Advanced Programming Business Objects and Editing while (true) { Console. string reply.account = inAccount. public AccountEditTextUI(Account inAccount) { this. When I want to edit an account I create an editor instance and pass it a reference to the account instance: public class AccountEditTextUI { private IAccount account. reply = account. if ( reply.WriteLine( "Invalid name : " + reply ).ReadLine(). Now that we have our edit code we need to put it somewhere. There will be a dependency between the editor class and the account class. Creating an Editor class The best way to do this is to create a class which has the job of doing the editing. reply = this. Console. but it does keep the user informed of what it is doing and it does work. } Console. This class will work on a particular account that needs to be edited. but this is something we will just have to live with. } this. This code will perform the name editing for an account instance referred to by account.ReadLine().Write ( "Enter new name : " ) . If the name is not valid the message is printed and the loop repeats.Write ( "Enter new name : " ) . newName = Console. } } C# Programming © Rob Miles 2010 151 .ValidateName(newName). It will read a new name in.account. string reply.Length == 0 ) { break. if ( reply.account. If the name is valid the loop is broken and the name is set. } account. } public void EditName () { string newName. } Console. This is not the most elegant solution. while (true) { Console. newName = Console.ValidateName(newName).SetName(newName). in that if the account class changes the editor may need to be updated.WriteLine( "Name Edit" ).SetName(newName).Length == 0 ) { break.WriteLine( "Invalid name : " + reply ). Console.WriteLine ( " Enter pay to pay in funds" ).Write ("Enter command : "). AccountEditTextUI edit = new AccountEditTextUI(a). You will use this technique when you create different editing forms 5. not a references to the account class. This code creates an instance of a customer account.ReadLine(). but I will add other edit methods later. Console. I've extended the account class to manage the account balance and added edit methods which pay in funds and withdraw them. account. edit.2 A Text Based Edit System We now have a single method in our editor class which can be used to edit the name of a bank account.. Note that I trim the command string and convert it to lower case before using it to drive the switch construction which selects the command.Advanced Programming Business Objects and Editing This is my account editor class. Programmer’s Point: Get used to passing references around It is important that you get used to the idea of passing references between methods.GetName() ).EditName(). At the moment it can only edit the name. Note that the editor class is passed a reference to the IAccount interface. Console. It then passes that reference to the service methods which will do the actual work.3. I would use the name editor as follows: CustomerAccount a = new CustomerAccount("Rob". Console.Trim(). Console. do { Console. It then creates an editor object and asks it to edit the name of that account.WriteLine ( "Editing account for {0}". command = Console. public void DoEdit (CustomerAccount account) { string command. switch ( command ) { C# Programming © Rob Miles 2010 152 . I pass it a reference to this account when I construct it.WriteLine ( " Enter exit to exit program" ). My edit class contains a method which does this: This is my edit method which repeatedly reads commands and dispatches them to the appropriate method.ToLower().WriteLine ( " Enter draw to draw out funds" ). The class keeps track of the account it is editing. command = command. This means that anything which behaves like an account can be edited using this class.WriteLine ( " Enter name to edit name" ). The edit method is passed a reference to the account which is being edited. Note also that the editor remembers the account class that is being edited so that when I call EditName it can work on that reference. 50). If I want to "give" a class something to work on I will do this by calling a method in that class and passing the reference as a parameter to this method. command = command. The C# libraries contain a set of resources which help you manage the internationalization of your programs. } } while ( command != "exit" ). case "draw" : WithDrawFunds(account). The only thing that can decide on the validity of a name is the account object itself. break.1 Creating a Form If I want a form on the screen for the user to interact with. Everything should be managed in terms of message numbers. As a general rule in a production system you should never write out straight text to your user (this includes the names of commands that the user might type in). This question is not the responsibility of the front end.4. These will range from an operator in a call centre.Windows. an operator on a dial up terminal.Advanced Programming A Graphical User Interface case "name" : EditName(account). The menu for my bank account edit method sample code prints out text which is hard wired to English. 5. Bank Notes: More Than One User Interface The bank may have a whole range of requirements for editing account details. a customer on a mobile phone and a customer at a cash machine. Note that we never do things like allow the user interface code to decide what constitutes a valid name. The object that I create is a Form. case "pay" : PayInFunds(account). I hope that you can see that the only way we can manage all these different ways of interacting with the bank account is to separate the business object (the account itself) from the input/output behaviour. This class can be found in the System. I can create an instance of this class and ask it to do things for me: C# Programming © Rob Miles 2010 153 . break. In a properly written program this would be managed in terms of message numbers to make it easier to change the text which is output. I need to create an instance of an object to do this for me. 5.4 A Graphical User Interface It should come as no surprise that a graphical user interface on the screen is represented by objects.Forms namespace. } Programmer’s Point: Every Message Counts You should remember that every time your program sends text to the user you may have a problem with language.. The user interface must always work on the basis that it will use the business object to perform this kind of validation. break. Forms. f.ShowDialog(). It can 'contain' a number of graphical components which are used to build the user interface. f. sets the text property of the label to ―Hello‖ and then adds it to the controls which are contained by the frame. } } The Form class provides a method called ShowDialog. Adding Components to a Form A form is a container. title. Label title = new Label (). This asks the form to show itself and pause the program until the form is closed. it disappears and the program ends.ShowDialog(). to add a label to the form we can do the following: using System. f.Add(title). We must create the components and add them to the form to make our user interface.Text="Hello".Forms. } } This creates a label. class FormsDemo { public static void Main () { Form f = new Form().Advanced Programming A Graphical User Interface using System. For example. class FormsDemo { public static void Main () { Form f = new Form(). The result of this code is a form which looks like this: I can fiddle with the properties of a component to move it around on the screen and do lots of interesting things: C# Programming © Rob Miles 2010 154 . If I run the program above the following appears on the screen: When the window is closed with the red button.Windows.Windows.Controls. ForeColor = Color. the pixel at 0.ShowDialog(). } } The position on the screen is given in pixels (a pixel being an individual dot on the screen). it behaves like every text field you've ever used on a windows screen. In short. The origin (i.Advanced Programming A Graphical User Interface using System.Windows. class FormsDemo { public static void Main () { Form f = new Form(). It provides a whole set of static colour values and also lets you create your own colours by setting the intensity of the red. f. title.Forms.BackColor = Color. It lets the user cut and paste text in and out of the box using the Windows clipboard. title.e. title. Label title = new Label (). The user can then enter text into the textbox and modify it. This is a component just like a label. title. green and blue components. The Windows Forms library provides a TextBox component which is used for this.Left=50. The program above would display a form as below: By adding a number of labels on the form and positioning them appropriately we can start to build up a user interface. I can set the text property of the TextBox to the text I want to have edited.Drawing namespace. This is because it is actually the same thing as every text field you've ever used. but it provides text edit behaviour. I can then read the text property back when I want the updated value. Editing Text with a TextBox Component Displaying labels is all very well.Yellow.Red.Drawing.Text="Hello". The TextBox gives me a great deal of functionality for very little effort on my part. The Color class is found in the System.Add(title). I can create and use a TextBox in my program as follows: C# Programming © Rob Miles 2010 155 .Top=50.0) is in the top left hand corner of the screen. but what I want to do is provide a way that the name text can be edited.Controls. It lets the user type in huge amounts of text and scrolls the text around to make it fit in the box. title. f. using System. It also lets you change the text in the name for whatever you want. Label nameLabel = new Label(). TextBox nameTextBox = new TextBox().Advanced Programming A Graphical User Interface using System. If you run this program you get a form as follows: This is not particularly flashy. f. class FormsDemo { public static void Main() { Form f = new Form(). I can place it on the form and manage its position just like any other: C# Programming © Rob Miles 2010 156 . nameLabel.Controls. f. This will trigger my program to store the updated name and close the form down. The Button Component What we want is a button that the user can press when they have finished editing the name. just to show how the components work.Top=50. I've also set the name text we are editing to be Rob.Add(nameLabel). A Button is just like any other component. But at the moment we have no way of signalling when the edit has been finished. nameLabel.ShowDialog(). Now we are going to find out how to make one work. For that we need a button which we can press to cause an event.Forms.Top=50.Left=0.Add(nameTextBox). f. nameLabel. nameTextBox.Left=100. nameTextBox.Controls. You have pressed buttons like these thousands of times when you have used programs. nameTextBox.Drawing.Text="Name".Text = "Rob".Windows. but it is not bad for 25 or so lines of code. } } I've fiddled slightly with the position of the label and given it a more sensible name. using System. Label nameLabel = new Label(). Up until now our programs have run from beginning to end. Users expect to interact with items on a screen by pressing "buttons" and triggering different actions inside the program. This means that the way our programs work has to change. finishButton.Top=50. nameLabel. f. When the program wants something from the user it waits patiently until that information is supplied (usually by means of a call of the ReadLine method). nameTextBox.Add(finishButton). TextBox nameTextBox = new TextBox(). f. f.2 Events and Delegates Events are things that happen.Left=0.Left=100. 5. (well.Advanced Programming A Graphical User Interface using System. nameLabel. f. using System. } } This gives me a button on the form which I can press: However at the moment nothing happens when the button goes down.Forms.Text="Name".Text="Finished".Text = "Rob".Controls. Button finishButton = new Button(). To get this to work we have to bind a method in our program to the event which is generated when the button is pressed. nameLabel.Add(nameTextBox). nameTextBox. finishButton.4.Top=50. C# Programming © Rob Miles 2010 157 . finishButton. Nowadays program use is quite different.Controls. class FormsDemo { public static void Main() { Form f = new Form().Add(nameLabel).Top=80.Left=100. The windows forms system uses delegates to manage this. Rather than waiting for the user to do something our programs must respond when an event is generated. nameTextBox.Drawing.Controls. The upshot of this is that the programming language must provide some means by which events can be managed.ShowDialog(). At any given instant the program was either running through code or waiting for input. duh).Windows. In the early days of computers this is how they were all used. Button Events To get back to the problem we are solving. The button then does its animation so that it moves in and out. The button keeps a list of people to tell about events.Text="Finished".Advanced Programming A Graphical User Interface Events and method calls In C# an event is delivered to an object by means of a call to a method in that object.Forms.Left=100. nameTextBox.Add(nameTextBox). from mouse movement. finishButton. so we can use this class every time we need to create a delegate. using System. f. f. Then it looks for people to tell about the event. From the point of view of our name editing form we would like to have a particular method called when the "Finished" button is pressed by the user. to window closing. nameLabel. f. TextBox nameTextBox = new TextBox(). The form decides which of the components on the form should be given the event and calls a method in that component to tell it "you've been pressed".Add(finishButton). In this respect you can regard an event and a message as the same thing.Controls.Top=50.ShowDialog().Top=80.Left=100. store it if it was OK and then close down the edit form. nameLabel. using System. In the case of our button. Button finishButton = new Button(). f. class FormsDemo { public static void Main() { Form f = new Form(). The good news is that creating a delegate instance for a windows component is such a common task that the forms library has provided a delegate class which does this for us.Left=0.Controls. finishButton. nameTextBox. Label nameLabel = new Label(). nameLabel.Add(nameLabel).Text = "Rob". finishButton.Drawing.Text="Name". finishButton. C# Programming © Rob Miles 2010 158 . We just need to create an instance of this class to get a delegate to give to the button. the delegate is going to represent the method that we want to have called when the button is pressed. So. A delegate is an object which can be used to represent a particular method in an instance of a class. We pass the button a reference to this delegate and it can then call the method it represents when the button is pressed. This method would validate the new name. The actual code to create a delegate and assign it to a method is as follows: using System. The list is actually a list of delegates.Windows.Controls.Top=50. nameTextBox. to get a button to run a method of ours we need to create a delegate object and then pass that to the button so that it knows to use it when the event occurs. when the user clicks on the button on our form this is registered by the Windows operating system and then passed into the form as an event. The signature of the method that is called when the event occurs is the same for every kind of event. to button press.Click += new EventHandler(finishButton_Click). 5. In the code above I have an event handler method called finishButton_Click which accepts these parameters (but doesn't do anything with them). we might want to use them to provide information such as the mouse coordinates. C# Programming © Rob Miles 2010 159 .WriteLine ("Finish Pressed").3 An Account Edit Form My example code above is OK for showing how the forms work and components are added to them. sometimes. This is because I have made everything by hand and there is no edit object as such. If you remember our text editing code you will recall that we had an object which did the editing for us. for example when we are capturing mouse movement events. The EventHandler delegate class is in the System namespace and can refer to methods which are void and accept two parameters. The idea is that when the form is created the constructor in the form makes all the components and adds them to the form in the appropriate places. To make a proper account editor we need to create a class which will do this job for us. a reference to the object which caused the event and a reference to an EventArgs instance which contains details about the event which occurred. We passed it a reference to our account and it managed the edit process. In the completed editor this method will finish the edit off for us. Our form can then be regarded as a customised version of an empty form. EventArgs e) { Console. returning when the edit was complete.Advanced Programming A Graphical User Interface } private static void finishButton_Click( object sender.4. If you compile the above program and run it you will find that each time you press the Finish button the program prints out a message. often our methods will ignore the values supplied. This will be used in almost exactly the same way as the text editor. but it is not production code. } } The highlighted code is the bit that ties a delegate to the click event. Instead it prints out a message each time the button is pressed. Note that we don’t actually have to use the parameters. However. Extending the Windows Form class It turns out that the best way to create a class to do this job is to extend the Form class to make a new form of our own. This is a standard technique for using windows components. And the way that you create customised versions of classes is to extend them. if ( reply.Add(this.Forms.finishButton.Add(this. } this.Top=50. this. IAccount account.Text).EventArgs e) { string reply = account.finishButton).Length > 0 ) { System.nameLabel).finishButton.Windows.Top=80.Click += new System.Windows. private TextBox nameTextBox.Text="Finished".nameTextBox = new TextBox().account. The finishButton_Click method gets the name out of the text box and validates it. return.Form { private Label nameLabel. this.Left=100. It then gets the properties out of the form and displays them for editing. this.Controls. private Button finishButton. this.Advanced Programming A Graphical User Interface using System.Windows.nameTextBox.nameLabel = new Label(). If it is the name of the account class should be set and the form must then dispose of itself. This code is the windows equivalent of the AccountEditTextUI method that we created previously.Left=100.finishButton.Text="Name".Top=50.EventHandler(finishButton_Click).Show(reply) .Text) . this.nameTextBox. } } The form will be passed a reference to the account instance which is being edited.nameTextBox). this. this.nameTextBox. public AccountEditForm (IAccount inAccount) { this. this. this. } private void finishButton_Click(object sender. this.SetName( nameTextBox. this.GetName().Dispose().nameLabel.account. public class AccountEditForm : System.Forms.Forms.finishButton = new Button(). this.MessageBox. this.nameLabel. If the name is invalid it uses a static method in the windows forms system to pop up a message box and report an error: C# Programming © Rob Miles 2010 160 .Left=0.Add(this.Controls. this.ValidateName(nameTextBox. When the user presses the finish button the form must make sure that the name is valid.nameLabel.Controls. using System.Text = this. System.finishButton. this. this.account = inAccount. this. All the form components are created in the constructor for the form. the fundamental principles that drive the forms it produces are exactly the same. AccountEditForm edit = new AccountEditForm (a). This piece of test code creates an account and sets the name of the account holder to Rob. It will also look after the creation of delegates for button actions. Visual Studio and Form Editing The Visual Studio application can take care of all the hard work of creating forms and adding components to them. There are a number of different forms of this Show method which you can use to get different forms of message box and even add extra buttons to it. Disposing of forms The Dispose method is used when we have finished with this form and we want it to get rid of it. It then creates an edit form and uses that to edit the name value in the account.SetName("Rob").ShowDialog(). Once we have disposed of a form we can never use it again. Using the Edit form To use the edit form we must first construct an account instance. The Dispose method is important because we must explicitly say when we have finished with the instance. Modal Editing The call of ShowDialog in the edit form is modal. However. Account a = new Account(). Programmer’s Point: Customers really care about the user interface If there is one part of the system which the customer is guaranteed to have strong opinions about it is the user interface. This means that while the form is on the screen the rest of the system is paused. edit. ever assume you know that the user interface should work in a particular way.Advanced Programming A Graphical User Interface This is how we tell the user that the name is not correct. We will need to create a new form instead. We then pass a reference to the account into the constructor of an AccountEditForm.WriteLine ( "Name value : " + a. The design of this should start at the very beginning of the product and be refined as it goes. The good news is that with something like Visual Studio it is very easy to produce quite realistic looking prototypes of the front end of a system. I have had to spend more time re-working user interface code than just about any other part of the system. Never. it is important to remember that although it automates a lot of the actions that I have performed by hand above. All the components on the form are destroyed and the form is removed from the screen. These can then be shown to the customer (get them signed off even) to establish that you are doing the right thing.GetName()). In the code above the WriteLine is not performed until after the edit form has been closed. a. If we just removed a reference to the form object it will still remain in memory until the garbage collector gets around to noticing it. Console. C# Programming © Rob Miles 2010 161 . This means I can use it as a kind of method selector. Therefore you should read this text carefully and make sure you understand what is going on. We have seen that things like overriding let us create methods which are specific to a particular type of object.1 Type safe delegates The phrase type safe in this context means that if the method accepts two integer parameters and returns a string. Delegates are useful because they let us manipulate references to methods. When the event occurs (this is sometimes called the event "firing") the method referred to by the event is called to deliver the message.Advanced Programming Using Delegates 5. for example we provided a custom WithdrawFunds for the BabyAccount class which only lets us draw out a limited amount of cash. Note that I've not created any delegates yet. I call a delegate ―A way of telling a piece of program what to do when something happens‖. This word is used to distinguish a delegate from things like pointers which are used in more primitive languages like C. Events are things that happen which our program may need to respond to. Just remember that delegates are safe to use. the delegate for that method will have exactly the same appearance and cannot be used in any other way. Delegates are an important part of how events are managed in a C# program. An example of a method we might want to use with this delegate you could consider this one: C# Programming © Rob Miles 2010 162 . I've just told the compiler what the delegate type CalculateFee looks like. consider the calculation of fees in our bank. If you call the delegate it calls the method it presently refers to. A delegate is a "stand in" for a method.5 Using Delegates Events and delegates are a very important part of C#. It might want to have a way in which a program can choose which fee calculation method to use as it runs.5. In C you can create pointers to methods. This delegate can stand in for a method which accepts a single decimal parameter (the balance on the account) and returns a decimal value (the amount we are going to charge the customer). These techniques are very useful. depending on the type of customer and the status of that customer. The way that C# does this is by allowing us to create instances of delegate classes which we give the event generators. but they are hard wired into the code that I write. In each case we need to tell the system what to do when the event occurs. This means that you can call them in the wrong way and cause your program to explode. A delegate type is created like this: public delegate decimal CalculateFee (decimal balance). We can manage which particular method is going to be called in a given situation in terms of a lump of data which we can move around. Using a Delegate As an example. 5. A posh description would have the form: A delegate is a type safe reference to a method in a class. but the C environment does not know (or even care) what the methods really look like. clocks going tick and messages arriving via the network. Once I've compiled the class the methods in it cannot change. They include stuff like people pressing buttons in our user interface. Don’t worry about this too much. The bank will have a number of different methods which do this. In the future. } } This is a rather evil fee calculator. rather than as a good way to write programs. In the same way that you can put more than one train on a C# Programming © Rob Miles 2010 163 . Now when I "call" calc it will run the FriendlyFee method. 5. so I can build structures which contain delegates and I can also pass delegates in and out of methods.6 Threads and Threading If you want to call yourself a proper programmer you need to know something about threads. Delegates are used a lot in event handlers and also to manage threads (as you will see below).1 What is a thread? At the moment our programs are only using a single thread when they run. An instance of a delegate is an object like any other. You can regard a list of delegates as a list of methods that I can call. If I want to use this in my program I can make an instance of CalculateFee which refers to it: CalculateFee calc = new CalculateFee (RipoffFee). The thread usually starts in the Main method and finishes when the end of this method is reached.6. This means that it can be managed in terms of references. where the speed of computer processors is going to be limited by irritating things like the speed of light and the size of atoms. You can visualise a thread as a train running along a track. If you are overdrawn the fee is 100 pounds. they are the way that we will be able to keep on improving the performance of our computer systems. I don’t use them much beyond this in programs that I write. The calc delegate presently refers to a delegate instance which will use the RipoffFee method. but they can also be the source of really nasty bugs. Now I can "call" the delegate and it will actually run the ripoff calculator method: fees = calc(100). Programmer’s Point: Use Delegates Sensibly Allowing programs to change what they do as they run is a rather strange thing to want to do. If you are in credit the fee is 1 pound. The track is the statements that the thread is executing. } else { return 1. They can make programs much easier to create. it is best just to consider them in terms of how we use delegates to manage the response of a program to events. 5. For now however. I can change that by making another delegate: calc = new CalculateFee (FriendlyFee). I’m presenting this as an example of how delegates let a program manipulate method references as objects.Advanced Programming Threads and Threading public decimal RipoffFee (decimal balance) { if ( balance < 0 ) { return 100. This gives us another layer of abstraction and means that we can now design programs which can have behaviours which change as the program runs. This of course only works if FriendlyFee is a method which returns a value of type decimal and accepts a single decimal value as a parameter. 6. When a thread is not running it is held in a ―frozen‖ state. it makes sense to share this ability amongst several tasks. rather than try interleaving the second task with the first. You have not been aware of this because the operating system (usually Windows) does a very good job of sharing out the processing power. The first computers had only one processor and so were forced to use ―time slicing‖ to support multiple threads.Advanced Programming Threads and Threading single track. Threads are also how Windows forms respond to events. I’m going to give some tips on how to make sure that your programs don’t fall foul of threading related bugs. Bugs caused by threading are amongst the hardest ones to track down and fix because you have to make the problem happen before you can fix it.3 Threads and Processors Consider the following method: static private void busyLoop() { long count. Newer machines now have ―dual core‖ or even ―quad core‖ processors which can actually run multiple threads simultaneously. The first is by rapidly switching between active threads. count < 1000000000000L. for (count = 0. A modern computer can perform many millions of instructions per second. The second way to support multiple threads is to actually have more than one processor.6. The programs that you have been writing and running have all executed as threads in your computer. and the circumstances that cause the fault may only occur every now and then. Programmer’s Point: Threads can be dangerous In the same way that letting two trains share the same railway track can sometimes lead to problems. Your system can play music and download files while your program waits for you to press the next key.2 Why do we have threads? Threads make it possible for your computer to do something useful while one program is held up. 5. As far as the thread is concerned it is running continuously. waiting for its turn to run. in that if we wish to do more than one thing at the same time it is very useful just to send a thread off to perform the task. Threads provide another level of ―abstraction‖. This is how your program can be active at the same time as other programs you may wish to use alongside it. and I suggest that you follow these carefully. The Windows system actually creates a new thread of execution which runs the event handler code. programs that use threads can also fail in spectacular and confusing ways. but in reality a thread may only be active for a small fraction of a second every now and then. 5. A computer can support multiple threads in two ways. These could be performed ―in the background‖ while the user continues to work on the document. count = count+1) { } } C# Programming © Rob Miles 2010 164 . If we wrote a word processor we might find it useful to create threads to perform time consuming tasks like printing or spell checking. a computer can run more than one thread in a single block of program code. You have seen that a ―click‖ event from a Button component can be made to run an event handler method. It is possible for systems to fail only when a certain sequence of events causes two previously well behaved threads to “fight” over a shared item of data. giving each thread the chance to run for a limited time before moving on to run another. The easiest way to make sure that we can use all the threading resources is to add a using directive at the start of our program: using System. If I run a program that calls this method the first thing that happens is that the program seems to stop. You can see little graphs under the CPU (Central Processor Unit) Usage History part of the display showing how busy each processor is. If I start up Windows Task Manager I see the picture below: My laptop has four processor cores. We have used namespaces to locate resources before when we used files.Threading. From the look of the above graph. 5. The Thread class provides a link between your program and the operating system.Advanced Programming Threads and Threading This method does nothing.4 Running a Thread An individual thread is managed by your program as an instance of the Thread class. the leftmost processor and the rightmost processor are quite busy but the middle two processors are not doing anything. One job of the operating system is to manage threads on your computer and decide C# Programming © Rob Miles 2010 165 . If I stop my program running I get a display like the one below. as my programs run on multiple processors. The method above can only ever use a maximum of 25% of my system.6. When we start using more than one thread we should see more of the graphs climbing up. which means that it can run four threads at a time. since it only runs on one of the four available processors. Then the fan in my laptop comes on as the processor starts to heat up as it is now working hard. Now all the processors are just ticking over. but it does do it many millions of times. Programmer’s Point: Multiple Threads Can Improve Performance If you can work out how to spread your program over several threads this can make a big difference to the speed it runs at. This class lives in the System namespace. This is like telling your younger brother where on the track you’d like him to place your train. Note that at the moment the thread is not running. } } The above code creates a thread called t1 and starts it running the busyLoop method. Creating a Thread Once you have your start point defined you can now create a Thread value: Thread t1 = new Thread(busyLoopMethod). for (count = 0. class ThreadDemo { static private void busyLoop() { long count.Start(). A delegate is a way of referring to a method in a class. t1. This is the point at which the thread begins to run. it is waiting to be started. It also calls busyLoop directly from the Main method.Start(). This delegate type can refer to a method that does not return a value or accept any parameters. This changes the Task Manager display: C# Programming © Rob Miles 2010 166 . count < 1000000000000L. You can create a ThreadStart delegate to refer to this method as follows: ThreadStart busyLoopMethod = new ThreadStart(busyLoop). Selecting where a Thread starts running When you create a thread you need to tell the thread where to start running.Advanced Programming Threads and Threading exactly when each should get to run. The variable t1 now refers to a thread instance. By calling methods provided by the Thread class you can start and stop them. To start the thread running you can use the Start method: t1. This means that there are two processes active. Starting a Thread The Thread class provides a number of methods that your program can use to control what it does. The delegate type used by threads is the ThreadStart type. When we start running t1 it will follow the delegate busyLoopMethod and make a call to the busyloop method. Thread t1 = new Thread(busyLoopMethod). If you take a look at the busyLoop method above you will find that this method fits the bill perfectly. You do this by using delegates. count = count+1) { } } static void Main() { ThreadStart busyLoopMethod = new ThreadStart(busyLoop). busyLoop(). This is potentially dangerous. Programmer’s Point: Two Many Threads Will Slow Everything Down Note that nothing has stopped your program from starting a large number of threads running. t1. This makes your computer unusable by starting a huge number of threads which tie up the processor. } This loop will create 100 threads. we can create many more threads than this: for (int i = 0. and the CPU usage is up to 100%. Now our computer is really busy: All the processors are now maxed out. all running the busyLoop method. If you run this code you might actually find that the machine becomes slightly less responsive.Advanced Programming Threads and Threading Now more of the usage graphs are showing activity and the CPU usage is up from 25% to 50% as our program is now using more processors. and that all the cooling fans come on full blast. Making lots of Threads From the displays above you can see that if we create an additional thread we can use more of the power the computer gives us. called a Denial of Service attack. This is actually the basis of a type of attack on your computer. C# Programming © Rob Miles 2010 167 . If you run too many threads at once you will slow everything down. Fortunately Windows boosts the priority of threads that deal with user input so you can usually get control and stop such wayward behaviour.Start(). i < 100. i = i + 1) { Thread t1 = new Thread(busyLoopMethod). In fact. Before the addition can be performed.Advanced Programming Threads and Threading 5. We could make a tiny change to this code and make the count variable a member of the class: static long count. When they entered the single track they were given the token. As the threads run they are all loading. static object sync = new object(). count < 1000000000000L. What we need is a way of stopping the threads from interrupting each other. Anyone wanting to enter the track had to wait for their turn with the token. This is because the variable is local to the busyLoop method: static private void busyLoop() { long count. Sometime later Thread 1 gets control again. It is now very hard to predict how long this multi-threaded program will take to finish. adds one to it and stores it back in memory. it has overwritten the changes that Thread 20 made. must be allowed to complete without being interrupted. it is as if the data for each thread is held in trucks that are pulled along behind the train. This is potentially disastrous. Using Mutual Exclusion to Manage Data Sharing Allowing two threads to share the same variable is a bit like allowing two trains to share the same piece of track. 4. C# Programming © Rob Miles 2010 168 . 2. Because of the way that Thread 1 was interrupted during its calculation. You can do this by using a feature called mutual exclusion or mutex.5 Threads and Synchronisation You might be wondering why all the threads don’t fight over the value of count that is being used as the loop counter. Both are dangerous. Thread 1 fetches the value of the count variable so that it can add 1 to it. The single track problem was solved by using a single brass token which was held by the engine driver. Consider the following sequence of actions: 1. incrementing and storing the value of count and overwriting changes that they have made. Mutual exclusion works in just the same way by using an instance of an object to play the role of the token. The statement count = count + 1. If you are still thinking about threads as trains. 3. count = count + 1) { } } The method looks very similar. When the train left single track section the track the driver handed the token back. adds 1 to the value it fetched before it was stopped and stores the result back in memory. We can return to our train analogy here. static private void busyLoop() { for (count = 0.6. but now every thread running busyLoop is now sharing the same count variable. Thread 20 fetches the value of count. for (count = 0. count = count+1) { } } The count variable is declared within the body of the method. Thread 1 is stopped and Thread 20 is allowed to run. This means that each method has its own copy of this local variable. count < 1000000000000L. Programmer’s Point: Threads can Totally Break your Program If a thread grabs hold of a synchronisation object and doesn’t let go of it. The above call would pause a program for half a second.Abort(). In other words. each thread will end when the call of busyloop finishes.Advanced Programming Threads and Threading This object doesn’t actually hold any data. Another one. and thread b has got object y and is waiting for object x. This asks the operating system to destroy that thread and remove it from memory. count = count + 1. C# Programming © Rob Miles 2010 169 . This method is given the number of milliseconds (thousandth’s of a second) that the execution is to pause. so the first thread to get to the entry point will be the first to get the token. All the increment operations will complete in their entirety. These let you pause threads. This queue is held in order. there is no chance of Windows interrupting the increment statement and switching to another process.Exit(sync). but at the expense of any other threads that want to run. called the “Deadly Embrace” is where thread a has got object x and is waiting for object y. 5. wait for a thread to finish. If you just want your program to pause. I’m going to wait for him to call me”. The code between the Monitor. This is a really good way to make your programs fail.6 Thread Control There are a number of additional features available for thread management. Once execution leaves the statements between the Monitor calls the thread can be suspended as usual. Pausing Threads As you can see above. It is just used as the token which is held by the active process. This will certainly pause your program. perhaps to allow the user to read the output or to wait a little while for something to happen you should use the Sleep method which is provided by the Thread class: Thread. This is the computer version of “I’m not calling him to apologise. You can abort a thread by calling its Abort method: t1.Sleep(500). A thread finishes when it exits the method that was called when it started.Enter(sync). Monitor.Join(). see if a thread is still active and suspend and remove threads. we don’t need to know how it works. Monitor. This would cause the executing thread to wait until the thread t1 finishes.6. In our examples above.Enter and Monitor. Threads that aren’t able to run are ―parked‖ in a queue of waiting threads. A thread instance provides a Join method that can be called to wait for another thread to complete operation. Joining Threads You might want to make one thread wait for another to finish working. t1.Exit calls can only be performed by one thread at a time. Thread Control The Thread class provides a set of methods that you can use to control the execution of a thread. one way to ―pause‖ a thread is to create a loop with an enormous limit value. this will stop other threads from running if they need that object. with the other threads lining up for their turn. The Monitor class looks after all this for us. } 5. threads can also be a great source of frustration. The most useful are: ThreadState. Synchronisation problems like the ―Deadly Embrace‖ described above may only appear when two users both request a particular feature at exactly the same time.Suspend ThreadState. However. t1. When you have problems with a multi-threaded system the biggest difficultly is always making the fault occur so you can fix it. but simply make it pause for a while.6.Running ThreadState. waiting to join with another thread or waiting for a Monitor As an example. You should protect any variables shared between threads by using the Monitor class as described above. If variables sometimes get ―out of step‖ then this is a sure sign that you have several threads fighting over data items. is to create a multi-threaded application which starts up a thread to deal with each incoming request. They let your program deal with tasks by firing off threads of execution. This will stop inadvertent data corruption. Of course. This is mostly because we have done something wrong. A program which works fine for 99. or just lock up completely. This makes the code easier to manage and also means that your program can make the best use of the processing power available. Often the only way to investigate the problem is to add lots of write statements so that the program makes a log that you can examine after it has failed. to display a message if thread t1 is running: if ( t1. The best way to create a system that must support many users. You should try to avoid any ―Deadly Embrace‖ situations by making your threads either producers or consumers of data. Unfortunately when you add multi-threading to a solution this is no longer true. We know that our programs sometimes produce errors when they run. vanish completely. Finding the state of a thread You can find out the state of a thread by using its ThreadState property.999% of the time may fail spectacularly. When we get a problem we look at what has happened and then work out what the fault is. if you are very lucky. Up until now our programs have been single threaded and we have been able to put in the data which causes the problem.WaitSleepJoin the thread is running the thread has finished executing the thread method the thread has been suspended the thread is executing a Sleep.Resume(). time spent writing the log output affects the timing of events in the program and can often cause a fault to move or. This will cause the program to fail. If consumers are always waiting for producers C# Programming © Rob Miles 2010 170 .Stopped ThreadState.7 Staying Sane with Threads Threads are very useful.ThreadState == ThreadState.Running ) { Console. you can call the Suspend method on the thread: t1.Advanced Programming Threads and Threading If you don’t want to destroy a thread. at which point we can begin to fix it.Suspend(). for example a web server. The thread is put to sleep until you call the Resume method on that thread. This is an enumerated value which has a number of possible values. when a specific set of timing related events occur.WriteLine("Thread Running"). The next step up is to have more than one railway. This is actually a very important part of the design process. You can also use the Process class to start programs for you.exe"). 5. This means that potentially badly behaved code like this has to be enclosed in a try – catch construction so that our program can respond sensibly. or a Parse method is given an invalid string. Processes are different from threads. but nothing in the word processor program can ever directly access the variables in the browser. 5. Your word processor may fire off several threads that run within it (perhaps one to perform spell checking). You should also be thinking that when you build a system you should consider how you are going to manage the way that it will fail. The Start method is supplied with the name of the program that you want to start. When something bad happens the program must deal with this in a managed way.Start("Notepad.Diagnostics namespace.Diagnostics. When you are using a word processor and a web browser at the same time on your computer each of them is running on your computer as a different process. Programmer’s Point: Put Threads into your Design I think what I am really saying here is that any thread use should be designed into your program. You can also create Process instances that you can control from within your program in a similar manner to threads.Advanced Programming Structured Error Handling (and producers never wait for consumers) then you can be sure that you never get the situation where one thread waits for a thread that is waiting for it. and not tacked on afterwards. In a C# program you can create a process and start it in a similar way to starting a thread.7 Structured Error Handling By now I hope that you are starting to think very hard about how programs fail. We have been on the receiving end of exceptions already. Now we are going to take a closer look at exceptions and see about creating our own exception types. The key to achieving this is to think about making your own custom exceptions for your system. so you can add a Using statement to make it easier to get hold of the class: using System.6. We have seen that if something bad happens whilst a file is being read.8 Threads and Processes You can regard different threads as all living in the in computer together in the same way that a number of trains can share a particular railway. in that each process has its own memory space which is isolated from other processes. In programming terms this is a move from threads to processes. the system will throw an exception to indicate that it is unhappy.. This class is held in the System. C# Programming © Rob Miles 2010 171 . The above line of C# would start the Notepad program. To start a program on your system you can use the Start method on the Process class: Process. If you want to use threads the way that they are managed and how they communicate should be decided right at the start of your design and your whole system should be constructed with them in mind. 7.Exception class: public class BankException : System. I might want to throw an exception if the name of my account holder is an empty string. The default constructor in BankException (which is added automatically by the compiler).Exception class. I can do this with the code: if ( inName. 5.2 Creating your own exception type Creating your exception type is very easy.Exception class has a default constructor which takes no parameters.7. but they are all based on the parent Exception class. However. For example.1 The Exception class The C# System namespace holds a large number of different exceptions. It can be done by simply extending the System. but this means that exceptions produced by your code will get mixed up with those produced by other parts of the system.Length == 0 ) { throw new BankException( "Invalid Name" ). This all (of course) leads back to the metadata which you have gathered. In the code above I make a new instance of the bank exception and then throw that.7.Exception when something goes wrong. there is a version of the Exception constructor which lets us add a message to the exception. 5. can just use this to make an Exception instance. This might be a catch of mine.Advanced Programming Structured Error Handling 5. If you want to throw your own exceptions you are strongly advised to create your own exception type which extends the system one. If the exception is caught by the system it means that my program will be terminated. If I want to use this with my bank exception I have to sort out the constructor chaining for my exception class and write code as follows: public class BankException : System. } The throw keyword is followed by a reference to the exception to be thrown. or it might be one supplied by the system. At this point the execution would transfer to the ―nearest‖ catch construction. The thing that is thrown must be based on the System. along with everything else in your system. You can generate System.Exception { } This works because the System. If you want your code to be able to explicitly handle your errors the best way forward is to create one or more of your own exceptions. This can be picked up and used to discover what has gone wrong. This means that.Exception { public BankException (string message) : base (message) { } } This makes use of the base keyword to call the constructor of the parent class and pass it the string message. you will need to design how your program will handle and generate errors. in that the specification will give you information about how things can fail and the way that the errors are produced. To create a standard exception with a message I pass the constructor a string. However.3 Throwing an Exception The throw keyword throws an exception at that point in the code. I can catch the exception myself as follows: C# Programming © Rob Miles 2010 172 . Exception { public BankExceptionBadName (string message) : base (message) { } } public class BankExceptionBadAddress : System. you should seriously consider extending the exception class to make error exceptions of your own which are even more informative. Note that.WriteLine( "Error : " + exception. the catch invoked. This helps a great deal in working with different languages. It can contain a text message which you can display to explain the problem to the user. The Message member of an exception is the text which was given. } The code tries to create a new account. try { a = new Account(newName. If the customer can say “Error number 25” when they are reporting a problem it makes it much easier for the support person to respond sensibly.Message).Advanced Programming Structured Error Handling Account a. depending on how the code fails: C# Programming © Rob Miles 2010 173 . and the message printed. the code in the exception handler is obeyed. i. We can have many catch constructions if we like. However. newAddress). Errors should be numbered. This means that if I try to create an account with an empty name the exception will be thrown. and the catch will be matched up to the type of exception that was thrown: public class BankExceptionBadName : System. If doing this causes an exception to be thrown. 5.e.7.4 Multiple Exception Types It is worth spending time thinking about how the exceptions and errors in your system are to be managed. you need to design in your handling of errors. your exceptions should be tagged with an error number.Exception { public BankExceptionBadAddress (string message) : base (message) { } } Now I can use different catches. Programmer’s Point: Design your error exceptions yourself An exception is an object which describes how things have gone wrong. } catch (BankException exception) { Console. as with just about everything else. The reference exception is set to refer to the exception which has been thrown. and most of the time you will be using test data which assumes everything is OK.Advanced Programming Program Organisation Account a. In this section we are going to see how a large program can be broken down into a number of different chunks.Exception exception ) { Console.WriteLine("System exception : " + exception. C# Programming © Rob Miles 2010 174 . This is fine for teeny tiny projects. To do this we have to solve two problems: how we physically spread the code that we write around a number of files how we logically identify the items in our program. This might mean that you have to create special test versions of the system to force errors into the code.WriteLine("Invalid address : " + addrException. As a professional programmer you must make sure that your error handling code is tested at least as hard as the rest of the system. This is especially important when you consider that a given project may have many people working on it. } catch (BankExceptionBadName nameException) { Console. but now we are starting to write much larger programs and we need a better way to organise things.8. They only get run when something bad happens. ""). } catch (BankExceptionBadAddress addrException) { Console.WriteLine("Invalid name : " + nameException.Message).Message). error handlers are rather hard to test. 5. When you create the system you decide how many and what kind of errors you are going to have to manage.1 Using Separate Source Files In a large system a programmer will want to spread the program over several different source files. in that the error handler is supposed to put things right and if it fails it will usually make a bad situation much worse. which we compile and run.Message). try { a = new Account("Rob". Programmer’s Point: Programs often fail in the error handlers If you think about it. Of course this is a recipe for really big disasters. it is worth the effort! Error handling should be something you design in. The two problems are distinct and separate and C# provides mechanisms for both. } Each of the catches matches a different type of exception. At the very end of the list of handlers I have one which catches the system exception. This means that errors are more likely to get left in the error handlers themselves. When you design your solution to a problem you need to decide where all the files live. Believe me. } catch (System.8 Program Organisation At the moment we have put the entire program source that we have created into a single file. 5. This will be called if the exception is not a name or an address one. since the code doesn’t get exercised as much as the rest of the system. So. Options are a way of modifying what a command does. However. we might want to create lots of other classes which will deal with bank accounts. So instead I have decided to put the class into a file called "AccountManagement. This is so that classes in other files can make use of it. I use the target option to the compile command. the compiler cannot make an executable file. If I look at what has been created I find that the compiler has not made me an executable. since it does not know where the program should start. You can apply the protection levels to classes in the same way that you can protect class members. } } } This is a fairly well behaved class in that it won't let us withdraw more money than we have in the account. } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . Instead other programs will run and create accounts when they need them.cs" if we wanted to.cs The compiler will not now look for a Main method. because it has been told to produce a library rather than a program. public void PayInFunds ( decimal amount ) { balance = balance + amount.exe' does not have an entrypoint defined The compiler is expecting to produce an executable program.As I add more account management The problem is that the compiler now gets upset when I try to compile the file: error CS5001: AccountManagement. } if ( balance >= amount ) { balance = balance . return true. } else { return false . Note that I have made the Account class public. Generally speaking your classes will be public if you want them to be used in libraries. We could put it into a file called "Account. Consider a really simple Account class: public class Account { private decimal balance = 0. } public decimal GetBalance () { return balance. Creating a Library I solve this problem by asking the compiler to produce a library instead. The class will be called Account.amount .cs". Our bank account class does not have a main method because the program will never start by actually running an account. instead it has made me a library file: C# Programming © Rob Miles 2010 175 .Advanced Programming Program Organisation In our bank management program we have identified a need for a class to keep track of a particular account. These have an entry point in the form of the Main method. The compiler can tell that it is being given an option because options always start with a slash character: csc /target:library AccountManagement. and so it can build the executable program.GetBalance()). Console. The compiler now knows where to find all the parts of the application.dll The language extension dll stands for dynamic link library. Firstly I'm going to create another source file called AccountTest.cs(5. Library References at Runtime We have now made two files which contain program code: AccountManagement.3): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) AccountTest.exe the library containing the Account class code the executable program that creates an Account instance Both these files need to be present for the program to work correctly. test. } } This makes a new account. Deleting System Components This means that if I do something horrid like delete the Acccountmanagement. puts 50 pounds in it and then prints out the balance.37): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) The problem is that the compiler does not know to go and look in the file AccountManagement.dll AccountTest. If I try to compile it I get a whole bunch of errors: AccountTest. This means that the content of this file will be loaded dynamically as the program runs.PayInFunds (50). This because of the "dynamic" in dynamic link library.cs to find the Account class.cs(7.dll AccountTest. which causes further errors. not when it is built. Using a Library Now I have a library I next have to work out how to use it.Advanced Programming Program Organisation AccountManagement. This contains a Main method which will use the Account class: using System. To solve the problem I need to tell the compiler to refer to AccountManagement to find the Account class: csc /reference:AccountManagement.cs(6.cs The reference option is followed by a list of library files which are to be used.dll file and then run the program this causes all kinds of nasty things to happen: C# Programming © Rob Miles 2010 176 . It means that library is only loaded when the program runs.cs. class AccountTest { public static void Main () { Account test = new Account(). This means that it fails to create test.WriteLine ("Balance:" + test. which is the library that contains the required class. In this case there is just the one file to look at.3): error CS0246: The type or namespace name 'Account' could not be found (are you missing a using directive or an assembly reference?) AccountTest. was not found. Arrgh! We are now heading for real problems.Main() … lots of other stuff This means that we need to be careful when we send out a program and make sure that all the components files are present when the program runs. We don't just want to break things into physical chunks. And here we are again. and mean that at design time we have to make sure that we name all our classes in a way which will always be unique. We have decided that Account is a sensible name for the class which holds all the details of a customer account. Or both. and the number of times that I've installed a new program (or worse yet an upgrade of an existing one) which has broken another program on the computer is too numerous to happily remember. A far better way would be to say that we have a CustomerBanking namespace in which the word Account has a particular meaning. If the two systems ever meet up we can expect a digital fight to the death about what "Account" really means.IO. The bad news is that you have to plan how to use this technology. Unless the fixed code is exactly right there is a good chance that it might break some other part of the program. File name: "AccountManagement" at AccountTest. But this would be messy. Which would be bad. The bad news is that this hardly ever works. The good news is that I can fix the broken parts of the program without sending out an entire new version. But we also have another problem. rubber stamps. Windows itself works in this way. the new version is picked up by AccountTest automatically. and then make sure you use it. Programmer’s Point: Use Version Control and Change Management So many things end up being rooted in a need for good planning and management. consider the situation in our bank. Perhaps the programmers might decide that a sensible name for such a thing would be Account. The good news is that there are ways of making sure that certain versions of your program only work with particular program files. We could solve the problem by renaming our account class CustomerBankAccount. We also want to use logical ones as well. 5. When you think about selling your application for money you must make sure that you have a managed approach to how you are going to send out upgrades and fixes. But if you consider the whole of the bank operations you find that the word "account" crops up all over the place. It may well wish to keep track of these accounts using a computer system. If this sounds boring and pedantic then I'm very sorry. If I modify the AccountManagement class and re-compile it. Of course this only works as long as I don't change the appearance of the classes or methods which AccountTest uses. This makes management of the solution slightly easier. We can also have an C# Programming © Rob Miles 2010 177 . or one of its dependencies. little pens on chains (pre-supplied with no ink in of course) and the like from suppliers. but if you don't do this you will either go mad or bankrupt. "dll hell".Advanced Programming Program Organisation Unhandled Exception: System.FileNotFoundException: File or assembly name AccountManagement. The bank will buy things like paper clips.8. There is a special phrase. If you are not sure what I mean by this. reserved for what happens. Updating System Components Creating a system out of a number of executable components has the advantage that we can update part of it without affecting everything else.2 Namespaces We can use library files to break up our solution into a number of files. You could say that the bank has an account with such a supplier. C# Programming © Rob Miles 2010 178 . If I want to use the Account class from the CustomerBanking namespace I have to modify my test class accordingly. A given source file can contain as many namespace definitions and each can contain as many classes as you like.amount . This prevents the two names from clashing. } public decimal GetBalance () { return balance.e.Account(). This is because we have not explicitly set up a namespace in our source files. } } } } I have used the namespace keyword to identify the namespace. A name like this. they are very easy to set up: namespace CustomerBanking { public class Account { private decimal balance = 0.Account test. } else { return false . with the namespace in front. If we want to create an instance of the class we use the fully qualified name again: test = new CustomerBanking. This is followed by a block of classes. is known as a fully qualified name. } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . one created outside any namespace) can just be referred to by its name. in this case CustomerBanking. If you want to use a class from a namespace you have to give the namespace as well. This creates a variable which can refer to instances of the Account class. Putting a Class in a Namespace Up until now every name we have used has been created in what is called the global namespace.Advanced Programming Program Organisation EquipmentSupplier namespace as well. public void PayInFunds ( decimal amount ) { balance = balance + amount. However. CustomerBanking. in that they are not defined in the same namespace. return true. Every class declared in this block is regarded as part of the given namespace. The Account class we use is the one in the CustomerBanking namespace. Using a Class from a Namespace A Global class (i. } if ( balance >= amount ) { balance = balance . The compiler goes "ah.WriteLine ( "Hello World" ).WriteLine ( "Hello World" ). The System namespace is where a lot of the library components are located.3 Namespaces in Separate Files There is no rule that says you have to put all the classes from a particular namespace in a particular file.Console.RudeLetters . and only one. If it finds one.IO . . .Advanced Programming Program Organisation Using a namespace If you are using a lot of things from a particular namespace C# provides a way in which you can tell the compiler to look in that namespace whenever it has to resolve the name of a particular item. When the compiler sees a line like: Account RobsAccount. The System namespace is like this. We can use these by means of fully qualified names: System. If there is it uses that. it is common for most programs to have the line: using System.at the very top. This means that the programmer can just write: Console. However. You have to make sure that the files you want to use contain all the bits are needed. We have already used this technique a lot. Console then all is well and it uses that. you'd probably figured that one out already. We do this with the using keyword: using CustomerBanking .it automatically looks in the CustomerBanking namespace to see if there is a class called Account. You get to use the items in the System. Of course the namespaces that you use should always be carefully designed. But then again..IO namespace with an appropriate include: using System. It is perfectly OK to spread the classes around a number of different source files.8. there is a namespace which is part of the System namespace which is specifically concerned with Input/Output. I'll go and have a look for a thing called Console in all the namespaces that I've been told to use". and this means of course more planning and organising. Nesting Namespaces You can put one namespace inside another. This allows you to break things down into smaller chunks. C# Programming © Rob Miles 2010 179 . and the time taken to deal with them. you will not be supplied with a sequence of steps which cause the fault to appear. if a user reports a fault the evidence may well be anecdotal.RudeLetters. Incidentally.Advanced Programming Debugging Programmer’s Point: Fully Qualified Names are Good There are two ways you can get hold of something. those which always happen and those which sometimes happen. It is very rarely that you will see your program fail because the hardware is faulty. The good news is that if you use a test driven approach to your development the number of faults that are found by the users should be as small as possible. some will always be better than others. and we are going to explore some of these here.9. you should set up a process to deal with faults that are reported. this approach will not make you popular with users. i. Not everyone is good at debugging.9 Debugging Some people are born to debug. the steps taken to manifest it will be well recorded. Also. the way in which you manage your fault reports should be considered at the start of the project. Having said that there are techniques which you can use to ease the process. I know that this makes the programs slightly harder to write. but it means that when I'm reading the code I can see exactly where a given resource has come from. I've been programming for many years and only seen this in a handful of occasions. However. In other words. The two types of Fault Faults split into two kinds. the reason why problems with programs are called bugs is that the original one was caused by an actual insect which got stuck in some contacts in the computer. 5.e. If a program fails as part of a test. If I just see the name OverdraftWarning in the code I have no idea where that came from and so I have to search through all the namespaces that I'm using to find it. you will simply be told "There's a bug in the print routine". Of the two I much prefer the fully qualified name. However. debugging is working very hard to find out how stupid you were in the first place. This is not however how must bugs are caused. There is a strong argument for ignoring a fault report if you have not been given a sequence of steps to follow to make it happen. C# Programming © Rob Miles 2010 180 . The sad thing is that most of the bugs in programs have been put there by programmers. The number of faults that are reported. you can perform the sequence which always causes the bug to manifest itself and then use suitable techniques to nail it (see later). In other words. It is important to stress to users that any fault report will only be taken seriously if it is well documented. Faults are uncovered by the testing process or by users.1 Fault Reporting We have already seen that a fault is something which the user sees as a result of an error in your program. assigned to programmers and tracked very carefully. In a large scale development fault reports are managed.OverdraftWarning) or you can get hold a items in a namespace with using. is valuable information about the quality of the thing that you are making. but there will still be some things that need to be fixed. Faults which always happen are easy. if you formalize (or perhaps even automate) the fault reporting process you can ensure that you get the maximum possible information about the problem. causing it to fail. You can spell out the complete location by using a Fully Qualified Name (CustomerBanking. Programmer’s Point: Design Your Fault Reporting Process Like just about everything else I've ever mentioned. 5. even if it is just the cat! The act of explaining the problem can often lead you to deduce the answer. add extra code to prove that what you think is happening is really happening. Explain the problem to someone else . You might track this down to the number of pages printed. some folks are just plain good at finding bugs. for loops which contain code which changes the control variable. invalid loop termination's. The manifestation of a fault may be after the error itself has actually occurred. or the amount of text on the page. If you assume that "the only way it could get here is through this sequence" or "there is no way that this piece of code could be obeyed" you will often be wrong. Look for: use of un-initialised members of classes typographical errors (look for incorrectly spelt variable names. or the loading department turn on the big hoist and inject loads of noise into the mains. What this means is that you do not have a definite sequence of events which causes the system to fail. This is particularly important if the bug is intermittent. If the fault changes in nature this indicates problems with program or data being corrupted. It is best if the person you are talking to is highly sceptical of your statements. 5. Surprisingly. for example a program may fail when an item is removed from a database. errors which overwrite memory will corrupt different parts of the program if the layout of the code changes.e. where you put in extra print statements to find out more about the problem. This can lead to the most annoying kind of fault.2 Bugswatting You can split faults into other categories. If the bug appears on Friday afternoons on your UNIX system. find out if another department uses the machine to do a payroll run at that time and fills up all the scratch space. your first test is to change the code and data layout in some way and then re-run the program. incorrect comparison operators. or in code which overwrote the memory where the database lives. but the error may be in the routine which stored the item. Rather than make assumptions. Here are some tips: Don't make any assumptions. and the problem promptly disappears! If you suspect such an error. A fault may change or disappear when the program itself is changed. or the size of the document which is being edited when the print is requested. do – while constructions which never fail. improperly terminated comments) logical errors (look for faults in the sequence of instructions. this can be harder to find. methods that call themselves by mistake and recurse their way into stack overflow an exception that is not caught properly If your program does the wrong thing. wrongly constructed logical conditions) As I said above. This does not mean that there is no sequence (unless you are suffering from a hardware induced transient of some kind – which is rather rare) but that you have not found the sequence yet. An example would be a print function which sometimes crashes and works at other times. Look at all possible (if seemingly unrelated) factors in the manifestation of the bug. C# Programming © Rob Miles 2010 181 . where the program crashes (i. crashes are often easier to fix. They usually point to: a state which is not catered for (make sure that all selection statements have a default handler which does something sensible and that you use defensive programming techniques when values are passed between modules) programs that get stuck into loops.9.Advanced Programming Debugging Faults which sometimes happen are a pain. stops completely) or when it does the wrong thing. 5. this is probably the behaviour of a stopper bug. If you have taken some time off from debugging. This is because when people change the program to make one bit of it work the change that they make often breaks other features of the system. or one of your assumptions that it is impossible is wrong! Can you get back to a state where the bug was not present. heaven forbid. Rip it up and start again In some projects it is possible that the effort involved in starting again is less than trying to find out what is wrong with a broken solution that you have created. it is happening. In other words I can write programs that I can guarantee will contain no bugs. just that it will not be perfect. But if it does something like always output the first page twice if you do a print using the Chinese font and a certain kind of laser printer this might be regarded as a problem most users could live with. Alternatively. I have found statistics which indicate that "two for one" is frequently to be expected. I start introducing bugs. with inputs. or sometimes destroys the filestore of the host computer. explained the code to a friend and checked all your assumptions then maybe. Part of the job of a project manager in a development is deciding when a product is good enough to sell. Such efforts are always doomed. I have been nearly moved to tears by the sight of people putting in another loop or changing the way their conditions to "see if this will make the program work". This means that you need to evaluate the impact of the faults that get reported to you. Go off and do something different and you may find that the answer will just appear. This does not mean that every program that I write is useless. in that every bug fix will introduce two brand new bugs.9. This means that either the impossible is happening. When considering faults you must also consider their impact. A stopper is a fault which makes the program un-saleable. Programmer’s Point: Bug Fixes Cause Bugs The primary cause of bugs is probably the bug fixing process. just maybe this might be the best way forward. and whether or not a fault in the code is a "stopper" or not. One of the rules by which I work is that "any useful program will have bugs in it". and then introduce the changes until the bug appears. just like throwing a bunch of electrical components at the wall and expecting a DVD player to land on the floor is also not going to work. Alternatively you may find the answer as soon as you come back to the problem. If the program crashes every third time you run it. outputs and some behaviours. in that it can tell you exactly what changes have been made from one version to the next.Advanced Programming Debugging Leave the problem alone for a while. and then look at the changes made since? If the system is failing as a result of a change or. A good Source Code Control System is very valuable here.3 Making Perfect Software There is no such thing as perfect software. This at least makes sure that the fix has not broken anything important. However. try to move back to a point where the bug is not there. such programs will be very small and therefore not be good for much. The only way round this is to make sure that your test process (which you created as a series of lots of unit tests) can be run automatically after you've applied the fix. You also need to be aware of the C# Programming © Rob Miles 2010 182 . a bug fix. One thing that I should make clear at this point is that the process of debugging is that of fixing faults in a solution which should work. In other words you must know how the program is supposed to work before you try and fix problems with what it actually does. Remember that although the bug is of course impossible. As soon as I create a useful program. look carefully at how the introduction of the feature affects other modules in the system. prioritise them and manage how they are dealt with. as it covers the behaviours of a programmer very well indeed: Further Reading Code Complete Second Edition: Steve McConnell Published by Microsoft: ISBN 0-7356-1967-0 Not actually a book about C#. And I've never stopped programming. However.10 The End? This is not all you need to know to be a programmer. but there are quite a few things missing from this text.10. More a book about everything else.edu/howto/HowToBeAProgrammer.mines. 5. 5.10. If you are serious about this business you should be reading at least one book about the subject at any one time. I have been programming for as long as I can remember but I have never stopped learning about the subject. The key to making software that is as perfect as possible is to make sure that you have a good understanding of the problem that you are solving. For example. You should take a look at the following things if you want to become a great C# programmer: serialisation attributes reflection networking 5. How to be a programmer This web site is also worth a read.1 Continuous Development A good programmer has a deliberate policy of constantly reviewing their expertise and looking at new things. If you have any serious intention to be a proper programmer you should/must read/own this book. because we don't have time to teach them all. it is quite a good start. a fault in a video game is much less of a problem than one in an air traffic control system. Read some of the recommended texts at the end of this document for more on this aspect of programming. that you know how to solve it before you start writing code and that you manage your code production process carefully.Advanced Programming The End? context of the development.html C# Programming © Rob Miles 2010 183 . reading books about programming and looking at other people's code. It covers a range of software engineering and programming techniques from the perspective of "software construction". It is not even all you need to know to be a C# programmer. but it does not say how they are to be realised. Whenever you need to collect a number of things into a single unit you should think in terms of creating a class. When the end of the method. It is used in a constructor of a child class to call the constructor in the parent. Note that if the thing being given access to is managed by reference the programmer must make sure that it is OK for a reference to the object is passed out. This means that it is a member of the receipt family (i. Base base is a C# keyword which has different meanings depending on the context in which it is given. In the case of component design an abstract class contains descriptions of things which need to be present. cheque receipt. but you can use it as the basis of. We can therefore create an abstract Receipt class which serves as the basis of all the concrete ones. it can be treated as a Receipt) but it works in its own way. C# Programming © Rob Miles 2010 184 . An accessor is implemented as a public method which will return a value to the caller. Call When you want to use a method. starting at the first statement in its body. abstract one.Glossary of Terms The End? 6 Glossary of Terms Abstract Something which is abstract does not have a "proper" existence as such. It can be used to represent a real world item in your program (for example bank account). or template for. we may decide that we need many different kinds of receipt in our transaction processing system: cash receipt. is reached the sequence of execution returns to the statement immediately following the method call. you call it. Each "real" receipt class is created by extending the parent.e. You can't make an instance of an abstract class. or if it contains one or more method which is marked as abstract. Class A class is a collection of behaviours (methods) and data (properties). It is also used in overriding methods to call the method which they have overridden. For example. When a method is called the sequence of execution switches to that method. When writing programs we use the word to mean "an idealised description of something". If the object is not to be changed it may be necessary to make a copy of the object to return to the caller. wholesaler receipt etc. We don't know how each particular receipt will work inside. Accessor An accessor is a method which provides access to the value managed within a class. in that the data is held securely in the class but code in other classes may need to have access to the value itself. or the return statement. but we do know those behaviours which it must have to make it into a receipt. In C# terms a class is abstract if it is marked as such. Effectively the access is read only. a concrete one. C# Programming © Rob Miles 2010 185 . This means that rather than being thought of in terms of what it is (for example a BabyCustomerAccount) it is thought of in terms of what it can do (implement the IAccount interface to pay in and withdraw money). which produces the executable file which is later run by the host. A collection class will support enumeration which means that it can be asked to provide successive values to the C# foreach construction. Collection The C# library has the idea of a collection as being a bunch of things that you want to store together. The compiler will produce an executable file which is run. Their interactions are expressed in the interfaces between them. Otherwise the compiler will refuse to compile your program.Glossary of Terms The End? Code Reuse A developer should take steps to make sure that a given piece of program is only written once. When creating a system you should focus on the components and how they interact. takes the source which the user has written and then finds all the individual keywords. This is usually achieved by putting code into methods and then calling them. The final phase is the code generator. Compiler A compiler takes a source file and makes sense of it. the pre-processor. Component A component is a class which exposes its behaviour in the form of an interface. Most compilers work in several phases. Cohesion A class has high cohesion if it is not dependent on/coupled to other classes. rather than repeating the same statements at different parts of a program. Constructor A constructor is a method in a class which is called as a new instance of that class is created. One form of a collection is an array.Collections namespace. You only need to override the methods that you want to update. The collection classes can be found in the System. they used to be written in assembly language but are now constructed in high level languages (like C#!). If a class is a member of a hierarchy. The first phase. identifiers and symbols producing a stream of program source which is fed to the "parser" which ensures that the source adheres to the grammar of the programming language in use. Programmers use constructors to get control when an instance is created and set up the values inside the class. The use of class hierarchies is also a way of reusing code. which allows you to easily find a particular item based on a key value in that item. Whenever you want to store a number of things together you should consider using a collection class to do this for you. it is important when making the child that you ensure the parent constructor is called correctly. Another is the hashtable. A compiler is a large program which is specially written for a particular computer and programming language. and the parent class has a constructor. for example all the players in a football team or all the customers in a bank. Writing compilers is a specialised business. is a good example of this. a reference to the instance/class which contains the method and a reference to the method itself. A dependency relationship exists between two classes when a change in code in one class means that you might have to change the other as well. When the event occurs the method is called to deliver notification. Delegates are used to inform event generators (things like buttons. For example a user interface class may be dependent on a business object class (if you add new properties to the business object you will need to update the user interface). Coupling is often discussed alongside cohesion. Delegate A delegate is a type safe reference to a method. timers going tick etc. buttons being pressed. As an example see the discussion of the CustomerAccount and ChildAccount Load method on page 145. Making sure the spec. When a running C# Programming © Rob Miles 2010 186 . Events include things like mouse movement. However. Windows components make use of delegates (a delegate is a type safe reference to a method) to allow event generators to be informed of the method to be called when the event takes place. since it makes it harder to update the system. timers and the like) of the method which is to be called when the event they generate takes place. Exceptions are part of the way that a C# program can deal with errors. However. it is unlikely that changes to the way that the user interface works will mean that the business object needs to be altered. in that you should aim for high cohesion and low coupling. Dependency In general. Dependency is often directional. The fact that a delegate is an object means that it can be passed around like any other. where you try and pick up existing code. It can then be directed at a method in a class which matches that signature. Event An event is some external occurrence which your program may need to respond to. windows being resized. Generally speaking a programmer should strive to have as little coupling in their designs as possible. Many modern programs work on the basis of events which are connected to methods. It usually means that you have not properly allocated responsibility between the objects in your system and that two objects are looking after the same data. Exception An exception is an object that describes something bad that has just happened. too much dependency in your designs is a bad thing. keys being hit. A delegate is created for a particular method signature (for example this method accepts two integers and returns a float). structuring the design so that you can get someone else to do a lot of the work is probably the best example of creative laziness in action. Code reuse. Creative Laziness It seems to me that some aspects of laziness work well when applied to programming. Note that the delegate instance holds two items. is right before you do anything is another way of saving on work.Glossary of Terms The End? Coupling If a class is dependent on another the two classes are said to be coupled. whether the exception // was thrown or not } A try – catch construction can also contain a finally clause. The precise path followed depends on the nature of the job and the techniques in use at the developer. Extending the child produces a further level of hierarchy. Immutable An immutable object cannot be changed. amongst other things. all developments must start with a description of what the system is to do.Glossary of Terms The End? program gets to a position where it just can’t continue (perhaps a file cannot be opened or an input value makes no sense) it can give up and ―throw‖ an exception: throw new Exception("Oh Dear").. The Exception object contains a Message property that is a string which can be used to describe what has gone wrong. The classes at the top of the hierarchy should be more general and possibly abstract (for example BankAccount) and the classes at the lower levels will be more specific (for example ChildBankAccount).. GUID creation involves the use of random values and the date and time. which contains code that is executed whether or not the exception is thrown. however. or FDS. Most operating systems and programmer libraries provide methods which will create GUIDs. If the exception is not ―caught‖ the program will end at that point. and is often called the Functional Design Specification. Functional Design Specification Large software developments follow a particular path. It gives an identifier by which something can be referred to. This is the most crucial item in the whole project. In the above example the message would be set to ―Oh Dear‖.. You can make a program respond to exceptions by enclosing code that might throw an exception in a try – catch construction. from the initial meeting right up to when the product is handed over. A class which implements an interface must contain code for each of the methods. If a method is public it can be called by code other classes. Methods are used to break a large program up into a number of smaller units. Metadata must be gathered by the programmer in consultation with the customer when creating a system. Interface An interface defines a set of actions. as long as it implements the interface it can be thought of purely in terms of that ability. Each particular range of computer processors has its own specific machine code. The difference between a library and a program is that the library file will have the extension . Interfaces make it possible to create components. Machine code Machine Code is the language which the processor of the computer actually understands. The fact that the age value is held as an integer is metadata. A message is delivered to an object by means of a call of a method inside that object. This gives strings a behaviour similar to value types. Inheritance Inheritance is the way in which a class extends a parent to allow it to make use of all the behaviours and properties the parent but add/customise these for a slightly different requirement. We don't care precisely what the component is. Member A member of a class is declared within that class. The method has a particular name and may return a value. It operates at all kinds of levels. which makes them easier to use in programs.dll (dynamic link library) and will not contain a main method. The fact that it cannot be negative is more metadata. A public method is how an object exposes its behaviours. C# Programming © Rob Miles 2010 188 . It contains a number of very simple operations. For more detail see the description of hierarchy. They are also used to allow the same piece of program to be used in lots of places in a large development. It can either do something (a method) or hold some data (variable).Glossary of Terms The End? remains in memory. Methods are sometimes called behaviours. The actions are defined in terms of a number of method definitions. It may also accept a parameter to work on. A class which implements an interface can be referenced purely in terms of that interface. Library A library is a set of classes which are used by other programs. each of which performs one part of the task. or add one to an item in the processor. The string class is immutable. Method A method is a block of code preceded by a method signature. for example move an item from the processor into memory. Data members are sometimes called properties. which means that machine code written for one kind of machine cannot be easily used on another. Metadata Metadata is data about data. Private A private member of a class is only visible to code in methods inside that class. The programmer can then provide methods or C# properties to manage the values which may be assigned to the private members. This may entail providing updated versions of methods in the class. The only reason for not making a data member private is to remove the performance hit of using a method to access the data. Portable When applied to computer software. This is implemented in the form of a public method which is supplied with a new value and may return an error code. year information or by a text string or by a single integer which is the number of days since 1st Jan. Namespace A namespace is an area within which a particular name has a particular meaning. month. for example a date can be set by providing day. A portable application is one which can be transferred to a new processor or operating system with relative ease. not the overridden one in the parent. A fully qualified name of a resource is prefixed by the namespace in which the name exists. High Level languages tend to be portable. C# provides the using keyword to allow namespaces to be "imported" into a program. Namespaces let you reuse names. overloaded. Three different. In that case the SetDate method could be said to have been overloaded. each with the same name. the new method is called. The change will hopefully be managed. in that invalid values will be rejected in some way. A programmer creating a namespace can use any name in that namespace. C# Programming © Rob Miles 2010 189 . Methods are overloaded when there is more than one way of providing information for a particular action. A namespace can contain another namespace. When the method is called on instances of the child class. the more portable something is the easier it is to move it onto a different type of computer. You do this by creating a child class which extends the parent and then overriding the methods which need to be changed. Note that a namespace is purely logical in that it does not reflect where in the system the items are physically located. Computers contain different kinds of processors and operating systems which can only run programs specifically written for them. allowing hierarchies to be set up. Override Sometimes you may want to make a more specialized version of an existing class.Glossary of Terms The End? Mutator A mutator is a method which is called to change the value of a member inside an object. it just gives the names by which they are known. methods could be provided to set the date. You can use the base keyword to get access to the overridden method if you need to. It is conventional to make data members of a class private so that they cannot be changed by code outside the class. machine code is much harder to transfer. Overload A method is overloaded when one with the same name but a different set of parameters is declared in the same class. The signature is the name of the method and the type and order of the parameters to that method: void Silly(int a. An example of a property of a BankAccount class would be the balance of the account. 2) . int b) – has the signature of the name Silly and an float parameter followed by an integer parameter. The reference has a particular name. It is conventional to make the method members of a class public so that they can be used by code in other class. . Reference A reference is a bit like a tag which can be attached to an instance of a class. C# uses a reference to find its way to the instance of the class and use its methods and data.0f.would call the first method. Note that the type of the method has no effect on the signature. Public A public member of a class is visible to methods outside the class. One reference can be assigned to another. . This means that the code: Silly(1.Glossary of Terms The End? Property A property is an item of data which is held in an object. Source file You prepare a source file with a text editor of some kind. It lets you designate members in parent classes as being visible in the child classes.would call the second. whereas: Silly(1. int b) – has the signature of the name Silly and two int parameters. void Silly(float a. It is kind of a half way house between private (no access to methods outside this class) and public (everyone has access). The C# language has a special construction to make the management of properties easy for programmers. Static In the context of C# the keyword static makes a member of a class part of a class rather than part of an instance of the class. Another would be the name of the account holder. Signature A given C# method has a particular signature which allows it to be uniquely identified in a program. Protected A protected member of a class is visible to methods in the class and to methods in classes which extend this class. This means that you don’t need to create an C# Programming © Rob Miles 2010 190 . If you do this the result is that there are now two tags which refer to a single object in memory. It is text which you want to pass through a compiler to produce a program file for execution. 2) . A public method is how a class provides services to other classes. confusingly. The movement might be to a disk file. This means that the first element in the array must have a subscript value of 0. It is not managed by reference. Syntax Highlighting Some program editors (for example Visual Studio) display different program elements in different colours. Subscripts in C# always start at 0 (this locates. for use in non-static methods running inside that instance. This means that if you create a four element array you get hold of elements in the array by subscript values of 0. Subscript This is a value which is used to identify the element in an array. It is used in a constructor of a class to call another constructor. You put your program into a test harness and then the program thinks it is in the completed system.2 or 3. C# Programming © Rob Miles 2010 191 . for example interest rates for all the accounts in your bank. Static members are useful for creating class members which are to be shared with all the instances. Structures are useful for holding chunks of related data in single units. It must be an integer value. the first element of the array) and extend up to the size of the array minus 1. They are not as flexible as objects managed by reference. Structures are also passed by value into methods. Note that the colours are added by the editor. to make it easier for the programmer to understand the code. A test harness is very useful when debugging as it removes the need for the complete system (for example a trawler!) when testing. Streams remove the need to modify a program depending on where the output is to be sent or input received from. but they are more efficient to use in that accessing structure items does not require a reference to be followed in the same way as for an object.1. The best way to regard a subscript is the distance down the array you are going to move to get the element that you want. Stream A stream is an object which represents a connection to something which is going to move data for us.Glossary of Terms The End? instance of a class to make use of a static member. and there is nothing in the actual C# source file that determines the colour of the text. to a network port or even to the system console. Structure A structure is a collection of data items. strings in red and comments in green. Test harness The test harness will contain simulations of those portions of the input and output which the system being tested will use. It is also used as a reference to the current instance. Keywords are displayed in blue. and structures are copied on assignment. It also means that static members are accessed by means of the name of their class rather than a reference to an instance. This this is a C# keyword which has different meanings depending on the context in which it is given. They assume that just because code has been written to do something. In that case I may want to replace (override) the method in the parent with a new one in the child class. For this to take place the method in the parent class must have been marked as virtual. not afterwards when it has crashed.e. Of course. in that the program must look for any overrides of the method before calling it. that thing must be the right thing. Unit tests should be written alongside the development process so that they can be applied to code just after (or in test drive development just before) the code is written. This is why not all methods are made virtual initially. Some other languages are much more relaxed when it comes to combining things. if you really want to impose your will on the compiler and force it to compile your code in spite of any type safety issues you can do this by using casting. Try to put a float value into an int variable and the compiler will get cross at this point. C# Programming © Rob Miles 2010 192 . I think it is important that developers get all the help they can to stop them doing stupid things. i. C# is very keen on this (as am I). x = y causes the value in y to be copied into x. Unit test A unit test is a small test which exercises a component and ensures that it performs a particular function correctly. Value types are passed as values into method calls and their values are copied upon assignment. Making a method virtual slightly slows down access to it. and a language that stops you from combining things in a way that might not be sensible is a good thing in my book.Glossary of Terms The End? Typesafe We have seen that C# is quite fussy about combining things that should not be combined. Sometimes I may want to extend a class to produce a child class which is a more specialized version of that class. Value type A value type holds a simple value. Note that this is in contrast to reference types where the result of the assignment would make x and y refer to the same instance. Only virtual methods can be overridden. Changes to the value in x will not affect the value of y. This kind of fussiness is called type safety and C# is very big on it. One of these mistakes is the use of values or items in contexts where it is either not meaningful to do this (put a string into a bool) or could result in loss of data or accuracy (put a double into a byte).. and work on the basis that the programmer knows best. 26 data protection 112 default 70 default constructor 98 delegates 162 pointers 162 Dictionary 137 double 20 B base method 112.. 22 / /* 38 . 124 case 125 Glossary of Terms 193 . 21 { { 20 + + 23 A abstract classes and interfaces 116 methods 115 references to abstract classes 118 accessor 93.Glossary of Terms Index ( () 20. .. 159 Dispose 161 modal 161 fridge 6 fully qualified name 73 G Generics 134. 98 H hash table 131 Hashtable 132 I identifier 17. 136 global namespace 178 gozzinta 21 graphical user interface 153 GUID 109 N namespace 19.. 52 base method 112 Main 17 overriding 111 replace 113 sealed 114 stopping overriding 114 virtual 111 mutator 91. 53 parenthesis 23 Parse 22 pause 169 plumber 9 pointers 162 print formatting 50 Glossary of Terms 194 .while 43 for 44 while 44 P parameters 22. 177 global 178 nesting 179 separate files 179 using 179 namespaces 73 narrowing 34 nested blocks 58 nesting namespaces 179 new 85. 35 loops 43 break 46 continue 46 do . 31 if 39 immutable 124 information 7 inheritance 109 integers 27 interface abstraction 104 design 108 implementing 106 implementing multiple 108 reference 106 O object class 119 object oriented 15 objects 83. 89.Glossary of Terms operands 33 operators 33 M member protection 91 MessageBox 161 metadata 11 methods 17. 182 programming languages 13 properties 90. 103 Data Structures are Important 89 Delegates are strong magic 164. 67. 93. 85.. 124 comparison 125 editing 125 immutable 124 Length 125 literal 23 StringBuilder 126 structures 79 accessing 80 defining 79 subscripts 62 switch 68. 94 data 95 methods 96 story telling 37 stream 71 streams 141 StreamWriter 72 string 29. 78 Every Message Counts 153 Flipping Conditions 47 Fully Qualified Names are Good 180 Give Your Variables Sensible Names 32 Good Communicators 13 Great Programmers 16 Importance of Hardware 8 Importance of Specification 10 Interfaces are just promises 109 Internationalise your code 104. 87 parameters 56 to abstract class 118 replacing methods 113 return 53 S scope 76. 87 sealed 114 searching 131 semicolon 21 source files 174 Star Trek 7 statement 17 returning values 49 static 19... 69 case 70 System namespace 19 Glossary of Terms 195 .. 126 in interfaces 128 public 92 punctuation 25 R ReadLine 21 recipie 16 reference 84.Glossary of Terms print placeholders 50 priority 33 private 91.. 26 arrays 61 assignment 32 bool 31 char 29 declaring 26 double 20 float 28 list 20 string 30 structures 79 text 29 types 26 verbatim 30 virtual methods 111 void 19 W widening 34 WriteLine 23 Glossary of Terms 196 .
https://www.scribd.com/doc/37699489/Rob-Miles-CSharp-Yellow-Book-2010
CC-MAIN-2017-09
en
refinedweb
Table of Contents. Quick intro: When I first started to learn about Java threading, there was a nice "Ping Pong" example you could look at to get a basic idea of how threading worked. I was surprised when there wasn't a similar tutorial for Akka actors, so I took a little time to write my own.Back to top The SBT build file First up, I created this as an SBT project, so here's my build.sbt file, updated for Scala 2.10.0 and Akka 2.1.1: name := "Akka Ping Pong Example" version := "1.1" scalaVersion := "2.10.0" resolvers += "Typesafe Repository" at "" libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.1.1"Back to top Source code I'll describe the code a little more below, but to get things rolling, here's the source code for my simple Akka actors Ping Pong example: import akka.actor._ case object PingMessage case object PongMessage case object StartMessage case object StopMessage /** * An Akka Actor example written by Alvin Alexander of * * * Shared here under the terms of the Creative Commons * Attribution Share-Alike License: * * more akka info: */ } } } class Pong extends Actor { def receive = { case PingMessage => println(" pong") sender ! PongMessage case StopMessage => println("pong stopped") context.stop(self) } } object PingPongTest extends App { val system = ActorSystem("PingPongSystem") val pong = system.actorOf(Props[Pong], name = "pong") val ping = system.actorOf(Props(new Ping(pong)), name = "ping") // start them going ping ! StartMessage }Back to top Discussion Here are a few quick notes about this example: - As you can see from the import statement, I'm using Akka actors, not the traditional/older Scala actors. - When you implement an Akka actor, you define the receive method, and implement your desired behavior in that method. - Messages between actors should be immutable, and case classes are great for this purpose. - The code in my PingPongTest class shows the two ways to create Akka actors (see the 'val pong' and 'val ping' lines.) I've written more about this in my Simple Scala Akka actors examples tutorial. - I get everything started by sending a StartMessage to my "ping" actor. After that, the two actors bounce messages back and forth as fast as they can until they stop. I hope that brief discussion has been helpful. If you have any questions or improvements, just leave a note in the Comments section below. Add new comment
http://alvinalexander.com/scala/scala-akka-actors-ping-pong-simple-example
CC-MAIN-2017-09
en
refinedweb
Help for this page #include "apr.h" #include "apr_hash.h" ... return( 0 ); } retrieved number 23 = "twenty-three" retrieved number 10 = "ten" retrieved number 13 = "thirteen" Thunder fish Shocky knifefish TBD Electric eels were invented at the same time as electricity Before electricity was invented, electric eels had to stun with gas Results (293 votes). Check out past polls.
http://www.perlmonks.org/index.pl?displaytype=selectcode;node_id=461293
CC-MAIN-2017-09
en
refinedweb
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. RML Reports summation of answers columns I have edited the survey.answer and add a POINTS field.. What I need to do is, when a user answer a question. their is a corresponding point for that, the formula is response * points but then i need to get the sum of all answer, it means i need to have this formula * sum(response * points )* .. I dont know how to do this summation of columns in survey.answer Hello lhadiesleo you can use field.function() which will do the calculation at run time and print the result in your desire field. py file class survey_answer: def _my_point_sum(): calculate your sum here columns={ 'function' : fields.function( _my_point_sum, type='char', string='Points'), } I already do that but it is not working, it still gets the value in the last line of the
https://www.odoo.com/forum/help-1/question/rml-reports-summation-of-answers-columns-42410
CC-MAIN-2017-09
en
refinedweb
Calendar data for new locales843810 Jan 28, 2009 10:06 PM We're developing an aplication on JDK 6. This application needs to support Spanish and Basque. Spanish is not a problem as "es" is a supported locale for the JDK but Basque "eu" is not supported. We've used the new SPI API for defining the Date and Currency Symbols for the eu locale, this works fine. This content has been marked as final. Show 10 replies 1. Re: Calendar data for new locales843810 Jan 28, 2009 11:10 PM (in response to 843810)The easiest way might be to just use ICU. The CLDR data used by ICU has the correct value for first day of week: 2. Re: Calendar data for new locales796365 Jan 29, 2009 2:11 AM (in response to 843810)Java,util.Calendar has the method setFirstDayOfWeek 3. Re: Calendar data for new locales843810 Jan 29, 2009 9:09 AM (in response to 796365)Thanks a lot for your responses, The real problem for my is that i'm using a third-party library in a JSF application that renders the calendar. This component is using the calendar support of the JDK 6 that provides an incorrect first day of week for the "eu" locale. We can not modify the JSF component. 4. Re: Calendar data for new localespietblok Jan 29, 2009 9:40 AM (in response to 843810)You may have a look at the java.text.spi and java.util.spi packages. With these packages you can define your own provider classes, based, for instance, on the ICU4J classes. These classes will be used throughout your JVM, so by third party software as well. I remember having done this once as an experiment. I don't quite remember how to activate it, but I found my source code. Just as an example here how to make use of the com.ibm.icu.text.DateFormatSymbols The provider class: And here the wrapper class: package org.pbjar.icu4j; import java.text.spi.DateFormatSymbolsProvider; import java.util.Locale; import org.pbjar.icu4j.wrap.DateFormatSymbolsWrapper; import com.ibm.icu.text.DateFormatSymbols; /** * Wraps com.ibm.icu.text.DateFormatSymbols. * * @author Piet Blok */ public class ICU4JDateFormatSymbolsProvider extends DateFormatSymbolsProvider { public ICU4JDateFormatSymbolsProvider() { } @Override public Locale[] getAvailableLocales() { return ICU4JLocales.getAvailableLocales(); } @Override public java.text.DateFormatSymbols getInstance(Locale locale) { return new DateFormatSymbolsWrapper(new DateFormatSymbols(locale)); } } Piet package org.pbjar.icu4j.wrap; import com.ibm.icu.text.DateFormatSymbols; /** * Wrapper for com.ibm.icu.text.DateFormatSymbols. * * @author Piet Blok */ public class DateFormatSymbolsWrapper extends java.text.DateFormatSymbols { private static final long serialVersionUID = 1L; DateFormatSymbols symbols; public DateFormatSymbolsWrapper(DateFormatSymbols symbols) { this.symbols = symbols; } @SuppressWarnings("unused") private DateFormatSymbolsWrapper() { } @Override public Object clone() { return new DateFormatSymbolsWrapper((DateFormatSymbols) symbols.clone()); } @Override public boolean equals(Object obj) { return (obj instanceof DateFormatSymbolsWrapper ? symbols .equals((DateFormatSymbolsWrapper) obj) : false); } @Override public String[] getAmPmStrings() { return symbols.getAmPmStrings(); } @Override public String[] getEras() { return symbols.getEras(); } @Override public String getLocalPatternChars() { return symbols.getLocalPatternChars(); } @Override public String[] getMonths() { return symbols.getMonths(); } @Override public String[] getShortMonths() { return symbols.getShortMonths(); } @Override public String[] getShortWeekdays() { return symbols.getShortWeekdays(); } @Override public String[] getWeekdays() { return symbols.getWeekdays(); } @Override public String[][] getZoneStrings() { return symbols.getZoneStrings(); } @Override public int hashCode() { return symbols.hashCode(); } @Override public void setAmPmStrings(String[] newAmpms) { symbols.setAmPmStrings(newAmpms); } @Override public void setEras(String[] newEras) { symbols.setEras(newEras); } @Override public void setLocalPatternChars(String newLocalPatternChars) { symbols.setLocalPatternChars(newLocalPatternChars); } @Override public void setMonths(String[] newMonths) { symbols.setMonths(newMonths); } @Override public void setShortMonths(String[] newShortMonths) { symbols.setShortMonths(newShortMonths); } @Override public void setShortWeekdays(String[] newShortWeekdays) { symbols.setShortWeekdays(newShortWeekdays); } @Override public void setWeekdays(String[] newWeekdays) { symbols.setWeekdays(newWeekdays); } @Override public void setZoneStrings(String[][] newZoneStrings) { symbols.setZoneStrings(newZoneStrings); } } 5. Re: Calendar data for new locales843810 Jan 29, 2009 10:16 AM (in response to pietblok)Thanks Piet, We managed to localize the names of days and moths using the SPI extensión, in our case we are using an specific extension for Basque language. The problem is that the SPI does not include information about the first day of the week, this info seems to be located at sun.util.resources.CalendarData. We try to find a way to add a new CalendarData resource for the "eu" locale. Juanjo 6. Re: Calendar data for new localespietblok Jan 29, 2009 10:43 AM (in response to 843810)Ah, Create a properties file with the name: sun/util/resources/CalendarData_eu_ES.properties and have this file in your classpath, either by putting it in a jar, or, by having it in a directory that is mentioned in your classpath. Two key-value pairs: Is this what you wanted to know? # manually edited resource fbundle for eu_ES (Basque) firstDayOfWeek=2 minimalDaysInFirstWeek=4 Piet 7. Re: Calendar data for new locales843810 Jan 29, 2009 3:08 PM (in response to pietblok)Yes, we try but it does not work. We tested with a properties file and with a ListResourceBundle but the JDK is not taking this bundles. The question is that I try to retrieve the Bundle in the ususal way ResourceBundle.getBundle("sun.util.resources.CalendarData",new Locale("eu","ES")) and it works. IT seems that the JDK only takes the locales supported by default. Any idea? Thanks, Jaunjo 8. Re: Calendar data for new localespietblok Jan 29, 2009 3:30 PM (in response to 843810)That's a pity. I remember once having encountered a similar problem: I created properties files for resource bundles targeted at the Swing classes (for the Dutch language). When running as a desktop application, everything ran fine and I got Swing completely translated into Dutch. However, when deployed as a web start application (on a Dutch box ofcourse) it didn't work, and I got the default Emglish version. I never found out why. Sorry, Piet 9. Re: Calendar data for new locales843810 Mar 3, 2009 1:03 PM (in response to pietblok)I also have tryed creating a class un.text.resources.LocaleElements_xx_XX to test a locale of my own, and it does not work, only if i create the resource bundle via an explicit call to LocaleData.getLocaleElements it does take the parameter defined inside this class. 10. Re: Calendar data for new locales843810 Sep 27, 2009 7:25 PM (in response to 843810)Hi, Have you guys found any solution to the problem? The SPI extension api is great for adding new locale specific data but it leaks firstDayOfWeek and minimalDaysInFirstWeek functionality. br David
https://community.oracle.com/thread/1286562?tstart=105
CC-MAIN-2017-13
en
refinedweb
i want to determine the day (sunday, monday, etc..) of a given date (ex: august 3rd, 2005). i have written a function which count the number of days into the year that the date is...example, feb 1st is 32 days into the year. i can't figure out how to do this though... i know that jan 1st, 1900 was a tuesday, but i really have no idea what to do with that . any suggestions? also, i posted the code below because it seemed too easy and produced the right output the very first time.... any insight on possible errors which might occur in special cases? month, day, and year will always have valid values Code://declared in date.h int Date::month; int Date::day; int Date::year; //dummy function until i confirm it's accuracy bool Date::isLeap(void) { return !(year % 4); } int Date::daysIntoYear(void) { if(month == 1) return day; int count = 31; int lastMonth = 31; for(int i = 2; i < month; i++) { if(lastMonth == 31) //if the last month had { //31 days, this month //has 30 days if(i != 8) ///<--unless this month { //is august lastMonth = 30; } count += lastMonth; }else{ lastMonth = 31; count += lastMonth; } } if(month > 2) //if past Feb, remove { //1 or 2 days (if leap 1, else 2) if(isLeap()){ count--; }else{ count -= 2; } } return (count + day); }
https://cboard.cprogramming.com/cplusplus-programming/57691-determing-day-given-date.html
CC-MAIN-2017-13
en
refinedweb
Hello Mr. Kay I'd like to process small to medium sized XML documents with virtually one open-sized XSLT stylesheet. The structure of the different input documents should be able to evolve and grow independently from the process itself. The process should be able to handle any new namespace and element type with the addition of corresponding template matches. Since such a all-mighty stylesheet would soon grow too big, I would like to break it down, for example by namespace: 1) The process first scans the input document for all the namespaces contained. Then it dynamically builds a stylesheet, importing the according stylesheets per namespace. The result gets compiled and the input transformed. 2) The process scans the input document for the namespaces contained and builds a pipeline with the pre-compiled stylesheets, handling these namespaces. The input gets transformed step-by-step. 3) The process starts with the stylesheet for the root namespace. For all the unknown namespaces transforms the node with the pre-compiled stylesheet for the according namespace via the saxon:transform() extension. Every "foreign" node gets transformed separatly. Which approach do you think performs best? do you have ideas for another approach? The number of namespaces within one input document is only a small subset of the possible overall selection. Some namespaces appear more often, others very seldom. A proper cache management would prevent the process from pre-compiling all the stylesheets in a long term, wide coverage usage. Thanks, Bruno
https://sourceforge.net/p/saxon/discussion/94026/thread/ff13b355/
CC-MAIN-2017-13
en
refinedweb
ompl::geometric::BITstar::SearchQueue Class Reference A queue of edges to be processed that integrates both the expansion of Vertices and the ordering of the resulting edges. More... #include <ompl/geometric/planners/bitstar/datastructures/SearchQueue.h> Detailed Description A queue of edges to be processed that integrates both the expansion of Vertices and the ordering of the resulting edges. - Short Description - A two-stage queue that consists of vertices expanded into edges to be processed. The queue consists of a vertex expansion queue and an edge processing queue. Vertices are expanded as needed from the vertex queue into edges places in the edge queue. Edges are removed from the edge queue for processing by BIT*. The vertex queue is implemented as a static ordered list of the vertices in the graph with a token (i.e., an iterator) pointing to the next vertex that needs to be expanded. This is specifically a multimap ordered on ompl::base::Cost. The edge queue is implemented as an ordered list of potential edges. It is filled by the vertex queue and emptied by popping the best value off the front. It is specifically a multimap ordered on std::pair<ompl::base::Cost, ompl::base::Cost> - Notes: - An eraseEdge() function could be made by mimicking the vertex -> vertexQueue_::iterator lookup datastructure for the edgeQueue_ Definition at line 90 of file SearchQueue.h. The documentation for this class was generated from the following files: - ompl/geometric/planners/bitstar/datastructures/SearchQueue.h - ompl/geometric/planners/bitstar/datastructures/src/SearchQueue.cpp
http://ompl.kavrakilab.org/classompl_1_1geometric_1_1BITstar_1_1SearchQueue.html
CC-MAIN-2017-13
en
refinedweb
- Instantiation Modes It is possible to extend Butterfly Container Script (BCS) with custom instantiation modes, if the standard modes (new instance, singleton etc.) don't suffice. This text gives the following examples of custom instantiation modes: Injecting Current HttpServletRequest and HttpSession One situation in which the standard instantiation modes may not suffice is when processing HTTP requests in a web application. When processing an HTTP request you may need to instantiate objects which have the current HttpServletRequest or HttpSession objects injected into them. Since the request and session objects change between requests you cannot use the singleton instantiation mode. Neither can you use the new instance mode, because the request object to obtain from a given factory should be the same for as long as the request is being processed. The solution to this problem is to create a HttpRequestCache which associates the thread processing the HTTP request with the HttpServletRequest object representing the request being processed. In other words, maps the thread to the request it processes. Here is the HttpRequestCache class definition: public class HttpRequestCache{ Map requests = new ConcurrentHashMap (); public void set(HttpServletRequest request){ requests.put(Thread.currentThread(), } public HttpServletRequest get(){ return requests.get(Thread.currentThread()); } public void remove(){ requests.remove(Thread.currentThread()); } By calling the set() method with the current request as parameter, the request is associated with the thread calling the set() method. By calling the get() method the request object associated with the calling thread can be obtained. To integrate this into BCS and the container you will have to define three factories: requestCache = 1 com.myapp.HttpRequestCache(); request = * requestCache.get(); session = * request.getSession(); The "requestCache" factory defines an instance of HttpRequestCache as a singleton. The "request" factory is defined as a call to the get() method on the product returned from the "requestCache" factory. In other words, as a call to the get() method on the HttpRequestCache singleton. The "session" factory is defined as a call to the getSession() method of the product returned by the "request" factory. In other words, as a call to the getSession() method on the request object obtained from the HttpRequestCache singleton, which is the request object associated with the calling thread. Using the request and session factories in a script is like using any other factory. Here is an example: myAction = * com.myapp.MyAction(request, session); In order to make the the request and session factories return the correct objects you must first call the HttpRequestCache's set() method. After that you can obtain an instance from the myAction factory with the correct request and session objects injected. Here is how that looks in Java: ((HttpRequestCache) container.instance("requestCache")).set(request); MyAction action = container.instance("myAction"); Finally it is probably a good idea to remove the request object from the cache when the request processing is done. That is done like this in Java: ((HttpRequestCache) container.instance("requestCache")).remove();
http://tutorials.jenkov.com/butterfly-container/extending-bcs-with-instantiation-modes.html
CC-MAIN-2017-13
en
refinedweb
I have a python program. It stores a variable called "pid" with a given pid of a process. First of all I need to check that the process which owns this pid number is really the process I'm looking for and if it is I need to kill it from python. So first I need to check somehow that the name of the process is for example "pfinder" and if it is pfinder than kill it. I need to use an old version of python so I can't use psutil and subprocess. Is there any other way to do this? You can directly obtain this information from the /proc file system if you don't want to use a separate library like psutil. import os import signal pid = '123' name = 'pfinder' pid_path = os.path.join('/proc', pid) if os.path.exists(pid_path): with open(os.join(pid_path, 'comm')) as f: content = f.read().rstrip('\n') if name == content: os.kill(pid, signal.SIGTERM) .
https://codedump.io/share/FciLUXmiAPB2/1/get-the-process-name-by-pid
CC-MAIN-2017-13
en
refinedweb
I am using a text file to store the last time data was pulled from an API. After I check if new data should be pulled I am updating the last datapoint with this Python 2.7 code: if pullAgain == True: # open last time again lasttimedata = open('lasttimemultiple.txt', 'a+') for item in splitData: if item[0:2] == PullType: #formats the data point newTime = PullType + ':' + currenttime #trying to write that data point to the spot of the old point. lasttimedata.write(newTime) print('We updated the last time') lasttimedata.close() # close last time splitdata[item] splitdata splitdata[item] splitdata item item splitdata = ['00:23:15:42','01:15:12:54','02:12:23:54'] #Pull type is the piece of data being pulled, # capability to Have 99 types, current default is 00. def PullAgain(PullType): # This is the variable that decides if the API is called # again, True = pull data again. pullAgain = False # Calls the local time s1=time.localtime() #takes the hours, minutes and seconds out of the time currenttime = str(s1[3])+':'+str(s1[4])+':'+str(s1[5]) #opens the file that contains the last time run timefile = open('lasttimemultiple.txt','r+') #reads the last time file rawfile = timefile.read() #splits the string into each individual row splitData = string.split(rawfile,'\n') #closes last time timefile.close() lasttime = "05:06:12" for item in splitData: if item[0:2] == PullType: lasttime = str(item[3:]) print('We made it into the if statement') print lasttime #this is the time formatting FMT = '%H:%M:%S' #calculates the difference in times delta = ( datetime.strptime(currenttime, FMT) - datetime.strptime(lasttime, FMT)) #converts the difference into a string tdelta = str(delta) print 'this is tdelta before edit:',tdelta if tdelta[0] =='-': tdelta = tdelta[8:] print 'tdelta time has been adjusted', tdelta #if more than 0 hours apart if int(tdelta[0])>0: #Then call api again pullAgain = True elif int(tdelta[2])>=3: #if time is greater than 29 sec call api again pullAgain = True else: pullAgain = False print('New data not pulled, the time elapsed since last pull was: '),tdelta splitData2 = [] if pullAgain == True: # open last time again lasttimedata = open('lasttimemultiple.txt', 'a+') for item in splitData: if item[0:2] == PullType: newTime = PullType + ':' + currenttime splitData2.append(item) lasttimedata.write(splitData2) print('We updated the last time') lasttimedata.close() # close last time return pullAgain#return the decission to pull again or not There is two ways for doing that: Keep a counter to know witch element to edit: for index, item in enumerate(splitData): splitData[item] = new_value But your are editing the list while iterating, and that is not always a great idea. Create an output list will the element you want: output_list = [] for item in splitData: if i_want_to_keep: output_list.append(item) else: output_list.append(new_value) I think that the best way of doing it is: with open(filename, 'w') as f: for element in my_list: f.write(element) Please consider this code: splitData2 = [] if pullAgain == True: # Change in splitData all the times that need to be update for item in splitData: newTime = PullType + ':' + currenttime if item[0:2] == PullType: splitData2.append(newTime) print('We updated the last time') # ReWrite the whole file with the whole data from splitData2 with open('lasttimemultiple.txt', 'w') as f: for item in splitData2: f.write(item) I Hope that is going to help.
https://codedump.io/share/pMmJkhRqFvoP/1/modifying-string-in-a-text-file
CC-MAIN-2017-13
en
refinedweb
Let’s say you have a web application written in NodeJS and you want to test it. What’s the best way to go about that? Fortunately, this is a common enough problem that there are modules and recipes to go along with it. Separating Express from HTTP ExpressJS contains syntactic sugar to implement a complete web service. You will commonly see code like this: var express = require('express'); var app = express(); // Do some other stuff here app.listen(3000); Unfortunately, this means that you have to be doing HTTP calls to test the API. That’s a problem because it doesn’t lend itself to easily being tested. Fortunately, there is an easier way. It involves separating the express application from the HTTP logic. First of all, let’s create a web-application.js file. Here is mine: import bodyParser from 'body-parser'; import compression from 'compression'; import express from 'express'; import logCollector from 'express-winston'; import staticFiles from 'serve-static'; import logger from './lib/logger'; import apiRoute from './routes/api'; /** * Create a new web application * @param {boolean} [logging=true] - if true, then enable transaction logging * @returns {express.Application} an Express Application */ export default function webApplication(logging = true) { // Create a new web application let webApp = express(); // Add in logging if (logging) { webApp.use(logCollector.logger({ winstonInstance: logger, colorStatus: true, statusLevels: true })); } // Add in request/response middleware webApp.use(compression()); webApp.use(bodyParser.urlencoded({ extended: true })); webApp.use(bodyParser.json()); // Routers - Static Files webApp.use(staticFiles('wwwroot', { dotfiles: 'ignore', etag: true, index: 'index.html', lastModified: true })); // Routers - the /api route webApp.use('/api', apiRoute); // Default Error Logger - should be added after routers and before other error handlers webApp.use(logCollector.errorLogger({ winstonInstance: logger })); return webApp; } Yes, it’s written in ES2015 – I do all my work in ES2015 right now. The export is a function that creates my web application. I’ve got a couple of extra modules – an api route (which is an expressjs router object) and a logging module. Note that I’ve provided a logging parameter to this function. Setting logging=false turns off the transaction logging. I want transaction logging when I am running this application in production. That same logging gets in the way of the test results display when I am running tests though. As a result, I want a method of turning it off when I am testing. I also have a http-server.js file that does the HTTP logic in it: import http from 'http'; import logger from './lib/logger'; import webApp from './web-application'; webApp.set('port', process.env.PORT || 3000); logger.info('Booting Web Application'); let server = http.createServer(webApp()); server.on('error', (error) => { if (error.syscall !== 'listen') { throw error; } if (error.code) { logger.error(`Cannot listen for connections (${error.code}): ${error.message}`); throw error; } throw error; }); server.on('listening', () => { let addr = server.address(); logger.info(`Listening on port ${addr.family}/(${addr.address}):${addr.port}`); }); server.listen(webApp.get('port')); This uses the Node.JS HTTP module to create a web server and start listening on a TCP port. This is pretty much the same code that is used by ExpressJS when you call webApp.listen(). Finally, I have a server.js file that registers BabelJS as my ES2015 transpiler and runs the application: require('babel-register'); require('./src/http-server'); The Web Application Tests I’ve placed all my source code in the src directory (except for the server.js file, which is in the project root). I’ve got another directory for testing called test. It has a mocha.opts file with the following contents: --compilers js:babel-register This automatically compiles all my tests from ES2015 using BabelJS prior to executing the tests. Now, for the web application tests: /// <reference path="../../typings/mocha/mocha.d.ts"/> /// <reference path="../../typings/chai/chai.d.ts"/> import { expect } from 'chai'; import request from 'supertest'; import webApplication from '../src/web-application'; describe('src/web-application.js', () => { let webApp = webApplication(false); it('should export a get function', () => { expect(webApp.get).to.be.a('function'); }); it('should export a set function', () => { expect(webApp.set).to.be.a('function'); }); it('should provide a /api/settings route', (done) => { request(webApp) .get('/api/settings') .expect('Content-Type', /application\/json/) .expect(200) .end((err) => { if (err) { return done(err); } done(); }); }); }); First note that I’m creating the web application by passing the logging parameter of false. This turns off the transaction logging. Set it to true to see what happens when you leave it on. You will be able to see quite quickly that the test results get drowned out by the transaction logging. My http-server.js file relies on a webApp having a get/set function to store the port setting. As a result, the first thing I do is check to see whether those exist. If I update express and they decide to change the API on me, these tests will point that out. The real meat is in the third (highlighted) test. This uses supertest – a WebAPI testing facility that pretends to be the HTTP module from Node, listening on a port. You send requests into the webApp using supertest instead of the HTTP module. ExpressJS handles the request and sends the response back to supertest and that allows you to check the response. There are two parts to the test. The first is the construction of an actual request: request(webApp) .get('/api/settings') Supertest uses superagent underneath to actually do the requests. Once you have linked in the ExpressJS application, you can send a GET, POST, DELETE or any other verb. DELETE is a special case because it is a reserved word – use del() instead: request(webApp) .del('/tables/myTable/1') You can add custom headers. For example, I do a bunch of work with azure-mobile-apps – I can test that with: request(webApp) .set('ZUMO-API-VERSION', '2.0.0') .get('/tables/myTable/1') The second part of the request is the assertions. You can assert on anything – a specific header, status code or body content. For example, you might want to assert on a non-200 response: request(webApp).get('/api/settings') .expect(200) You can also expect a body. For example: request(webApp).get('/index.html') .expect(/<html>/) Note the use of the regular expression here. That pattern is really common. You can also check for a specific header: request(webApp).get('/index.html') .expect('X-My-Header', /value/); Once you have your sequence of tests, you can close out the connection. Since superagent and supertest are asynchronous, you need to handle the test asynchronously. That involves passing in a parameter of ‘done’ and then calling it after the test is over. You pass a callback into the .end() method: request(webApp).get('/index.html') .expect('X-My-Header', /value/) .end((error) => { done(error); }); Wrapping up The supertest module, when combined with mocha, allows you to run test suites without spinning up a server and that enables you to increase your test coverage of a web service to almost 100%. With this, I’ll now be able to test my entire API surface automatically.
https://shellmonger.com/tag/mocha/
CC-MAIN-2017-13
en
refinedweb
An LDAP v3 Client Library for Dart The Lightweight Directory Access Protocol (LDAP) is a protocol for accessing directories. An LDAP directory is organised as a hierarchy of entries, where one or more root entries are allowed. Each entry can be identified by a distinguished name, which is an ordered sequence of attribute/value pairs. Each entry contains a set of attributes. Attributes have a name and are associated with a set of one or more values (i.e. attributes can be repeated and are unordered). This library can be used to query (search for and compare entries) and modify (add, delete and modify) LDAP directories. This library supports the LDAP v3 protocol, which is defined in IETF RFC 4511. Breaking changes from previous versions are described at the bottom of this page. Using dartdap Search example To perform operations on an LDAP directory, the basic process is: - Create an LDAP connection ( LdapConnection). - Perform LDAP operations ( search, add, modify, modifyDN, compare, delete). - Close the connection ( import 'dart:async'; import 'package:dartdap/dartdap.dart'; Future example() async { // Create an LDAP connection object var host = "localhost"; var ssl = false; // true = use LDAPS (i.e. LDAP over SSL/TLS) var port = null; // null = use standard LDAP/LDAPS port var bindDN = "cn=Manager,dc=example,dc=com"; // null=unauthenticated var password = "[email protected]"; var connection = new LdapConnection(host: host); connection.setProtocol(ssl, port); connection.setAuthentication(bindDN, password); try { // Perform search operation var base = "dc=example,dc=com"; var filter = Filter.present("objectClass"); var attrs = ["dc", "objectClass"]; var count = 0; var searchResult = await connection.search(base, filter, attrs); await for (var entry in searchResult.stream) { // Processing stream of SearchEntry count++; print("dn: ${entry.dn}"); // Getting all attributes returned for (var attr in entry.attributes.values) { for (var value in attr.values) { // attr.values is a Set print(" ${attr.name}: $value"); } } // Getting a particular attribute assert(entry.attributes["dc"].values.length == 1); var dc = entry.attributes["dc"].values.first; print("# dc=$dc"); } print("# Number of entries: ${count}"); } catch (e) { print("Exception: $e"); } finally { // Close the connection when finished with it await connection.close(); } } Create an LDAP connection The first step is to instantiate an LdapConnection object using its constructor. These properties of the connection can be changed from their defaults: - hostname (defaults to "localhost"); - ssl: false is plain LDAP, true is LDAPS (LDAP over SSL/TLS) (defaults to false); - port: port number (defaults to standard port for LDAP/LDAPS: 389 or 636); - bindDN: distinguished name for binding, null means unauthenticated (default is null); - password: password for binding. These properties can be set using named parameters to the constructor, or with the setProtocol and setAuthentication methods. Perform LDAP operations This example performs a search operation. The search method returns a Future to a SearchResult object, from which a stream of SearchEntry objects can be obtained. The results are obtained by listening to the stream (which in the example is done using the "await for" syntax). The SearchEntry contains the entry's distinguished name and the attributes returned. The dn is a String. The attributes is a Map from the name of the attribute (a String) to an Attribute. An Attribute has a values member, which returns a Set of the values of the attribute. It is a Set because LDAP allows attributes to have multiple values. It also has a name member, which is the name of the attribute as a String. Close the connection When finished with the connection, call the close method. In the above example, the close is performed in the finally section, to ensure it gets closed even if an exception is thrown. The close method returns a Future, which completes when the connection is completely closed. Adding entries try { var attrs = { "objectClass": ["organizationalUnit"], "description": "Example organizationalUnit entry" }; await ldap.add("ou=Engineering,dc=example,dc=com", attrs); } on LdapResultEntryAlreadyExistsException catch (_) { // cannot add entry because it already exists } on LdapException catch (e) { // some other problem } Modifying entries try { var mod1 = new Modification.replace("description", ["Engineering department"]); await ldap.modify("ou=Engineering,dc=example,dc=com", [mod1]); } on LdapResultObjectClassViolationException catch (_) { // cannot modify entry because it would violate the schema rules } on LdapException catch (e) { // some other problem } Moving entries try { await ldap.modifyDN(oldDN, newDN); } on LdapException catch (e) { // some other problem } Comparing entries try { r = await ldap.compare("ou=Engineering,dc=example,dc=com", "description", "Engineering Dept"); if (r.resultCode == ResultCode.COMPARE_FALSE) { } else if (r.resultCode == ResultCode.COMPARE_TRUE) { } else { assert(false); } } on LdapException catch (e) { // some other problem } Deleting entries try { await ldap.delete("ou=Business Development,dc=example,dc=com"); } on LdapResultNoSuchObjectException catch (_) { // entry did not exist to delete } on LdapException catch (e) { // some other problem } Connecting and authenticating The LdapConnection can operate in automatic or manual modes. The mode can be set when it is created, or by using the setAutomaticMode method. In automatic mode (the default), it is not necessary to explicitly connect or send LDAP BIND requests. In automatic mode, the connection to the LDAP directory will be established whenever it is needed. This will occur when the first LDAP operation is performed. If it becomes disconnected (e.g. LDAP server timeout), it will also re-establish the connection when the next LDAP operation is performed. In automatic mode, LDAP BIND requests will be made when necessary. For example, if a bindDN and password has been set (via the constructor, or the setAuthentication and setAnonymous methods), an LDAP BIND request will be sent when the first LDAP operation is performed: obviously, after the connection has been established and before the operation's request. There are open and bind methods to explicitly cause the connection to be made and LDAP BIND request to be sent. But since these are performed automatically, using them is optional in automatic mode. However, an application might want to explicitly use them to check the connection/authentication parameters; rather than have the errors detected later when an LDAP operation is performed. In manual mode, opening the connection and sending LDAP BIND requests must be explicitly performed by the application. Exceptions will be raised if the application fails to do this (e.g. attempting to perform a search with a closed connection). In manual mode, if a disconnection occurs subsequent LDAP operations will fail unless the application re-opens the connection. It is expected that most applications will use automatic mode. The state property indicates what state the connection is in. See the documentation of LdapConnection for more details. Exceptions Methods in the package throws exceptions which are subclasses of the LdapException abstract class. See the documentaiton of LdapException for more details. Logging This package uses the Dart logging package for logging. The logging is mainly useful for debugging the package. Loggers The following loggers are used: Logger: ldap.control - finest = parsing of controls Logger: ldap.session - warnings = certificate issues - fine = connections successfully established, and closing them - finer = details about attempts to establish a connection Logger: ldap.send.ldap for the LDAP messages sent. - fine = LDAP messages sent. - finest = details of LDAP message construction Logger: ldap.send.bytes for the raw bytes sent to the socket. Probably only useful when debugging the dartdap package. - severe = errors/exceptions when sending - fine = number of raw bytes sent Logger: ldap.recv.ldap for the LDAP messages receive (i.e. received ASN.1 objects processed as LDAP messages). - fine = LDAP messages received. - finer = LDAP messages processing. Logger: ldap.recv.asn1 for the ASN.1 objects received (i.e. parsed from the raw bytes received). Probably only useful when debugging the dartdap package. - fine = ASN.1 messages successfully parsed from the raw bytes - finest = shows the actual bytes making up the value of the ASN.1 message Logger: ldap.recv.bytes for the raw bytes received from the socket. Probably only useful when debugging the dartdap package. - fine = number of raw bytes read - finer = parsing activity of converting the bytes into ASN.1 objects - finest = shows the actual bytes received and the number in the buffer to parse Logging Examples To take advantage of the hierarchy of loggers, enable hierarchicalLoggingEnabled and set the logging level on individual loggers. If the logging level is not explicitly set on a logger, it is inherited from its parent. The root logger is the ultimate parent; and its logging level is initally Level.INFO. For example, to view high level connection and LDAP messages send/received: import 'package:logging/logging.dart'; ... Logger.root.onRecord.listen((LogRecord rec) { print('${rec.time}: ${rec.loggerName}: ${rec.level.name}: ${rec.message}'); }); hierarchicalLoggingEnabled = true; new Logger("ldap.session").level = Level.FINE; new Logger("ldap.send.ldap").level = Level.FINE; new Logger("ldap.recv.ldap").level = Level.FINE; To debug messages received: new Logger("ldap.recv.ldap").level = Level.ALL; new Logger("ldap.recv.asn1").level = Level.FINER; new Logger("ldap.recv.bytes").level = Level.FINE; Note: in the above examples: SHOUT, SEVERE, WARNING and INFO will still be logged (except for those loggers and their children where the level has been set to Level.OFF). To disable those log messages change the root logger from its default of Level.INFO to Level.OFF. For example, to suppress all log messages (including suppressing SHOUT, SEVERE, WARNING and INFO): Logger.root.level = Level.OFF; Or leave the root level at the default and only disable logging from the package: new Logger("ldap").level = Level.OFF; Breaking changes Version 0.1.x to 0.2.x LdapConnectionchanged to support automatic connection/reconnections (and authentication when needed). This allows connections to be safely reused (i.e. kept open for later operations without having to re-open the connection). Previously, there was no guarantee a previously working connection would still be working when an LDAP operation was performed later: it could have been disconnected by intermittent network errors or LDAP server timeouts. Previously, the only safe way to use a connection was to open one for each LDAP operation (which is very inefficient) or to always expect LDAP operations could fail and to open a new connection if it fails (verbose and inelegant code). The searchmethod returns a Future to a SearchResult. Previously, it returned the SearchResult synchronously. This change was necessary because (with the introduction of automatic connections) a search could cause the connection to be opened, and bind request to be sent, before the search request is actually sent. Renaming of other classes and methods to consistently follow the Dart naming conventions. For example, LDAPConnectionbecomes LdapConnection, LDAPResultbecomes LdapResult, LDAPUtilbecomes LdapUtil. Exception raised if a bad certificate is encountered when opening a SSL/TLS connection. Provide a bad certificate handler function, if the application wants to override the default behaviour. Other than for testing, accepting bad certificates is a security risk: so, the default behaviour is the safer option. Internal classes hidden from public interface (e.g. ConnectionManager, LDAPUtil). LDAPConfigurationremoved. Version 0.0.x to 0.1.x Library is now called "dartdap" instead of "ldap_client". There was a disconnect in the naming: package X was imported, but only library Y was imported. That would have been ok if it had multiple libraries, but it currently only contains one publicly visible library. Also, many of the classes could apply an LDAP server too. LDAPExceptionrenamed to LdapExceptionto follow the Dart naming conventions. New exception classed defined for all the LDAP result error conditions. All LDAP operations now throws these new exceptions. Instead of checking the resultCode in the LDAPResult returned by the LDAP operations, catch the new exceptions. SocketExceptionexceptions are now being internally caught and thrown as LdapSocketExceptionobjects. This make it easier to detect common failure conditions. Instead of catching SocketException, catch the new LdapSocketExceptionor one of its subclasses. LDAPConfigurationis deprecated. Programs should use whatever configuration mechanism they normally use (e.g. databases or configuration files) rather than having to use a special configuration mechanism only for dartdap (and still having to use the other configuration mechanism for the rest of the program). It is also unsafe due to a race condition that could occur if multiple connections are being established. Internal organisation of libraries/imports/exports have been cleaned up. This should not be noticable by existing code, unless it was directly referencing those internal libraries or files.
https://www.dartdocs.org/documentation/dartdap/0.2.0/index.html
CC-MAIN-2017-13
en
refinedweb
Everybody talks about Monads when they mention Haskell, so I got a bit ahead of myself and wanted to see something of what they’re about. No, don’t worry, I’m not aspiring to yet another Monad tutorial. I feel I have a ways to go before I’m ready to craft my own light-saber. I did read about 10 Monad articles on the Web, and found myself more confused when I came out than when I went in. Today’s exercise took about 5-6 hours of pure frustration, before a kind soul on IRC finally set me straight. It sure is difficult when getting past a single compiler error takes you hours. That bedeviled cat Most geeks know about Schrödinger’s cat, the fated beast who, when put into a box with a random source tied to a deadly gas trigger, remains in a state of quantum superposition in which he’s neither alive nor dead until someone opens the box to look. Well, people kept saying that Monad are like “computational containers”, so I wanted to model the following: - There is a Schroedinger Monad into which you can put a Cat. - When you create the Monad, it is Unopened, and the Cat’s has no state. - You also pass in a random generator from the outside world. This involves another Monad, the IO Monad, because randomness relates to the “world outside”. - As long as you don’t use the monad object, the Cat’s is neither Dead nor Live. - As soon as you peek into the box, or use it in any calculation, the Cat’s fate is decided by a roll of the dice. When I run the program ten times in a row, here’s what I get: Opened (Live (Cat "Felix")) Opened Dead Opened Dead Opened Dead Opened Dead Opened (Live (Cat "Felix")) Opened Dead Opened Dead Opened (Live (Cat "Felix")) Opened (Live (Cat "Felix")) Let’s look at the code, and where I had troubles writing it. A flip of the coin The first function flips a coin and returns True or False to represent Heads or Tails: import System.Random flipCoin :: StdGen -> Bool flipCoin gen = fst $ random gen The sugar fst $ random gen is just shorthand for fst (random gen). There is no difference, I was just playing with syntax. You do need to pass in a valid random generator, of type StdGen, for the function to work. Cats data Cat = Cat String deriving Show data Probable a = Dead | Live a deriving Show These two types let me make Cats out of Strings, along with a Probable type which models a Live thing or a Dead thing. It treats all Dead things as equal. I can create a Live Cat with: felix = Live (Cat "Felix") Following my “fun with syntax” up above, I could also have written: felix = Live $ Cat "Felix" It doesn’t matter which. The $ character is the same as space, but with much lower precedence so that parentheses aren’t needed around the argument. If there were no parens, it would look like I was calling Live with two separate arguments: Cat and "Felix". Flipping a Cat flipCat :: StdGen -> a -> Probable a flipCat gen cat = if flipCoin gen then Live cat else Dead When I have a Cat, I can subject it to a coin toss in order to get back a Live Cat or a Dead one. I should probably have called this function randomGasTrigger, but hey. The type of the function says that it expects a random generator (for flipCoin), some thing, and returns a Probable instance of that thing. The Probable means “can be Live or Dead”, according to how I defined the type above. The rest of the function is pretty clear, since it looks a lot like its imperative cousin would have. Bringing in Schroedinger data Schroedinger a = Opened (Probable a) | Unopened StdGen a deriving Show This type declaration is more complicated. It creates a Schroedinger type which has two data constructors: an Opened constructor which takes a Probable object – that is, whose Live or Dead state is known – and an Unopened constructor which takes a random generator, and an object without a particular state, such as a Cat. Some values I could create with this type: felix = Opened (Live (Cat "Felix")) -- lucky Felix poorGuy = Opened Dead -- DOA unknown = Unopened (mkStdGen 100) (Cat "Felix") In the third case, the idea is that his fate will be determined by the random generator created with mkStdGen 100. However, I want a real random source, so I’m going to get one from the environment later. Here comes the Monad instance Monad Schroedinger where Opened Dead >>= _ = Opened Dead Opened (Live a) >>= f = f a Unopened y x >>= f = Opened (flipCat y x) >>= f return x = Opened (Live x) As complex as Monads sound on the Web, they are trivial to define. Maybe it’s a lot like binary code: nothing could be simpler than ones and zeroes, yet consider that all complexity expressable by computers, down to video, audio, programming languages, and reading this article, are contained within the possibilities of those two digits. Yeah. Monads are a little like that. This useless Monad just illustrates how to define one, so let’s cut it apart piece by piece. By the way, I didn’t author this thing, I just started it. Much of its definition was completed by folks on IRC, who had to wipe the drool from my face toward the end. instance Monad Schroedinger where Says that my Schroedinger type now participates in the joy and fun of Monads! He can be discussed at parties with much auspiciousness. Opened Dead >>= _ = Opened Dead The >>= operator is the “bind” function. It happens when you bind a function to a Monad, which is like applying a function to it. This line says that if you apply a function to an Opened box containing a Dead thing, what you’ll get back is an Opened box with a Dead thing. Opened (Live a) >>= f = f a If, however, you bind a function to an Opened box with a Live thing, it will apply the function to what’s in the box – in this case, the Cat itself. The function f is assumed to return another instance of the Schroedinger type, most likely containing the same cat or some transformed version of it. Unopened y x >>= f = Opened (flipCat y x) >>= f Here is the meat of this example, it’s reason for being, all contained within this one line: If you bind a function to an Unopened box, it gets bound in turn to an Opened box containing a Cat whose fate has been decided by the dice. That’s all. The reason I used a Monad to do this is to defer the cat’s fate until someone actually looked inside the container. return x = Opened (Live x) Lastly, if someone returns a cat from a box, assume its an Opened box with a Live Cat. I don’t honestly understand why this is necessary, but it seems Opened Dead cats are handled by the binding above, as shown by the output from my program. I’ll have to figure this part out soon… The main function The last part of the example is the main routine: main = do gen ,- getStdGen print (do box ,- Unopened gen (Cat "Felix") -- The cat's fate is undecided return box) This is fairly linear: it gets a random generator from the operating system, then creates an Unopened box and returns it, which gets printed. show on the Schroedinger type, since it was derived from Show earlier. Something I still don't understand: at exactly which point does the flipping happen? When box is returned? When show gets called? Or when show in order to pass it out to the IO subsystem? Closing thoughts The full version of this code is on my server. There is also a simpler version without Monads. I worked on the Monad version just to tweak my brain. At least I can say I'm closer to understanding them than when I started.
http://newartisans.com/2009/03/journey-into-haskell-part-2/
CC-MAIN-2017-13
en
refinedweb
Simple Humanoid Walking and Dancing Robot (Arduino) Introduction: Simple Humanoid Walking and Dancing Robot (Arduino). This robot can be made as a beginners robot to introduce yourself to the field of robotics. Let's get into making the robot!! Step 1: Tools and Material Required The bill of materials is as follows: - Micro Servo or any other (qty. 4) ($6 for four). - Arduino UNO(you can use other models but keep in mind that using other models may affect stability). ($6.45) - Wires. ($1.6 for 1m) - Perfboard(not necessary, I did not use one). ($0.78 for one, sold as kit) Thin sheet wood (2 pieces measuring 6.2 x 4.6 cm). This measurement can vary if you are using any other type of servos. Cardboard (small pieces required). Total:Around $16 including cardboard and sheet wood. The required tools include: - Soldering Iron (with solder). - Hot Glue gun. - Cutter. - Hacksaw (to cut wood). - Printer cable for Arduino. Step 2: Preparing Servos The first thing that you need to do is to attach the servo horns to the servos. Keep in mind that you can't just attach them to the servo, it has to be done properly or you will encounter problems later.This video explains how to attach the servo horns to the servos, click here to view it. (The video is not mine but is made by Karl Wendt). Now that you have attached the horns to the servos, it is time to glue the servos together. Both the servo sets are attached in different ways so be careful while gluing them. I have attached pictures which you can use as reference to attach the servos together. Try to keep the horns are as close to 90 degrees as possible. After that, take a piece of cardboard and glue both of the servos on it and cut extra cardboard out. One way to ensure that you do this properly is to make sure that the screw mounting part of both the servos is touching. Make sure to keep the wire part on the outside. Step 3: Attaching the Arduino Once that is done, take a rectangular piece of cardboard (mine measured 6.4 x 5.4 cm) and hot glue it to the backside of the servos as shown in the pictures. You can round the corners to make it look a bit neater. After that, take the Arduino and hot glue the backside of the arduino (the white side) to the cardboard as shown in the pictures. This MAY damage your Arduino (highly unlikely) so if you do this, it will be at your own risk. The only thing left to do now (in terms of hardware) is the wiring. Step 4: Wiring the Servos! The way I have done it, it looks a bit confusing but believe me, it isn't. The red wire of the servos are positive, the brown are negative and the orange wire is the signal wire. So, all you have to do is to solder all the red wires together and then solder a stiff piece of wire to that which connects to the 5v pin of the Arduino. Then, solder all the brown wires together and attach a solid piece of wire to them. This wire will connect to the GND pin which is below the 5v pin. (Wiring diagram attached) After that, you will be left with four orange wires or signal wires. Before soldering them to a stiff wire for connection, you have to understand the naming for the servos. Looking from the pin side of the arduino, the servo on the top right is the right thigh servo. The one below it is the right foot servo. The servo at the top left is the left thigh servo and the one below it is the left foot servo. Connect the right thigh signal wire to pin 5, the left thigh signal wire to pin 11, the left foot signal wire to pin 3 and the right foot signal wire to pin 9. Make sure that all of the signal wires are attached to the pins with a squiggly line before them (PWM pins). (Wiring diagram attached) Step 5: Choosing Power Source Now comes the time to choose whether you will be powering the robot using USB power (which is inconvenient and causes occasional disturbances) or using six AA cells. I chose the latter, although it's entirely your choice what you want to do. The problem with AA cells is that they run out in a few hours. If you chose USB power, all you have to do is to connect a printer cable and power it with that (mine didn't work like that, it kept on falling), but if you chose AA cells then its a little bit more complicated. If you are using USB power (which I don't recommend), you can a power bank to make it more portable. First of all, you have to create the 9v power supply which is just 3 3v AA battery packs soldered to each other in series. Then, you have to wire the 9v pack to the power jack on the Arduino (the wiring diagram is attached). The power jack has 3 pins one on top, one on bottom and one on the right (pic attached). The one at the top and the one at the right are the ground pins. The negative wire of your battery pack connects to one of them. The one at the bottom is the 9v pin, the positive wire of your battery pack gets soldered to that. Once again, soldering wires directly to that is can damage your Arduino (although its unlikely), so do this at your own risk. Step 6: Adding Feet The next step is creating the robot is to attach feet to the base of the robot. For feet, I used a 6.2 x 4.6 cm piece of thin sheet wood for the feet. At first, I had used cardboard but that was very floppy and unsuitable so I opted for sheet wood. All you have to do now is to hot glue the wood onto the feet servos of the robot. Try to glue the servos at the exact middle of the feet. Step 7: Programming Now that we are done with the hardware part of the robot, it is time to work on the software. there. Click on ports and select the one with Arduino/Genuino next to it. Then, enter the code I have provided into the software and click on the right arrow sign at the top left. After some time, it should say Done Uploading and if you have done everything right, your robot should start to move!! If you are having any problems, mention them in the comments section and I will try to answer them ASAP. I have uploaded the code for walking, jumping and a few dances. Of course, once you are familiar with the software you can write your own code for the robot. If you made some mistakes while making the robot, you might have to tweak the code just a little bit. Once again, if you need help just ask for it in the comment section. (Note: Yes I know, the way I programmed this robot is very inefficient but this was my first micro-controller project and I did not know how to use functions so hopefully the coding will be better in the future contests!) Step 8: Understanding the Code In this step, I will try to explain the code the best I can. Lets do the dancing code. ----------------------------------------------------------------------------------------------------------------------------------------------------- #include <><> This command is used for including the servo library. Servo rightfoot; <><> This command creates a Servo object with the name 'rightfoot'. This will be used to address the servo later. Servo rightthigh;<><> This command creates a Servo object with the name 'rightthigh'. This will be used to address the servo later. Servo leftfoot;<><> This command creates a Servo object with the name 'leftfoot'. This will be used to address the servo later. Servo leftthigh;<><> This command creates a Servo object with the name 'leftthigh'. This will be used to address the servo later. void setup() <><> This includes the intial commands that the Arduino will go through once before going through the loops. { <><> Marks the beginning of the setup commands. rightfoot.attach(9); <><> This command attached the Servo object 'rightfoot' to pin 9. rightthigh.attach(5); <><> This command attached the Servo object 'rightthigh' to pin 9. leftfoot.attach(3); <><> This command attached the Servo object 'leftfoot' to pin 9. leftthigh.attach(11); <><> This command attached the Servo object 'leftthigh' to pin 9. } <><> Marks the ending of the setup commands. void loop() <><> This is the code that will be repeated multiple times to do the actions. { <><> Marks the beginning of the loop of commands. leftfoot.write(10); <><> This command is used to make the Servo go to it's initial position after each loop. leftthigh.write(90); <><> This command is used to make the Servo go to it's initial position after each loop. rightthigh.write(105); <><> This command is used to make the Servo go to it's initial position after each loop. rightfoot.write(180); <><> This command is used to make the Servo go to it's initial position after each loop. delay(1000); <><> This creates a 1 sec delay before the next command is executed. The value is in milliseconds. leftfoot.write(17); <><>. leftthigh.write(95); <><>. ......... <><> I did not write all the commands because all the commands that follow are basically the same as these. .........<><> I did not write all the commands because all the commands that follow are basically the same as these. } <><> Marks the ending of the loop of commands. (I have attached a picture which shows how the servo degrees work.) ----------------------------------------------------------------------------------------------------------------------------------------------------- I used more or less the same commands in all of the programs I have coded so I don't think further explanation is needed. This could have been done in a much more shorter and efficient way but this was my first time working with a micro-controller so I used basic commands as they seemed to get the job done :). If you need further explanation of any part of the code, feel free to ask in the comments. Step 9: Conclusion Now that the robot is done, what next? Well, you should now be familiar with robotics and also with writing code for the Arduino. You can continue to code new functions for this robot or even make a new and bigger robot. This instructable was created with mainly the purpose of introducing people to the field of micro-controllers and robotics. I think that this is an excellent beginners robot as it is easy and cheap to make. I originally got this idea from this instructable here, but the person who made it made a mistake or something, I'm not sure, because my robot as well as many other people's robot in the comments section was not working so I though that I would re-write my own version of that instructable. Another thing that motivated me to write this instructable were the contests going on at Instructables at this time (such as the micro-controller contest) which had very good prizes. Winning those contests would equip me with gear which would be useful for future instructables. Thank you for viewing my instructable. awesome.... I will make this stuff... Good luck! :) Send me code i have made the same but my robot is not walking properly please help me I have put together a robot like yours. Your design is so simple that it is perfect to teach robotics. I have modified the code to make it walk smoothly. You can find the code here:... Using "for" loops allows you to vary the speed of any movement. It's amazing dude!!! Nice work :D Thanks again for your inspiring Instructable. Superb But i have a doubt.? Is there any way to speedup the walking, dancing like human functions............. This robot was my first ever robot so I tried to keep it simple. This robot is not stable enough to go faster than this. Going faster may cause slipping or falling over. Thanks for the comment !!! Thanks for your reply. Me too an Indian. Love to be developing Indian Technology. very creative.. this robot is so cute. you should name it. Thanks!! I'll think about naming it haha Good keep going.:) Love from INDIA.:) Thanks a lot!! ☺ really inspiring for a beginner like me -_- Not sure if you are being sarcastic or not based on that emoji lol. If you are then feel free to ask me anything about the project which you find confusing. That looks fun :) Yeah, it really is. It's educational too!
http://www.instructables.com/id/Simple-Humanoid-Walking-and-Dancing-Robot-Arduino/
CC-MAIN-2017-39
en
refinedweb
This example demonstrates how to remove all formatting from a cell or range of cells. You can do this in one of the following ways. Apply the Normal style to a cell or range of cells via the Range.Style property. The Normal style object can be accessed from the Workbook.Styles collection by the style name (Normal) or index (by default, this style is added as the first in the collection of styles and cannot be deleted), or via the StyleCollection.DefaultStyle property. using DevExpress.Spreadsheet; // ... IWorkbook workbook = spreadsheetControl1.Document; Worksheet; Imports DevExpress.Spreadsheet ' ... Dim workbook As IWorkbook = spreadsheetControl1.Document Dim worksheet As
https://documentation.devexpress.com/WindowsForms/15438/Controls-and-Libraries/Spreadsheet/Examples/Formatting/How-to-Clear-Cell-Formatting
CC-MAIN-2017-39
en
refinedweb
SAP Application Interface Framework (AIF) is a new tool for monitoring and error handling of all interface in one place. You can use it to monitor your IDOC and ABAP proxy scenarios in one place which was not possible in the past. For more features on AIF please have a look at AIF introduction on help.sap.com In this article I’d like to show a simple example of AIF on how to monitor existing IDOC scenarios, that is without changing any of your IDOC configuration. We will be doing configuration of the AIF to be able to monitor one inbound IDOC – SYSTAT01 in order to be able to see it in the AIF’s Monitoring and Error Handling application. Step 1 At first we need to create a new namespace in which we will be doing the configuration (it’s just a way of grouping for customizing objects). We can create it from transaction /AIF/CUST_IF – Interface Development – Define Namespace. Add a new namespace and save it as show in the Figure below. Step 2 Then need to generate a new IDOC structure which will be used in AIF. We can do this in transaction – /AIF/IDOC_GEN. Insert the following: – the basic type of the IDOC which you want to monitor – a prefix structure (any custom name – you can use name but I stick to Y/Z objects) – a prefix interface definition (any custom name – use Y/Z objects) – a namespace (created in step 1 of this article) – an interface version – 1 – a variant ID = 01 Once you’re in the generation screen (after pressing F8 – Execute) you can generate it. If the generation was successful you can copy the Raw Data Structure’s name as we will be using that in the next steps. Step 3 In the next step you need to define an interface which will be used in monitoring. Transaction – /AIF/CUST_IF – Interface Development – Define Interfaces. – Insert the interface name – Insert the interface version – SAP data Structure = RAW data structure (from the IDOC generation step) – make sure “move corresponding structures” check if selected Step 4 As a next step you need to define which engine will be used to handle the interface. Transaction – /AIF/CUST_IF – Interface Development – Additional Interface Properties – Specify Interface Engines. The engine should also be defined by the variant ID selected in /AIF/IDOC_GEN. Insert the following: – Application Engine = IDOC – Persistence Engine = IDOC – Selection Engine = IDOC control record – Logging Engine = IDOC status record Step 5 As a last configuration step we need to assign the IDOC type to the newly created interface from Step 3. Transaction – /AIF/CUST_IF – Interface Development – Additional Interface Properties – Assign IDOC type. Select your interface from Step 3 and insert IDOC’s Message Type and IDOC’s Basic Type. Testing Now you can run your standard IDOC scenario one more time and this time apart from standard IDOC monitoring transactions (WE02/WE05) you will be able to see it the AIF’s Monitoring and Error Handling application. Transaction – /AIF/ERR You can also display the message payload and edit it. Note This is just the first view of AIF – in the next articles I will try to show all AIF options for monitoring of IDOCs and ABAP Proxies, index tables, doing validations and mappings so please stay tuned. Hi Michal, Thanks for sharing this. Can you shed some light on the licensing model? I know that AIF require separate license. How do you justify customers to use AIF over free options like FEH for ABAP proxy? Thanks, Prateek Raj Srivastava Hi Prateek, I’m just a simple consultant – I don’t know/want to know anything about licensing 🙂 Regards, Michal Krawczyk Nicely put! 😉 Hi Michal, Thanks for keeping the PI/PO community informed about these updates on the front. If I understand good AIF can be positioned as an alternative for PI in some specific cases, e.g. less complex integration sceanario’s, no adapter needed etc.. Generally speaking AIF is a light version of PI. Do you agree on that? Regards, Roberto hi Roberto, >>>Generally speaking AIF is a light version of PI. Do you agree on that? not at all 🙂 AIF is only able to work with proxies, rfc, and IDOCs but cannot send/receive them from files or any other adapter – there needs to be the something like PI (or any other middleware which will be able to work with real adapters) so AIF is more like WE02/We05/SXI_monitor + a few features in one application but certainly not a light PI 🙂 it’s more like light version of Solman I’d say 🙂 Regards, Michal Krawczyk Hi Michal, That was exactly what I was hoping for ;-). However, at help.sap.com AIF is described with a broader scope than only monitoring interfaces. How about that? 🙂 Hi, >>>How about that? 🙂 so this the processing framework as shown in my second blog on AIF 🙂 still the same thing – generic monitoring tool for all SAP interfaces with some simple mapping functions, nothing related to adapters, scheduling, etc. so for me it’s only way better WE02/SXMB_MONI with many new functions (index tables, alerting, etc.) just I said it’s like FEH/ECH for all interfaces (not only proxies) but you know – I might be wrong 🙂 Regards, Michal Krawczyk Dear Michal, Please provide some post for Outbound IDOC. Error Handling for Outbound IDOC and Recipients configuration for this. With Best Regards Sayantan Das Hi Michal, do you have some example of outbound idoc configuration? I would like mainly use AIF for data mapping before sending the idoc. Thank you Jamal Hi Michal, thanks for the helpful summary. In Step 4 you have assigned your Namespace “TEST” to each engine except to the logging engine. Why? The standard IDoc processing doesn’t know any namespaces, right?!. So which sense does it make assigning one here? Best regards Rainer Hi Michal, Basically, AIF should implement on Application system like ERP etc. However is it possible to implement AIF on PI system just for a demo test? Thanks Leon Hi Maichal, Thank you for share this scenrio. When I generate Idoc it occured an erro. Could you please help to solve it. error msg: Number range /AIF/ISG failed Error during structure generation. Processing stopped. Thanks & Regards, Misty. Hello, Can you check if the number ranges were generated (with report /AIF/GENERATE_NUMBER_RANGES). This is a mandatory post-installation activity (check the Master Guide SAP Application Interface Framework 2.0 – SAP Help Portal Page). Good luck with AIF, George Thank you, George! It’s very helpful. Thank you Michal for bringing up this topic & highlighting its benefits. Apart from above advantages, it can be used for, 1) Moving the Business logic from PI to AIF[Add on to ECC]. so far, we had restrictions of implementing Business Logic in IDOC scenario AIF helps a lot in implementing business logics before IDOC generation. Hence, we can use PI for structural mapping & ECC for busines logics. 2)Moving Value mappings, RFC Lookup to ECC, to AIF. If any customer is using Huge value mapping tables in PI for validation purposes. Those tables & Logics can be re-implemented in AIF. This improves the performance on PI. if we are using RFC lookups to ECC system in an IDOC scenario, that would drain the performance of the message. By moving the RFC lookup logic to AIF, it would drastically improve message perfromance. Regards. santosh.
https://blogs.sap.com/2012/10/06/michals-pi-tips-application-interface-framework-aif-20-monitoring-existing-idocs/
CC-MAIN-2017-39
en
refinedweb
Where. It not really works... This example works: <? foreach ($key as $val) : echo $val; endforeach; ?> but this not: <? foreach ($key as $val) : ?> <div><?=$val;?></div> <? endforeach; ?> I've been trying to add some PL/SQL support, but I'm having trouble with the settings. The settings I'm using are (based on the PHP settings): { "name": "plsql_keywords", "open": "^\\s*\\b(if)\\b", "close": "^\\s*\\b(end if)\\b", "style": "default", "language_filter": "whitelist", "scope_exclude": "string", "comment"], "plugin_library": "User.plsqlkeywords", "language_list": "SQL", "PL/SQL (Oracle)"], "enabled": true } The plsqlkeywords.py file in my user directory has: def compare(name, first, second, bfr): print name return "end " + bfr[first.begin:first.end].lower() == bfr[second.begin:second.end].lower() (I was trying to print the parameters so I could get a better general understanding of it's workings) However, BH2 is not able to call the plugin defined in the plugin_library parameter, no matter what. In order to identify what I'm doing wrong, I'd like to clarify some things:- In the language_list parameter array, I should use the language name defined in the .tmLanguage file, right?- I'm using bizoo's package (github.com/bizoo/Oracle), so in my case the language name should be "PL/SQL (Oracle)". I'm assuming that there's no need to escape the forward slash (I've tried renaming the language name, but without success)- I've also tried to simplify the open and close regexes to the point of just "(.)", but even in this case the plugin is not called. Could anyone clarify me on what I could be doing wrong? the code I'm using to test is this: if ( true ) then null; end if; Thanks for any help! Well, it works, but you don't quite understand the rules. PHP has some quirks. This is simply a case of dangling brackets. You can see here that the curly braces are not actually matches. ({)(}) The algorithm is very general in BracketHighlighter so that it works with all languages. Stuff like this is a bit tricky to deal with without making some concessions. So, I have updated the PHP Conditional Keywords on the Beta branch, but in order for this to work for you, you have to ignore <?, <?php, and ?>. If you do this, those will no longer be highlighted, but BracketHighlighter will be able to see things like the foreach and endforeach across the <? ?> punctuation. So update your BH2 branch and then change your Angle definition to match this in your User/bh_core.sublime-settings file. // Angle { "name": "angle", "open": "(<)", "style": "angle", "scope_exclude": "string", "comment", "keyword.operator", "punctuation.section.embedded.end.php", "punctuation.section.embedded.begin.php"], "language_filter": "whitelist", "language_list": "HTML", "HTML 5", "XML", "PHP", "HTML+CFML", "ColdFusion", "ColdFusionCFC"], "plugin_library": "bh_modules.tags", "enabled": true }, That is the best I can do for you. Edit: I am sure other things can break this like comments right before or right after the php punctuation, but if someone wants to take the time to code up the "perfect" regex, I will pull it in, but this should work in most cases; not sure if there will be any side effects when ignoring <? and ?>. This isn't guaranteed to be perfect, I kind of expect the community to polish up the regex for their languages and save me from trying to come up with the regex for every language that I might not even use. I will take a look when I have some time. .
https://forum.sublimetext.com/t/brackethighlighter2-beta-branch/7683/130
CC-MAIN-2017-39
en
refinedweb
This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers. dotCover is a unit test runner and code coverage tool that enables .NET developers to easily see how successful they are in covering their applications with unit tests. JetBrains' dotCover is a .NET code coverage tool with an integrated test runner that enables developers to easily determine how much of their code is covered by tests. Code coverage analysis can be executed right from within Visual Studio 2005, 2008, 2010, and 2012 RC. dotCover seamlessly integrates with JetBrains' ReSharper’s unit test runner to enable analyzing coverage of unit tests. If you don’t have ReSharper installed, you can use dotCover's integrated test runner to run and analyze coverage of unit tests based on MSTest, NUnit, xUnit, or the MSpec framework. Coverage details are presented as a tree view. dotCover calculates and reports statement-level code coverage for applications built with .NET Framework 1.0 to 4.0, as well as in Silverlight 4 and 5. dotCover helps you learn to what extent your code is covered with unit tests. It also helps developers and QA engineers test software products as thoroughly as possible by reporting code coverage for automated and manual test runs. dotCover is a plug-in to Visual Studio giving you the advantage of analyzing and visualizing code coverage without leaving your code editor. Currently dotCover integrates into Visual Studio 2005, 2008, 2010, and 2012 Release Candidate. In addition to the tree view for visualizing coverage data, dotCover can highlight covered and uncovered lines of code right in the Visual Studio code editor. You can specify light, medium, or dark color schemes for code highlighting to match your preferred Visual Studio theme. dotCover comes bundled with a unit test runner that it shares with ReSharper, JetBrains' .NET developer productivity tool, to enable analyzing coverage of unit tests based on MSTest, NUnit, xUnit, or MSpec. However, even if you don’t have ReSharper installed, you can still use dotCover for running and analyzing coverage of unit tests based on NUnit and MSTest. In case you have both ReSharper and dotCover installed, you can choose which unit test runner you want to use, or alternatively use them both. From within the coverage tree view, you can exclude a specific node or all nodes except the current node from the coverage calculation. As soon as you've excluded a node or nodes, dotCover instantly recalculates percentages of covered and uncovered code. This is useful for focusing on production code or filtering out code that you're not interested in testing right now. In addition to including or excluding nodes in the coverage tree, you can set global or solution-specific coverage filters based on project, namespace, type, or type member names. Attribute filters are also available that restrict gathering coverage information from code marked with certain attributes. dotCover uses these filters to include or exclude coverage data during a coverage run. dotCover includes a command line runner, which is a great fit with continuous integration servers and can easily be called from build scripts. JetBrains' own continuous integration product, TeamCity, bundles dotCover's coverage analysis engine, which helps schedule coverage runs as part of the continuous integration process and generating server-side coverage reports. Via the TeamCity add-in for Visual Studio, dotCover is able to obtain coverage data from a TeamCity server — without running coverage analysis on a local machine. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
https://www.codeproject.com/Articles/418999/JetBrains-dotCover-Released
CC-MAIN-2017-39
en
refinedweb
JTree: Construct Tree - Online Code Description This Code tells us how to construct a tree. Source Code import javax.swing.tree.*; import javax.swing.*; import java.awt.*; public class ConstructTree extends JFrame { public static void main(String[] args) { ConstructTree obj=new ConstructTree(); obj... (login or register to view full code) To view full code, you must Login or Register, its FREE. Hey, registering yourself just takes less than a minute and opens up a whole new GetGyan experience.
http://www.getgyan.com/show/536/JTree%3A_Construct_Tree
CC-MAIN-2017-39
en
refinedweb
Gary Bradski, Adrian Kaehler Mentioned 34 Describes the features and functions of OpenCV along with information on how to build applications using computer vision. I am currently working on a system for robust hand detection. The first step is to take a photo of the hand (in HSV color space) with the hand placed in a small rectangle to determine the skin color. I then apply a thresholding filter to set all non-skin pixels to black and all skin pixels white. So far it works quite well, but I wanted to ask if there is a better way to solve this? For example, I found a few papers mentioning concrete color spaces for caucasian people, but none with a comparison for asian/african/caucasian color-tones. By the way, I'm working with OpenCV via Python bindings. Have you taken a look at the camshift paper by Gary Bradski? You can download it from here I used the the skin detection algorithm a year ago for detecting skin regions for hand tracking and it is robust. It depends on how you use it. The first problem with using color for tracking is that it is not robust to lighting variations or like you mentioned, when people have different skin tones. However this can be solved easily as mentioned in the paper by: Throwing away the V channel in HSV and only considering H and S channels is really enough (surprisingly) to detect different skin tones and under different lighting variations. A plus side is that its computation is fast. These steps and the corresponding code can be found in the original OpenCV book. As a side note, I've also used Gaussian Mixture Models (GMM) before. If you are only considering color then I would say using histograms or GMM makes not much difference. In fact the histogram would perform better (if your GMM is not constructed to account for lighting variations etc.). GMM is good if your sample vectors are more sophisticated (i.e. you consider other features) but speed-wise histogram is much faster because computing the probability map using histogram is essentially a table lookup whereas GMM requires performing a matrix computation (for vector with dimension > 1 in the formula for multi-dimension gaussian distribution) which can be time consuming for real time applications. So in conclusion, if you are only trying to detect skin regions using color, then go with the histogram method. You can adapt it to consider local gradient as well (i.e. histogram of gradients but possibly not going to the full extent of Dalal and Trigg's human detection algo.) so that it can differentiate between skin and regions with similar color (e.g. cardboard or wooden furniture) using the local texture information. But that would require more effort. For sample source code on how to use histogram for skin detection, you can take a look at OpenCV"s page here. But do note that it is mentioned on that webpage that they only use the hue channel and that using both hue and saturation would give better result. For a more sophisticated approach, you can take a look at the work on "Detecting naked people" by Margaret Fleck and David Forsyth. This was one of the earlier work on detecting skin regions that considers both color and texture. The details can be found here. A great resource for source code related to computer vision and image processing, which happens to include code for visual tracking can be found here. And not, its not OpenCV. Hope this helps. I am learning OpenCV using Learning OpenCV book. One problem I am facing while compiling the code is that I have to write a long command to compile and get the executable. This is the command I am using g++ `pkg-config –cflags opencv` file_name.cpp -o output_file `pkg-config –libs opencv` I am no Make expert but I think I can eliminate writing that long command using make. Before that I should explain my work flow. I have created a directory called opencv in my home directory ( ~/opencv/). I am reading the book section by section and coding the examples or exercises into new cpp source code files in that directory. So I don't know the names of the files before hand. Now what I want make to do is, Suppose I have coded a new file named facedetect.cpp in my opencv directory, and if I call make like this make facedetect then I want make to execute the following command for me g++ `pkg-config --cflags opencv` facedetect.cpp -o facedetect `pkg-config --libs opencv` so that whenever I make a new file named abc.cpp, I will execute make abc so that I can run $ ./abc at my command line to test my abc.cpp Please give that make file so that I can save the frustration of typing that long command each time. PS: I have Googled for help on this and found this on using CMake but I could not understand what that does. Kindly also explain how can I use CMake for the same task. You can create a file called Makefile in you working directory like this: CFLAGS = `pkg-config --cflags opencv` LIBS = `pkg-config --libs opencv` % : %.cpp g++ $(CFLAGS) $(LIBS) -o $@ $< then you can use this file for all your single-file programms. Just call make with the basename of the file you want to compile. For facedetect.cpp that would be make facedetect Here some more details: The general format of a makefile is like this: target : dependecy1 dependenc2 ... command that generates the target So for your example you could write: facedetect : facedetect.cpp g++ $(CFLAGS) $(LIBS) -o facedetect facedetect.cpp For each new example you can now create a new target. But you can also make it more general: % : %.cpp g++ $(CFLAGS) $(LIBS) -o $@ $< Here % matches any nonempty substring. The automatic variables $@ and $< substitute the names of the target file and the source file. For more information you can consult the make documentation. i want to do a small project on object recognition, any any tools or literature suggestions on this topic ? You will probably need to work with Image Processing techniques in your project. A very good introductory book to this area is the Digital Image Processing by Gonzalez and Woods. It covers topics such as image segmentation, which is a technique used to separate the objects to be recognized from the rest of the image After you have identified the objects in the input image, the next step consists in finding a way to measure how similar they are to one another. Probably, the best way to do that is to use image descriptors. Usually, for object recognition, the best class of descriptors are the ones based on shape. The article "Review of shape representation and description techniques" by Zhang D. and Lu G. provides a great review about shape descriptors. Finally, you have to classify those objects. [Machine Learning] by Mitchell is a classical book that discusses techniques such as k-NN that you can use in your project. OpenCV or Matlab. I particularly use OpenCV and I really like it for the following reasons: High, I need to do some image manipulations on CT volume images. Mainly segmentations. Which open-source library supports 3D algorithms - Filtering, edge detection, deformable objects and so ? Language is not an issue at the moment. 10x I'm going to set up some devices to perform real-time 3D motion tracking. My first idea to do so is to use a pair of cameras to take stereo image and calculate the depth map to get the 3D data I needed. Are there any good open source libraries (C/C++) available and is fast enough for real-time(~12-24fps)? I've found 3D Reconstruction using Stereo Vision and EStereo in SourceForge, have anyone tried them? Or any algorithm suggestion that I can implement? Opencv has a whole section on this, see chapter 12 of Learning Opencv I have a basic understanding in image processing and now studying in-depth the "Digital Image Processing" book by Gonzales, but have an urgent task and will appreciate help from somebody experienced in this area. When image given and object of interest approximated form is known (e.g. circle, triangle), what is the best algorithm / method to find this object on image? The object can be slightly deformed, so brute force approach will not help. I strongly recommend you to use OpenCV, it's a great computer vision library that greatly help with anything related to computer vision. Their website isn't really attractive, nor helpful, but the API is really powerful. A book that helped me a lot since there isn't a load of documentation on the web is Learning OpenCV. The documentation that comes with the API is good, but not great for learning how to use it. Related to your problem, you could use a Canny Edge detector to find the border of your item and then analyse it, or you could proceed with and Hough transform to search for lines and or circles. I tried to read Digital Image Processing by Gonzalez/Woods but I found it difficult to understand/grasp. I have taken a Graduate Course in Computer Vision, which is more practically oriented and I am doing lot of cool stuff with OpenCV, however I still feel I am swimming in higher abstractions, and do NOT understand the basics beneath. I am planning to read a book on Computer Vision/Image Processing during the Winter Break to solidify my understanding of the content and would appreciate some must-read suggestions I have done assignments like - camera calibration, image transforms, stitching images into panoramas, haar classification. Have a look at this book. It's quite heavy (and expensive!), but it covers a lot of topics, and each chapter is authored by a different person that is competent in the corresponding field. If cost is a huge issue, I've seen reprints from Taiwan that appear to be legitimate for a fraction of the original price (they are soft cover, though, and the print quality is obviously not as good). Mind you, I've got both The Handbook and Gonzalez & Woods, and I've found Gonzalez to be easier to digest during the initial stages. Rather than just reading, it is definitely recommended to attempt to reproduce all the examples that they give, and make an honest attempt at the exercises at the end of each chapter. The Handbook is great for coverage but lacks exercises. Finally, your choice of must read really depends which specific direction you are expecting to be working in. The basic knowledge (spatial and frequency domain filtering, for example) has been around since the dawn of the field (early 60s) and is usually covered fairly well by most texts. If you want to learn about more recent applications, you have be a bit more specific (or go for The Handbook as it attempts to cover it all). Gonzales and woods (or Wintz in my day) is a very good introduction. There is a more readable but less concise introduction - Image-Processing-Analysis-Machine-Vision And since you are working with opencv - you can do worse than read the opencv book I" if you are looking to learn more about OpenCV generally, you a good place to start is with this book: Learning OpenCV by Bradksi et al. I have been finding a book for OpenCV, but Learning OpenCV is all what I can find. Unfortunately, the book is written for OpenCV 1.1 and is quite out of date. So I searched in Stackoverflow and found this thread. After reading the thread, I understand I can still learn OpenCV from the book, but I am afraid the code differences between OpenCV 1.1 and 2.2 will make learning OpenCV frustrating, especially for a complete novice like me. Currently I am finding for a book or tutorial website that is specifically written for OpenCV 2.2, so I can follow the code in the book and get started more easily. By the way, I would like to know that which language integrates best with OpenCV? I am wondering is using Emgu CV (OpenCV for .net) with C#.net a good choice? Thanks! Learning OpenCV book is recently updated to OpenCV version 2.4. Here is the link. Also there is a good reference manual for OpenCV version 2.4.2 here[pdf]. OpenCV 2 Computer Vision Application Programming Cookbook was published in June 2011. It covers the newer C++ APIs, so it may be what you're looking for. How do services like card.io work behind the scenes? Do they use an OCR library like Tesseract or is it more complex? Also, in this video, it looks like the app is waiting for you to hold your card in a specific range from the camera inside the green boundaries on the camera, and when you do it takes the photo automatically. If the image recognition is happening on the server, how did they do that? How can I implement my own mobile 2D object scanner? Where do I start? Josh from card.io here. I can't tell you the details of how card.io works (hopefully others will speculate here), but I can answer some of your other questions. card.io does not use an OCR engine; we looked at Tesseract and others and found that they did not work well on many credit cards. card.io's image recognition happens entirely on the phone. Early versions required some server assistance, but even those did a good chunk of the work on the phone. To get started, I recommend sitting down and reading Learning OpenCV; it is a good general introduction to computer vision. Then play around and ask more detailed questions. On the machine learning side, Theano and Eigen are very helpful libraries. I want to develop a system that can track and follow a road. Initially, I'd like to handle well-defined roads only and maybe later incorporate tracking for roads that aren't so well defined. The problem I'm facing is that I don't know where to get started. I am new to image processing and I was hoping I could get some pointers on where to start off and what books to read on the subject. I am an 'experienced' programmer (I can program in C and Python fairly well, and can handle C++ and Objective-C), so the code itself isn't that big of an issue - its just "where do I start? what do I read?" thats confusing me. I am also open on learning another language if it helps me in anyway. I'll appreciate any pointers/suggestions regarding this. For a hands-on: Learning OpenCV: Computer Vision with the OpenCV Library by Gary Bradski and Adrian Kaehler. This book will give you a nice introduction to a lot of CV topics, references to go further and code examples using OpenCV, probably the most used computer vision library nowadays (recently, NVidia announced porting part of the code to their GPUs). OpenCV presents C, C++ and Python APIs. Gonzalez and Woods' Digital Image Processing is a nice companion of image processing techniques. Update I forgot the hot new Szelisk's book. There is a free (and good) draft available! I am using opencv with C, and I am trying to get the extrinsic parameters (Rotation and translation) between 2 cameras. I'm told that a checkerboard pattern can be used to calibrate, but I can't find any good samples on this. How do I go about doing this? edit The suggestions given are for calibrating a single camera with a checkerboard. How would you find the rotation and translation between 2 cameras given the checkerboard images from both views? I was using code from. It has some useful information and code of the author is pretty easy to understand and analyze, it covers both - chessboard calibrate and getting depth image from stereo cameras. I think it's based on this OpenCV book I am working on backgroun subtraction under sudden light change. Is there any example code or way to do this efficiently in OpenCV or IPP? I am reading video frames, so the running time should be very fast. Thanks in advance. I am really new to digital image processing and is fixed with the below mentioned problem:- I need to write a C program which will load a ppm image file and do line detection with convolution kernels. Any kind of help will be appreciated. fopen(..) Might find this link helpful To Implement the masks in the links you're refering to, take this code and change GX and GY to a) and b) /* 3x3 GX Sobel mask. Ref: */ GX[0][0] = -1; GX[0][1] = 2; GX[0][2] = -1; GX[1][0] = -1; GX[1][1] = 2; GX[1][2] = -1; GX[2][0] = -1; GX[2][1] = 2; GX[2][2] = -1; /* 3x3 GY Sobel mask. Ref: */ GY[0][0] = -1; GY[0][1] = -1; GY[0][2] = -1; GY[1][0] = 2; GY[1][1] = 2; GY[1][2] = 2; GY[2][0] = -1; GY[2][1] = -1; GY[2][2] = -1; Same for c) and d) Other than creating from scratch you could also use the open source openCV There are online documentation and textbooks on how to use it too I am searching in the Computer Vision topic, I don't have any previous experience.I found a good library OpenCv with python interfacing .I have started reading it's documentation, but I have faced many new concepts and names, that I am not familiar with, such as Compute the Laplacian , GoodFeaturesToTrack, CreateMat and many others So my questions is what I have to study before starting with this library, to understand the functions of the library ? I would recommend a book by OpenCV author Gary Bradski - Learning OpenCV: Computer Vision with the OpenCV Library. It is not only a refence how to use OpenCV, but also a comprehensive book on many computer vision topics, with many images that illustrate the concepts. It guides you through OpenCV basics, then trough image processing using filters, convolutions, histograms, contours, segmentation, tracking, camera calibration and 3D vision. It is relatively easy to read (not too much math, just enough), I liked it really much. I would recommend you the book of gonzalez and woods - Digital image processing for the image processing basics. there is a book on opencv but is for version 1.0. It is a decent book anyway. Anyway openCV is a good library image processing but you would still need the basics of programming (don't forget this). I am sorry about the Title for this question, but really I don't know how to name it. There is something that I have seen sometimes, and I ask myself how to do that kind of software. It's about the PitchTrax that MLB uses in its TV-games. I think that is did it using cameras or something like that... I would like to read (or to learn) how to do little applications using this kind of technology, but I don't know anything about that, really I don't know where "to start" studying for this... Do you know something about this?? I am sorry about my English. I don't know pitch trax specifically (try google or their site) But the general field of object tracking and image processing then openCV is probabyl a good place to start (as a programmer) There is a good book at I am working on developing an iOS video app that needs to do stuff like apply filters, adjust brightness/contrast/saturation add overlays etc. As I am new to image processing I am not able to judge which resources (i.e. APIs, open source libraries) I can use. So any guidance from those who have experience in this field will be of great help. 1. Get OpenCV 2. Check out this SOF for more details on OpenCV on iOS 3. All the best. I have two cameras setup as shown in following picture: What I have with this setup: (x1,y1)as its 2D image coordinates. (x2,y2)as its 2D image coordinates. How can I trace/identify real world 3D coordinates (x,y,z) of this green object via these two cameras (i.e combination of top view image and side view image)? I know how to calibrate single camera using JavaCV/OpenCV but I don't know how perform stereo calibration other stuff using JavaCV/OpenCV. What is the step-by-step procedure for doing such stereo calibration via two cameras? What would be the output (e.g., intrinsic matrix, distortion etc.) of such a stereo calibration process and how can I use that output in order to compute the real world 3D coordinates of this green object? Hi the following blog will answer all your questions... No image was uploaded.. Just check or else you could find theoritical concepts from the book or for the actual code implementing with cameras one can refer to I'm having some images, of euro money bills. The bills are completely within the image and are mostly flat (e.g. little deformation) and perspective skew is small (e.g. image quite taken from above the bill). Now I'm no expert in image recognition. I'd like to achieve the following: I think of these two steps as pre-processing, but maybe one can do the following steps without the above two. So with that I want to read: I assume this should be quite possible to do with OpenCV. I'm just not sure how to approach it right. Would I pick a FaceDetector like approach or houghs or a contour detector on an edge detector? I'd be thankful for any further hints for reading material as well. I am looking for a way to separate the part of an image that contains a person from the background in an image. It does not have to be very accurate, rough borders will do too. It can be an algorithm, a software lib (pref. open source), or even a reference to a relevant AI or image processing material. Having to train the solver is acceptable. However, the final application have to be reasonably lightweight, as it would have to run on a smartphone. Start with OpenCV. It's an open-source computer-vision library that already contains some algorithms for that. Try what it's got and see if it's good enough for your needs. The “Learning OpenCV” book will give good introduction into computer vision and machine learning. I have started learning OpenCV. I am working on linux. From their documentation page I was able to compile this However after that I got lost in trying to declare a new mat and it's constructors. SO I decided to go with this book However I am not able to compile the very first program from this book. The program is here : #include "highgui.h" int main(int argc, char** argv) { IplImage* img = cvLoadImage (argv[1]); cvNamedWindow("Example1", CV_WINODW_AUTOSIZE); cvShowImage("Example1",img); cvWaitKey(0); cvReleaseImage(&img); cvDestroyWindow("Example1"); } I saved this in a file named load.c Then I created a CMakeLists.txt file and put this in it : project( load ) find_package( OpenCV REQUIRED ) add_executable( load load ) target_link_libraries( load ${OpenCV_LIBS} ) when running "cmake ." from terminal it is succesful. But when I am running "make" it gives me this error : Scanning dependencies of target load [100%] Building C object CMakeFiles/load.dir/load.o /home/ishan/load/load.c: In function ‘main’: /home/ishan/load/load.c:4:2: error: too few arguments to function ‘cvLoadImage’ /usr/local/include/opencv2/highgui/highgui_c.h:212:18: note: declared here /home/ishan/load/load.c:5:28: error: ‘CV_WINODW_AUTOSIZE’ undeclared (first use in this function) /home/ishan/load/load.c:5:28: note: each undeclared identifier is reported only once for each function it appears in make[2]: *** [CMakeFiles/load.dir/load.o] Error 1 make[1]: *** [CMakeFiles/load.dir/all] Error 2 make: *** [all] Error 2 I think it is because this example in the book is for OpenCV 1.x while I am currently running 2.4.3, however I believe there must be a way to run this program and the subsequent program that are in the book. I think the problem lies with linking the header files properly. I would like to first read from the book and using reference from documentation and then switch to documentation fully. But for now I wish to learn from the book as learning from the book is far easier to me than documentation. Plus I bought this book for approx 3000 INR and got it just today, I don't want to see it go to waste. I want to learn from it. Please help me out. CV_WINODW_AUTOSIZE is mispelled. The correct constant is CV_WINDOW_AUTOSIZE cvLoadImage (argv[1]); should be cvLoadImage (argv[1], 1); (for loading a color image) because the C standard does not support default arguments. By the way, if you're using OpenCV 2.0+, I recommend learning the C++ API. It's a lot less convoluted than the C API and performance is comparable. I'm just getting started with OpenCV. I came across this question, and I'm trying to find where that code came from. Any ideas? If you don't have reference image of the background then you could try to make an average of first n frames and use such resultant image as a reference. This number, n, could be 20 or similar and it should be enough if the scene isn't too complex. I recommend you to read a chapter about background subtraction in official OpenCV book () as there are some of other similar techniques presented. I want to segregate the frames that have high correlation. Suppose in a video the first 6 seconds, the scenes do not change much except that there is a very little movement of objects. How can I separate out those frames by finding the correlation between all of them. .... For this I visited this link but it did not help much .... Please help me in this problem ! You can use image subtraction. Cross-correlation is also acceptable here. Google search phrase: background subtraction algorithm. Also this book contains needed info for you. My goal is to be able to have a person with a mobile phone snap a picture of a local landmark (building or otherwise (ex. gazebo, statue, etc)) on our college campus and be able to identify the landmark and tell them what it is. For instance, they are walking around and they see a large building with a metal dome. They don't know what it is, but it looks interesting, so they snap a picture and the app tells them that it's the basketball center (and other relevant info). My limited knowledge in this particular field led me to think of using neural networks and training the program to recognize particular places. If this is the case, please also give me resources for this option, as the extent of my knowledge of NN is that they can be used to recognize things if they are trained. :) I know of the OpenCV library, but as I am not a C developer, I'd like to know if I need to go down that road before I start. I primarily work in Java, but I'm not opposed to getting my hands dirty. Thanks! This is in response to your original question. The best resource would be the O'Reilly book Learning OpenCV You can read the thing on Google books for free and it uses C along with OpenCV. You can use python or Java to suit your work. The OpenCV library includes haar training and sample programs on training it for face/text recognition. After that you'll basically have to figure things out. Another useful resource I just stumbled upon is Intel's reference manual for OpenCV. So, good luck! Now I control robot to run tic-tac-toe game but i couldn't know how to use opencv library to recognize game board and inner square I wonder how to use algoritm to get corner of game board and 9X9 Game square This is what i do get the corner Binary Image: cvFindContours: #include <stdio.h> #include <fcntl.h> #include <cv.h> #include <cxcore.h> #include <highgui.h> int main(void){ IplImage *img=NULL; IplImage *gray=NULL; CvMemStorage* contour_storage; CvSeq* contours=NULL; CvPoint2D32f *corners; img = cvLoadImage("tictactoe.bmp",CV_LOAD_IMAGE_COLOR); gray = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 ); cvSmooth( img, img, CV_GAUSSIAN, 3, 0, 0, 0); cvCvtColor(img, gray, CV_RGB2GRAY); cvAdaptiveThreshold(gray, gray, 128,CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY_INV, 3, 5); cvNamedWindow( "Threshold", CV_WINDOW_AUTOSIZE); cvShowImage("Threshold", gray); contour_storage = cvCreateMemStorage(0); corners = (CvPoint2D32f *)malloc(sizeof(CvPoint2D32f)*9); cvFindContours(gray, contour_storage, &contours, sizeof (CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); cvDrawContours(img, contours, CV_RGB(255,0,0), CV_RGB(0,255,0), 2, 4, 8, cvPoint(0,0)); cvNamedWindow("Calibration", CV_WINDOW_AUTOSIZE); cvShowImage( "Calibration", img); cvWaitKey(0); return 0; } i wonder how to process to image processing to perform game This Progmram is limited to Using C Code and OpenCv 1.x to run embedded board using arm Please let me know how to develop this game using opencv I only used the c++ interface up to now, so I don't know about the exact names of the functions you'll have to call. Nevertheless, here's a description of a rough algorithm I would use to achieve what you want, so you have a few keywords you can look up: As the camera image is clearly distorted, recognizable by the curved board lines, you should start by calibrating your camera. If you always use the same camera, or at least the same model with the same focal length, you'll only have to do this once. A quick tutorial on this can be found here. This is a more detailed tutorial, with more mathematics, unfortunately he uses the c++ functions. The next step would be detecting the cells of your board. I think this can be achieved more easily by using a Hough Line Transform (also c++) and then calculating the line intersections and thus you can define your cells. If you want your software to automatically take it's turn, you can use a motion detector to determine if there's currently no motion and then act. Background subtraction is an easy way to do this. I didn't find a suitable explanation on this, just do a google search. After that you'll have to find circles and crosses. Circles are the easier part, as there's also a Hough Circle Transform. Crosses are more tricky. I would estimate the length of the crosses lines by taking the diagonals of your cells into account and the again use a Hough Line Detector. Everything I mentioned here gets explained in detail (but not too theoretically) in this book, which I found very helpful when learning OpenCV. They even use the C-Interface. HI guys, Currently I am developing an image processing library for android, I need a book/pdf doc which contains all algorithms implemented in open Cv. Thank you!! There is an O'Reilly book by two of the major authors of OpenCV: Learning OpenCV: Computer Vision with the OpenCV Library by Bradski and Kaehler. You should note that it is based on OpenCV 1.0, not the more recent 2.2. Nonetheless, to understand algorithms it will likely be useful. For most of the higher-level algorithms like corner detection, for example, the book contains a mathematical descriptions of the implementation. Also, the authors do a decent job of providing references to academic journal articles, so even if their own description of the implementation is lacking, you will be able to use the references as a starting point. I am Looking for book or tutorials for implementing face detection in iphone sdk? OpenCV is one but it takes more time to detect faces. I want to learn algorithms used for face detection. Once i got a logic then it can be easily converted into programs. Plz send me appropriate tutorials or ebook links ??? The OpenCVS library can be used on the IPhone: Learning OpenCV: Computer Vision with the OpenCV Library I can't find the best way to detect red color in different illumination or background. I found that there's YCbCr color space which is good for red or blue color detection (actually I need to detect blue color too). The problem is that I can't figure out which threshold to use in different lightning. For example in sunny weather this threshold equals 210 (from 255), when in cloudly weather this threshold equals 130. I use OpenCV library to implement this. Thanks for any help or advice. Yes, HSV is usually used for such purpose. In HSV you can tell that whatever is brightness etc, red is what is needed. I also recommend to look into two places. One is simple tutorial and another is to take a book Learning OpenCV and use examples of histograms from there. They do exactly what you need. Using HSV and Histograms makes your solution solid. i have been given a project where i will need to write code such that it parts of images. For example the project will require me to extract a river part from the scenery or so. I have no experience in this context. Please tell me where do i start studying form. Which are good books? Which technologies will i need to learn. What are the tools that are helpful? openCV is probably the most complete free image processing library. There is also a book which describes both the library and some image processing techniques. This is a reasonably complex problem, not exactly graduate research but challenging! See this question for a list of other books. I want to create a simple program that could calculate transformation of camera based on recorded video. The idea is that I could put some picture on top of the video and transformation of the picture will be matching the image in the video. I was looking at optical flow, but then can not figure out how to calculate transformations (translate, scale, rotation) based on the results. What would be the best way of doing it? It's called pose estimation - there is a tutorial on the POSIT algorithm It's covered in the openCV book if you can get hold of a copy The pixel value of a colored image represents the total of the Red , green , blue component effect . I want to extract the exact value for each component using opencv, Please suggest ! It's all in the OpenCV FAQ Wiki: Suppose, we have 8-bit 3-channel image I (IplImage* img): I(x,y)blue ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3] I(x,y)green ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3+1] I(x,y)red ~ ((uchar*)(img->imageData + img->widthStep*y))[x*3+2] You might also want to get a copy of O'Reilly's Learning OpenCV and read it if you're planning to do any serious work with OpenCV - it will save a lot of time on very basic questions such as the above. Within my project I'm using the camera function of the iPhone. I'd like to take a picture of a card (Rectangle shape). After I take this picture I'd like to scale and fit this card to a new image. Can anyone point me in the right direction for making these functions? (are there any libraries or so?) Help is greatly appreciated I'm rather novice in C++ and I must realize this schoolar project : Assume an image in a document containing both texts and images. There should be a program written in C++ whose the goal is to load the document and extract separately texts and images in order to output it in some target destinations like UI or file. Furthermore, if image contains any texts like legends, program should be able to extract it separately too. Is there an existing c++ library that respond to those requirements ? No doubt in that, use OpenCV. But remember, you have a long way to go. 1. First of all, you should be good in C++ and object oriented programming. Well, if you are not good, try to learn it first. Check out following link for some best resources : What are good online resources or tutorials to learn C++ 2. Then get OpenCV and install Check out OpenCV homepage to get info about downloading and installing OpenCV. 3. Now And always, Google is your best friend. Ask everything there first. Come here only when you are lost in your path. Acquire all the above things. Then you will be really good in OpenCV and i am sure you will enjoy its power. Once you are done with these, you will get enough idea on realizing your project.( Otherwise, you will post new questions every day asking codes to realize your project, which will be useless for you. ) For your understanding, your project include advanced things like Optical Character Recognition. It is a big topic. So build yourself from basics. And it will take time. All the best. 3d3d-reconstructionalgorithmanalysisandroidartificial-intelligenceaugmented-realitybackgroundbackground-imagebackground-subtractioncc++cameracard.iocmakecolorscompilationcomputer-visionedge-detectiongraphicsimageimage-processingimage-recognitionimage-segmentationiosiphonejavajavacvlanguage-agnosticmakefileobject-recognitionocropen-sourceopencvopencvdotnetpattern-matchingpattern-recognitionphotogrammetrypythonsignal-processingskinstereo-3dtesseracttic-tac-toevideo-processing
http://www.dev-books.com/book/book?isbn=0596516134&name=Learning-OpenCV
CC-MAIN-2017-39
en
refinedweb
JOHN M. APPLETON, PLAINTIFF,V.UNITED STATES OF AMERICA, DEFENDANT. The opinion of the court was delivered by: Urbina, District Judge. MEMORANDUM OPINION Denying the Plaintiffs Renewed Motion for Summary Judgment on Count 2; Denying the Defendant's Renewed Motion for Summary Judgment on Count 2 I. INTRODUCTION This matter is before the court upon cross-motions for summary judgment on the sole remaining count of the complaint, count 2. The plaintiff, John M. Appleton, filed a three-count complaint alleging negligence and arbitrary and capricious exercise of power by the U.S. Treasury Department's Bureau of Alcohol Tobacco and Firearms ("ATF") and the U.S. State Department (collectively, "the Government"). In 1994, Mr. Appleton filed five applications for permits to import ammunition originally made for the South-African government. Mr. Appleton did not know exactly who had made the ammunition, so on his applications he listed "State Arsenal, South Africa", a generic term which he claims is accepted by firearms dealers and by the ATF when more specific information is not available. So far as the record currently discloses, it appears that the ATF examiner, Ms. Frances Burroughs,*fn1 did not conduct an investigation into the identity of the manufacturer. The ATF granted Mr. Appleton's import permits in 1994 and 1995. Relying on those permits, Mr. Appleton contracted to resell the ammunition to a businessman in Illinois. When the ammunition arrived in the United States, however, the ATF investigated to see if it could identify the manufacturer more specifically than "State Arsenal, South Africa." Based on information the ATF requested and received from Mr. Appleton, the agency discovered that the ammunition had been manufactured by Pretoria Metal Pressings ("PMP"), an entity which had been "debarred" by State under the Arms Export Control Act ("AECA"), 22 U.S.C. § 2778 et seq. As a consequence of the debarment, it was illegal to import arms manufactured by PMP. Accordingly, ATF revoked Mr. Appleton's import permits. Because it was illegal to import the ammunition without the permits, Mr. Appleton could comply with the law only by breaching his resale contract, which he did. Mr. Appleton alleged that the State Department acted arbitrarily by debarring PMP and by doing so without notice. He further alleged that ATF's revocation of his permits interfered with his resale contract. See Compl. Counts 1 and 3. Lastly, he alleged that ATF was negligent in approving his applications in the first place, i.e., in "failing to determine that some state arsenals of South Africa were ineligible for ammunition import permit approval." See Compl. Count 2, ¶ 23. The case is unusual in this respect because Mr. Appleton is essentially arguing that the ATF should have denied his import applications. Pursuant to the Federal Tort Claims Act ("FTCA"), 28 U.S.C. § 1346(b)(1), 2671-2680, the Government asked the court to dismiss the complaint for failure to state a claim. Specifically, the Government contended that the FTCA shields it from suit for actions taken in the performance of a "discretionary function", and for actions which allegedly interfere with contract rights. Alternatively, the Government contended that Mr. Appleton was contributorily negligent in the approval of the permits, because he should have supplied more information about the origin of the ammunition. (See Mot. to Dis. at 1-2). Mr. Appleton opposed the motion and filed his own motion for summary judgment. Counts 1 and 3 Dismissed. By Memorandum Opinion and Order dated August 31, 1999, the court granted in part and denied in part the Government's motion to dismiss. Specifically, the court held that the FTCA's contract interference exception, 28 U.S.C. § 2680(h), barred Mr. Appleton's claim that ATF interfered with his contractual relations with a third party. Accordingly, the court dismissed counts One and Three and denied the plaintiff's motion for summary judgment on those counts. Count 2: ATF's Discretion. Secondly, the court found that the record left a genuine issue as to whether or not ATF employees exercised discretion in approving Mr. Appleton's import applications. Accordingly, the court denied without prejudice the Government's motion to dismiss count two (the negligence claim) and permitted Mr. Appleton to conduct discovery to obtain evidence on the discretion issue. Count 2: Negligence and Contributory Negligence. Lastly, the court found there was a genuine issue as to whether or not ATF and/or Mr. Appleton acted negligently. Accordingly, the court denied without prejudice the plaintiffs motion for summary judgment on count 2 and authorized discovery on the issue of each party's negligence. As directed by the August 31, 1999 Order, Mr. Appleton and the Government conducted supplemental discovery and filed renewed motions for summary judgment on count 2. For the reasons set forth below, the court will deny both parties' motions.*fn2 II. BACKGROUND Mr. Appleton is an American businessman licensed to buy and sell arms under the Arms Export Control Act ("AECA"), 22 U.S.C. § 2778 and 22 C.F.R. § 120130. In 1994, British arms broker Tony Slatter offered to sell Mr. Appleton ammunition imported from South Africa. Mr. Appleton submitted five "Form 6" import permit applications to ATF listing "State Arsenal, Republic of South Africa" as the manufacturer of the ammunition. (See Appleton Dec. ¶ 6.) ATF approved the permits between October 1994 and January 1995. Mr. Appleton then contracted to resell the ammunition to an arms dealer in Illinois. (See Comp. ¶ 14.) Mr. Appleton maintains that he supplied all the information he could reasonably obtain about the identity of the manufacturer. Mr. Appleton asked Mr. Slatter for information about Slatter's supplier and about the original manufacturer. Mr. Slatter professed not to know who the manufacturer was and also indicated that he was unwilling to divulge the identity of his supplier for proprietary reasons. In other words, Slatter refused to identify his supplier out of concern that Mr. Appleton would contact the supplier directly and "cut out" Slatter. (See Pl.'s Mot. for Summ.J. at 5-6.)*fn3 Nonetheless, the Government maintains that Mr. Appleton could have asked Mr. Slatter for additional information at the time of their negotiations which would have revealed that the ammunition was in a crate marked "ARMSCOR." ATF was able to determine the manufacturer based on Mr. Appleton's submission of a drawing of the "headstamp" markings on the ammunition during a subsequent investigation. The ATF argues that Mr. Appleton should have requested a sample of the ammunition and/or a reproduction of the headstamp markings from Mr. Slatter before submitting his applications. (See Opp. to Pl.'s Mot. for Summ.J. at 8-10.) When the ammunition arrived in the United States in February 1995, ATF initiated an investigation into the identity of the manufacturer. ATF discovered that the ammunition had been manufactured by Pretoria Metal Pressings Ltd. ("PMP") in 1983, delivered to the South African Defense Force directly after production and sold at some unspecified date to a British concern called TSF. (See Pl.'s Mot. for Summ.J., Ex. 20.) Following a State Department policy which debarred certain arms manufacturers related to the defunct South African apartheid regime, including PMP, ATF revoked Mr. Appleton's permits in March 1995. See 27 C.F.R. § 47.55. Subsequently, complying with the legal prohibition on importing PMP-made ammunition, Mr. Appleton breached his contract to resell the ammunition. In May 1996, Mr. Appleton filed an administrative claim with ATF. ATF denied the claim in August 1997. Mr. Appleton subsequently initiated the instant action. III.
http://dc.findacase.com/research/wfrmDocViewer.aspx/xq/fac.20000519_0000070.DDC.htm/qx
CC-MAIN-2017-39
en
refinedweb
In the last post we looked at how Generative Adversarial Networks could be used to learn representations of documents in an unsupervised manner. In evaluation, we found that although the model was able to learn useful representations, it did not perform as well as an older model called DocNADE. In this post we give a brief overview of the DocNADE model, and provide a TensorFlow implementation. Neural Autoregressive Distribution Estimation Recent advances in neural autoregressive generative modeling has lead to impressive results at modeling images and audio, as well as language modeling and machine translation. This post looks at a slightly older take on neural autoregressive models – the Neural Autoregressive Distribution Estimator (NADE) family of models. An autoregressive model is based on the fact that any D-dimensional distribution can be factored into a product of conditional distributions in any order: \(p(\mathbf{x}) = \prod_{d=1}^{D} p(x_d | \mathbf{x}_{<d})\) where \(\mathbf{x}_{<d}\) represents the first \(d-1\) dimensions of \(\mathbf{x}\) in the current ordering. We can therefore create an autoregressive generative model by just parameterising all of the separate conditionals in this equation. One of the more simple ways to do this is to take a sequence of binary values, and assume that the output at each timestep is just a linear combination of the previous values. We can then pass this weighted sum through a sigmoid to get the output probability for each timestep. This sort of model is called a fully-visible sigmoid belief network (FVSBN): A fully visible sigmoid belief network. Figure taken from the NADE paper. Here we have binary inputs \(v\) and generated binary outputs \(\hat{v}\). \(\hat{v_3}\) is produced from the inputs \(v_1\) and \(v_2\). NADE can be seen as an extension of this, where instead of a linear parameterisation of each conditional, we pass the inputs through a feed-forward neural network: Neural Autoregressive Distribution Estimator. Figure taken from the NADE paper. Specifically, each conditional is parameterised as: \(p(x_d | \mathbf{x_{<d}}) = \text{sigm}(b_d + \mathbf{V}_{d,:} \mathbf{h}_d)\) \(\mathbf{h}_d = \text{sigm}(c + \mathbf{W}_{:,<d} \mathbf{x}_{<d})\) where \(\mathbf{W}\), \(\mathbf{V}\), \(b\) and \(c\) are learnable parameters of the model. This can then be trained by minimising the negative log-likelihood of the data. When compared to the FVSBN there is also additional weight sharing in the input layer of NADE: each input element uses the same parameters when computing the various output elements. This parameter sharing was inspired by the Restricted Boltzmann Machine, but also has some computational benefits – at each timestep we only need to compute the contribution of the new sequence element (we don’t need to recompute all of the preceding elements). Modeling documents with NADE In the standard NADE model, the input and outputs are binary variables. In order to work with sequences of text, the DocNADE model extends NADE by considering each element in the input sequence to be a multinomial observation – or in other words one of a predefined set of tokens (from a fixed vocabulary). Likewise, the output must now also be multinomial, and so a softmax layer is used at the output instead of a sigmoid. The DocNADE conditionals are then given by: \(p(x | \mathbf{x_{<d}}) = \frac{\text{exp} (b_{w_d} + \mathbf{V}_{w_d,:} \mathbf{h}_d) } {\sum_w \text{exp} (b_w + \mathbf{V}_{w,:} \mathbf{h}_d) }\) \(\mathbf{h}_d = \text{sigm}\Big(c + \sum_{k<d} \mathbf{W}_{:,x_k} \Big)\) An additional type of parameter sharing has been introduced in the input layer – each element will have the same weights no matter where it appears in the sequence (so if the word “cat” appears input positions 2 and 10, it will use the same weights each time). There is another way to look at this however. We now have a single set of parameters for each word no matter where it appears in the sequence, and there is a common name for this architectural pattern – a word embedding. So we can view DocNADE a way of constructing word embeddings, but with a different set of constraints than we might be used to from models like Word2Vec. For each input in the sequence, DocNADE uses the sum of the embeddings from the previous timesteps (passed through a sigmoid nonlinearity) to predict the word at the next timestep. The final representation of a document is just the value of the hidden layer at the final timestep (or in the other words, the sum of the word embeddings passed through a nonlinearity). There is one more constraint that we have not yet discussed – the sequence order. Instead of training on sequences of words in the order that they appear in the document, as we do when training a language model for example, DocNADE trains on random permutations of the words in a document. We therefore get embeddings that are useful for predicting what words we expect to see appearing together in a full document, rather than focusing on patterns that arise due to syntax and word order (or focusing on smaller contexts around each word). An Overview of the TensorFlow code The full source code for our TensorFlow implementation of DocNADE is available on Github, here we will just highlight some of the more interesting parts. First we do an embedding lookup for each word in our input sequence ( x). We initialise the embeddings to be uniform in the range [0, 1.0 / (vocab_size * hidden_size)], which is taken from the original DocNADE source code. I don’t think that this is mentioned anywhere else, but we did notice a slight performance bump when using this instead of the default TensorFlow initialisation. with tf.device('/cpu:0'): max_embed_init = 1.0 / (params.vocab_size * params.hidden_size) W = tf.get_variable( 'embedding', [params.vocab_size, params.hidden_size], initializer=tf.random_uniform_initializer(maxval=max_embed_init) ) self.embeddings = tf.nn.embedding_lookup(W, x) Next we compute the pre-activation for each input element in our sequence. We transpose the embedding sequence so that the sequence length elements are now the first dimension (instead of the batch), then we use the higher-order tf.scan function to apply sum_embeddings to each sequence element in turn. This replaces each embedding with sum of that embedding and the previously summed embeddings. def sum_embeddings(previous, current): return previous + current h = tf.scan(sum_embeddings, tf.transpose(self.embeddings, [1, 2, 0])) h = tf.transpose(h, [2, 0, 1]) h = tf.concat([ tf.zeros([batch_size, 1, params.hidden_size], dtype=tf.float32), h ], axis=1) h = h[:, :-1, :] We then initialise the bias terms, prepend a zero vector to the input sequence (so that the first element is generated from just the bias term), and apply the nonlinearity. bias = tf.get_variable( 'bias', [params.hidden_size], initializer=tf.constant_initializer(0) ) h = tf.tanh(h + bias) Finally we compute the sequence loss, which is masked according to the length of each sequence in the batch. Note that for optimisation, we do not normalise this loss by the length of each document. This leads to slightly better results as mentioned in the paper, particularly for the document retrieval evaluation (discussed below). h = tf.reshape(h, [-1, params.hidden_size]) logits = linear(h, params.vocab_size, 'softmax') loss = masked_sequence_cross_entropy_loss(x, seq_lengths, logits) Experiments As DocNADE computes the probability of the input sequence, we can measure how well it is able to generalise by computing the probability of a held-out test set. In the paper the actual metric that they use is the average perplexity per word, which for time \(t\), input \(x\) and test set size \(N\) is given by: \(\text{exp} \big(-\frac{1}{N} \sum_{t} \frac{1}{|x_t|} \log p(x_t) \big)\) As in the paper, we evaluate DocNADE on the same (small) 20 Newsgroups dataset that we used in our previous post, which consists of a collection of around 19000 postings to 20 different newsgroups. The published version of DocNADE uses a hierarchical softmax on this dataset, despite the fact that they use a small vocabulary size of 2000. There is not much need to approximate a softmax of this size when training relatively small models on modern GPUs, so here we just use a full softmax. This makes a large difference in the reported perplexity numbers – the published implementation achieves a test perplexity of 896, but with the full softmax we can get this down to 579. To note how big an improvement this is, the following table shows perplexity values on this task for models that have been published much more recently: One additional change from the evaluation in the paper is that we evaluate the average perplexity over the full test set (in the paper they just take a random sample of 50 documents). We were expecting to see an improvement due to the use of the full softmax, but not an improvement of quite this magnitude. Even when using a sampled softmax on this task instead of the full softmax, we see some big improvements over the published results. This suggests that the hierarchical softmax formulation that was used in the original paper was a relatively poor approximation of the true softmax (but it’s possible that there is a bug somewhere in our implementation, if you find any issues please let us know). We also see an improvement on the document retrieval evaluation results with the full softmax: For the retrieval evaluation, we first. Note: for working with larger vocabularies, the current implementation supports approximating the softmax using the sampled softmax. Conclusion We took another look a DocNADE, noting that it can be viewed as another way to train word embeddings. We also highlighted the potential for large performance boosts with older models due simply to modern computational improvements – in this case because it is no longer necessary to approximate smaller vocabularies. The full source code for the model is available on Github.
http://blog.aylien.com/author/john/
CC-MAIN-2017-39
en
refinedweb
The Chinese state-owned company Sinohydro is poised to begin building a 110-meter-high hydroelectric dam on Kampot's Kamchay River next month, and locals are giving voice to a range of concerns. Townsfolk fear that the giant dam, 15km upriver from Kampot, could burst, drowning them all. Environmentalists point out that the dam will flood more than 1,000 hectares of forest in Bokor National Park. Durian farmers on land below the dam site fear their orchards will be ruined by fluctuating river flows. And vendors at the Teuk Chhu waterfall downriver from the dam are afraid its construction will deter tourists. Khuon Sambath, 49, a villager in Mak Prang commune, who has been farming durian for more than a decade, says he is concerned that the dam will make seasonal water flows more extreme: his durian trees could be destroyed by the land being saturated in the rainy season then desiccating in the dry season. "Not only my durian but all people in the commune will be affected by the dam," Sambath said. "I will complain to the company and government if my durian farm is damaged when the dam is built." A food seller at Teuk Chhu resort said she is happy that the dam ultimately will provide her with electricity, but worries that while it is being built the river will stop flowing, tourists will stop coming and she will have to close her shop. "I want the company to make sure that the river flows as usual, so tourists will keep coming to swim," she said. The government licensed Sinohydro to build the dam in February 2006 and it is expected to be finished by 2010. Sinohydro general affairs officer Kim Sovan said the company was investing $280 million on the project and will run it for 40 years on a build-operate-transfer basis. Sovan said a feasibility study is now complete and Sinohydro will begin construction next month. The company is bringing construction equipment from China. The government strongly supports the project, he said. "Our firm, the government, and local residents will all benefit from the project," Sovan said. "We will develop Teuk Chhu to become the most beautiful tourism resort." Bun Heng, director of the environment department of Kampot, said the dam will affect some people living around the Teuk Chhou waterfall and people cannot enter to cut bamboo in the area any more. But he said a committee set up to evaluate potential damage showed that it would not be serious. "The government has a policy to compensate to all affected residents," Heng said. "What we are doing will not affect their living conditions." Heng said the dam will not pollute the water downstream where tourists swim, and will help to prevent flooding in Kampot town in the rainy season. Sovan said Sinohydro was aware of likely adverse effects on residents, but said it was the government's responsibility to compensate them. Although visitors might be deterred from visiting Teuk Chhu during the three years of construction, ultimately it would be a great tourist attraction because it would be the first big dam built in the country, and easily accessible. "I think the construction process will go well and will be complete on time," Sovan said. Taing Sophanara, officer in charge of environment of SAWAC Consultants for Development, a company commissioned to assess the environmental impact of the dam, said farms in the area would not be seriously affected, but the dam will damage thousands of hectares of forest. Sinohydro will replant trees every year surrounding the Bokor National Park, he said. "What people are concerned about is the collapse of the dam, because we have never had anything like this before," Sophanara said. "The Chinese firm assures us that the dam will be safe. I think it will be beneficial to local people when it is complete." Sophanara said that because of the great cost of building the dam, the price of the electricity it produces will be higher than that imported from neighboring countries. But it would be a sustainable source of power produced within the country, and it was important to diversify sources of electricity. The wholesale price of Kamchay power would be about 700 riel per kilowatt hour, compared with 600 to 650 riel/kWh for electricity bought from Vietnam. Sophanara said Canada and Russia had each explored the possibility of building a Kamchay hydroelectric dam since 1950, and Japan had done so in 1992. All had rejected it because of the high cost. "The government decided to allow the Chinese company to build the dam to reduce the high price of electricity produced by oil-driven generators," Sophanara said. "You can see the price of electricity at the moment is very expensive." Sinohydro's Sovan said the Kamchay hydroelectric dam will produce 193 megawatts and will sell directly to Electricité du Cambodge (EDC). The retail price of the electricity for local people will require approval by the Electricity Authority of Cambodia. Sovan said when the Kamchay dam is producing power the government will reduce the import of electricity from neighboring countries. Chhun Hin, Kampot director of the Industry, Mines and Energy Department, said the government had prepared 1,300 hectares above the dam for stocking water. Sinohydro would fill the dam in three stages, the first to produce 180MW, the second another 3MW, and third the final 10MW. Hin said the power from Kamchay hydroelectric dam will supply southern provinces and municipalities - Kampot, Kep, Takeo and Sihanoukville - and also Phnom Penh. Because of the shortage of electricity Cambodia needed to buy power from Vietnam at present, but that was just temporary. "The residents in the province here face electricity shortages, and the price is high at 1,200 riel per kWh," Hin said, "They have protested many times demanding that the price go down but it is impossible." He said that to bridge the gap until the Kamchay dam begins producing power in 2010, EDC had contracted with a local company to bring electricity from Vietnam to Kep and to Kampot to meet demand. Lam Du Son, deputy director of Electricity of Vietnam (EVN) has told the Post previously that EVN sold 2.7 million kWh of electricity to Cambodia in 2002 but in the first ten months of 2006 that had climbed to 36.4 million kWh. Houng Chantha, head of the technical office of corporate planning and projects at EDC also told the Post previously that EDC had encouraged private companies to invest in power supply to meet increasing demand. At the border with Vietnam in Chrey Thom district of Kandal, local company Anco Brother had invested to buy electricity from Vietnam and sell it to more than 10,000 families in the district. Hin also said that in 2007 the Kampot Cement Factory will run its own 20MW oil-driven generator, and people in two neighboring districts will be able to buy electricity from the factory.
http://www.phnompenhpost.com/national/kampot-poised-enter-world-hydroelectric-power
CC-MAIN-2017-39
en
refinedweb
Graphics routines - Colors - Locking and pixel formats - Bitmap creation - Bitmap properties - Drawing operations - al_clear_to_color - al_clear_depth_buffer - al_draw_bitmap - al_draw_tinted_bitmap - al_draw_bitmap_region - al_draw_tinted_bitmap_region - al_draw_pixel - al_draw_rotated_bitmap - al_draw_tinted_rotated_bitmap - al_draw_scaled_rotated_bitmap - al_draw_tinted_scaled_rotated_bitmap - al_draw_tinted_scaled_rotated_bitmap_region - al_draw_scaled_bitmap - al_draw_tinted_scaled_bitmap - al_get_target_bitmap - al_put_pixel - al_put_blended_pixel - al_set_target_bitmap - al_set_target_backbuffer - al_get_current_display - Blending modes - Clipping - Graphics utility functions - Deferred drawing - Image I/O - Render State These functions are declared in the main Allegro header file: #include <allegro5/allegro.h> Colors ALLEGRO_COLOR typedef struct ALLEGRO_COLOR ALLEGRO_COLOR; An ALLEGRO_COLOR structure describes a color in a device independent way. Use al_map_rgb et al. and al_unmap_rgb et al. to translate from and to various color representations. al_map_rgb ALLEGRO_COLOR al_map_rgb( unsigned char r, unsigned char g, unsigned char b) Convert r, g, b (ranging from 0-255) into an ALLEGRO_COLOR, using 255 for alpha. See also: al_map_rgba, al_map_rgba_f, al_map_rgb_f al_map_rgb_f ALLEGRO_COLOR al_map_rgb_f(float r, float g, float b) Convert r, g, b, (ranging from 0.0f-1.0f) into an ALLEGRO_COLOR, using 1.0f for alpha. See also: al_map_rgba, al_map_rgb, al_map_rgba_f al_map_rgba ALLEGRO_COLOR al_map_rgba( unsigned char r, unsigned char g, unsigned char b, unsigned char a) Convert r, g, b, a (ranging from 0-255) into an ALLEGRO_COLOR. See also: al_map_rgb, al_premul_rgba, al_map_rgb_f al_premul_rgba ALLEGRO_COLOR al_premul_rgba( unsigned char r, unsigned char g, unsigned char b, unsigned char a) This is a shortcut for al_map_rgba(r * a / 255, g * a / 255, b * a / 255,: int r = 255; int g = 0; int b = 0; int a = 127; ALLEGRO_COLOR c = al_premul_rgba(r, g, b, a); /* Draw the bitmap tinted red and half-transparent. */ al_draw_tinted_bitmap(bmp, c, 0, 0, 0); Since: 5.1.12 See also: al_map_rgba, al_premul_rgba_f al_map_rgba_f ALLEGRO_COLOR al_map_rgba_f(float r, float g, float b, float a) Convert r, g, b, a (ranging from 0.0f-1.0f) into an ALLEGRO_COLOR. See also: al_map_rgba, al_premul_rgba_f, al_map_rgb_f al_premul_rgba_f ALLEGRO_COLOR al_premul_rgba_f(float r, float g, float b, float a) This is a shortcut for al_map_rgba_f(r * a, g * a, b * a,: float r = 1; float g = 0; float b = 0; float a = 0.5; ALLEGRO_COLOR c = al_premul_rgba_f(r, g, b, a); /* Draw the bitmap tinted red and half-transparent. */ al_draw_tinted_bitmap(bmp, c, 0, 0, 0); Since: 5.1.12 See also: al_map_rgba_f, al_premul_rgba al_unmap_rgb void al_unmap_rgb(ALLEGRO_COLOR color, unsigned char *r, unsigned char *g, unsigned char *b) Retrieves components of an ALLEGRO_COLOR, ignoring alpha. Components will range from 0-255. See also: al_unmap_rgba, al_unmap_rgba_f, al_unmap_rgb_f al_unmap_rgb_f void al_unmap_rgb_f(ALLEGRO_COLOR color, float *r, float *g, float *b) Retrieves components of an ALLEGRO_COLOR, ignoring alpha. Components will range from 0.0f-1.0f. See also: al_unmap_rgba, al_unmap_rgb, al_unmap_rgba_f al_unmap_rgba void al_unmap_rgba(ALLEGRO_COLOR color, unsigned char *r, unsigned char *g, unsigned char *b, unsigned char *a) Retrieves components of an ALLEGRO_COLOR. Components will range from 0-255. See also: al_unmap_rgb, al_unmap_rgba_f, al_unmap_rgb_f al_unmap_rgba_f void al_unmap_rgba_f(ALLEGRO_COLOR color, float *r, float *g, float *b, float *a) Retrieves components of an ALLEGRO_COLOR. Components will range from 0.0f-1.0f. See also: al_unmap_rgba, al_unmap_rgb, al_unmap_rgb_f Locking and pixel formats ALLEGRO_LOCKED_REGION typedef struct ALLEGRO_LOCKED_REGION ALLEGRO_LOCKED_REGION; Users who wish to manually edit or read from a bitmap are required to lock it first. The ALLEGRO_LOCKED_REGION structure represents the locked region of the bitmap. This call will work with any bitmap, including memory bitmaps. typedef struct ALLEGRO_LOCKED_REGION { void *data; int format; int pitch; int pixel_size; } ALLEGRO_LOCKED_REGION; data points to the leftmost pixel of the first row (row 0) of the locked region. For blocked formats, this points to the leftmost block of the first row of blocks. format indicates the pixel format of the data. pitch gives the size in bytes of a single row (also known as the stride). The pitch may be greater than width * pixel_sizedue to padding; this is not uncommon. It is also not uncommon for the pitch to be negative (the bitmap may be upside down). For blocked formats, 'row' refers to the row of blocks, not of pixels. pixel_size is the number of bytes used to represent a single block of pixels for the pixel format of this locked region. For most formats (and historically, this used to be true for all formats), this is just the size of a single pixel, but for blocked pixel formats this value is different. See also: al_lock_bitmap, al_lock_bitmap_region, al_unlock_bitmap, ALLEGRO_PIXEL_FORMAT ALLEGRO_PIXEL_FORMAT typedef enum ALLEGRO_PIXEL_FORMAT Pixel formats. Each pixel format specifies the exact size and bit layout of a pixel in memory. Components are specified from high bits to low bits, so for example a fully opaque red pixel in ARGB_8888 format is 0xFFFF0000. Note: The pixel format is independent of endianness. That is, in the above example you can always get the red component with (pixel & 0x00ff0000) >> 16 But you can not rely on this code: *(pixel + 2) It will return the red component on little endian systems, but the green component on big endian systems. Also note that Allegro's naming is different from OpenGL naming here, where a format of GL_RGBA8 merely defines the component order and the exact layout including endianness treatment is specified separately. Usually GL_RGBA8 will correspond to ALLEGRO_PIXEL_ABGR_8888 though on little endian systems, so care must be taken (note the reversal of RGBA <-> ABGR). The only exception to this ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE which will always have the components as 4 bytes corresponding to red, green, blue and alpha, in this order, independent of the endianness. Some of the pixel formats represent compressed bitmap formats. Compressed bitmaps take up less space in the GPU memory than bitmaps with regular (uncompressed) pixel formats. This smaller footprint means that you can load more resources into GPU memory, and they will be drawn somewhat faster. The compression is lossy, however, so it is not appropriate for all graphical styles: it tends to work best for images with smooth color gradations. It is possible to compress bitmaps at runtime by passing the appropriate bitmap format in al_set_new_bitmap_format and then creating, loading, cloning or converting a non-compressed bitmap. This, however, is not recommended as the compression quality differs between different GPU drivers. It is recommended to compress these bitmaps ahead of time using external tools and then load them compressed. Unlike regular pixel formats, compressed pixel formats are not laid out in memory one pixel row at a time. Instead, the bitmap is subdivided into rectangular blocks of pixels that are then laid out in block rows. This means that regular locking functions cannot use compressed pixel formats as the destination format. Instead, you can use the blocked versions of the bitmap locking functions which do support these formats. It is not recommended to use compressed bitmaps as target bitmaps, as that operation cannot be hardware accelerated. Due to proprietary algorithms used, it is typically impossible to create compressed memory bitmaps. - ALLEGRO_PIXEL_FORMAT_ANY - Let the driver choose a format. This is the default format at program start. - ALLEGRO_PIXEL_FORMAT_ANY_NO_ALPHA - Let the driver choose a format without alpha. - ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA - Let the driver choose a format with alpha. - ALLEGRO_PIXEL_FORMAT_ANY_15_NO_ALPHA - Let the driver choose a 15 bit format without alpha. - ALLEGRO_PIXEL_FORMAT_ANY_16_NO_ALPHA - Let the driver choose a 16 bit format without alpha. - ALLEGRO_PIXEL_FORMAT_ANY_16_WITH_ALPHA - Let the driver choose a 16 bit format with alpha. - ALLEGRO_PIXEL_FORMAT_ANY_24_NO_ALPHA - Let the driver choose a 24 bit format without alpha. - ALLEGRO_PIXEL_FORMAT_ANY_32_NO_ALPHA - Let the driver choose a 32 bit format without alpha. - ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA - Let the driver choose a 32 bit format with alpha. - ALLEGRO_PIXEL_FORMAT_ARGB_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_RGBA_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_ARGB_4444 - 16 bit - ALLEGRO_PIXEL_FORMAT_RGB_888 - 24 bit - ALLEGRO_PIXEL_FORMAT_RGB_565 - 16 bit - ALLEGRO_PIXEL_FORMAT_RGB_555 - 15 bit - ALLEGRO_PIXEL_FORMAT_RGBA_5551 - 16 bit - ALLEGRO_PIXEL_FORMAT_ARGB_1555 - 16 bit - ALLEGRO_PIXEL_FORMAT_ABGR_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_XBGR_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_BGR_888 - 24 bit - ALLEGRO_PIXEL_FORMAT_BGR_565 - 16 bit - ALLEGRO_PIXEL_FORMAT_BGR_555 - 15 bit - ALLEGRO_PIXEL_FORMAT_RGBX_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_XRGB_8888 - 32 bit - ALLEGRO_PIXEL_FORMAT_ABGR_F32 - 128 bit - ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE - Like the version without _LE, but the component order is guaranteed to be red, green, blue, alpha. This only makes a difference on big endian systems, on little endian it is just an alias. - ALLEGRO_PIXEL_FORMAT_RGBA_4444 - 16bit - ALLEGRO_PIXEL_FORMAT_SINGLE_CHANNEL_8 - A single 8-bit channel. A pixel value maps onto the red channel when displayed, but it is undefined how it maps onto green, blue and alpha channels. When drawing to bitmaps of this format, only the red channel is taken into account. Allegro may have to use fallback methods to render to bitmaps of this format. This pixel format is mainly intended for storing the color indices of an indexed (paletted) image, usually in conjunction with a pixel shader that maps indices to RGBA values. Since 5.1.2. - ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT1 - Compressed using the DXT1 compression algorithm. Each 4x4 pixel block is encoded in 64 bytes, resulting in 6-8x compression ratio. Only a single bit of alpha per pixel is supported. Since 5.1.9. - ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT3 - Compressed using the DXT3 compression algorithm. Each 4x4 pixel block is encoded in 128 bytes, resulting in 4x compression ratio. This format supports sharp alpha transitions. Since 5.1.9. - ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT5 - Compressed using the DXT5 compression algorithm. Each 4x4 pixel block is encoded in 128 bytes, resulting in 4x compression ratio. This format supports smooth alpha transitions. Since 5.1.9. See also: al_set_new_bitmap_format, al_get_bitmap_format al_get_pixel_size int al_get_pixel_size(int format) Return the number of bytes that a pixel of the given format occupies. For blocked pixel formats (e.g. compressed formats), this returns 0. See also: ALLEGRO_PIXEL_FORMAT, al_get_pixel_format_bits al_get_pixel_format_bits int al_get_pixel_format_bits(int format) Return the number of bits that a pixel of the given format occupies. For blocked pixel formats (e.g. compressed formats), this returns 0. See also: ALLEGRO_PIXEL_FORMAT, al_get_pixel_size al_get_pixel_block_size int al_get_pixel_block_size(int format) Return the number of bytes that a block of pixels with this format occupies. Since: 5.1.9. See also: ALLEGRO_PIXEL_FORMAT, al_get_pixel_block_width, al_get_pixel_block_height al_get_pixel_block_width int al_get_pixel_block_width(int format) Return the width of the the pixel block for this format. Since: 5.1.9. See also: ALLEGRO_PIXEL_FORMAT, al_get_pixel_block_size, al_get_pixel_block_height al_get_pixel_block_height int al_get_pixel_block_height(int format) Return the height of the the pixel block for this format. Since: 5.1.9. See also: ALLEGRO_PIXEL_FORMAT, al_get_pixel_block_size, al_get_pixel_block_width al_lock_bitmap ALLEGRO_LOCKED_REGION *al_lock_bitmap(ALLEGRO_BITMAP *bitmap, int format, int flags)_WRITEONLY - The locked region will not be read from. This can be faster if the bitmap is a video texture, as no data need to be read from the video card. You are required to fill in all pixels before unlocking the bitmap again, so be careful when using this flag... Note: While a bitmap is locked, you can not use any drawing operations on it (with the sole exception of al_put_pixel and al_put_blended_pixel). See also: ALLEGRO_LOCKED_REGION, ALLEGRO_PIXEL_FORMAT, al_unlock_bitmap, al_lock_bitmap_region, al_lock_bitmap_blocked, al_lock_bitmap_region_blocked al_lock_bitmap_region ALLEGRO_LOCKED_REGION *al_lock_bitmap_region(ALLEGRO_BITMAP *bitmap, int x, int y, int width, int height, int format, int flags) Like al_lock_bitmap, but only locks a specific area of the bitmap. If the bitmap is a video bitmap, only that area of the texture will be updated when it is unlocked. Locking only the region you indend to modify will be faster than locking the whole bitmap. Note: Using the ALLEGRO_LOCK_WRITEONLY with a blocked pixel format (i.e. formats for which al_get_pixel_block_width or al_get_pixel_block_height do not return 1) requires you to have the region be aligned to the block width for optimal performance. If it is not, then the function will have to lock the region with the ALLEGRO_LOCK_READWRITE instead in order to pad this region with valid data. See also: ALLEGRO_LOCKED_REGION, ALLEGRO_PIXEL_FORMAT, al_unlock_bitmap al_unlock_bitmap void al_unlock_bitmap(ALLEGRO_BITMAP *bitmap) Unlock a previously locked bitmap or bitmap region. If the bitmap is a video bitmap, the texture will be updated to match the system memory copy (unless it was locked read only). See also: al_lock_bitmap, al_lock_bitmap_region, al_lock_bitmap_blocked, al_lock_bitmap_region_blocked al_lock_bitmap_blocked ALLEGRO_LOCKED_REGION *al_lock_bitmap_blocked(ALLEGRO_BITMAP *bitmap, int flags) Like al_lock_bitmap, but allows locking bitmaps with a blocked pixel format (i.e. a format for which al_get_pixel_block_width or al_get_pixel_block_height do not return 1) in that format. To that end, this function also does not allow format conversion. For bitmap formats with a block size of 1, this function is identical to calling al_lock_bitmap(bmp, al_get_bitmap_format(bmp), flags). Note: Currently there are no drawing functions that work when the bitmap is locked with a compressed format. al_get_pixel will also not work. Since: 5.1.9 See also: al_lock_bitmap, al_lock_bitmap_region_blocked al_lock_bitmap_region_blocked ALLEGRO_LOCKED_REGION *al_lock_bitmap_region_blocked(ALLEGRO_BITMAP *bitmap, int x_block, int y_block, int width_block, int height_block, int flags) Like al_lock_bitmap_blocked, but allows locking a sub-region, for performance. Unlike al_lock_bitmap_region the region specified in terms of blocks and not pixels. Since: 5.1.9 See also: al_lock_bitmap_region, al_lock_bitmap_blocked Bitmap creation ALLEGRO_BITMAP typedef struct ALLEGRO_BITMAP ALLEGRO_BITMAP; Abstract type representing a bitmap (2D image). al_create_bitmap ALLEGRO_BITMAP *al_create_bitmap(int w, int h) Creates a new bitmap using the bitmap format and flags for the current thread. Blitting between bitmaps of differing formats, or blitting between memory bitmaps and display bitmaps may be slow. Unless you set the ALLEGRO_MEMORY_BITMAP flag, the bitmap is created for the current display. Blitting to another display may be slow. If a display bitmap is created, there may be limitations on the allowed dimensions. For example a DirectX or OpenGL backend usually has a maximum allowed texture size - so if bitmap creation fails for very large dimensions, you may want to re-try with a smaller bitmap. Some platforms also dictate a minimum texture size, which is relevant if you plan to use this bitmap with the primitives addon. If you try to create a bitmap smaller than this, this call will not fail but the returned bitmap will be a section of a larger bitmap with the minimum size... On some platforms the contents of video bitmaps may be lost when your application loses focus. Allegro has an internal mechanism to restore the contents of these video bitmaps, but it is not foolproof (sometimes bitmap contents can get lost permanently) and has performance implications. If you are using a bitmap as an intermediate buffer this mechanism may be wasteful. In this case, if you do not want Allegro to manage the bitmap contents for you, you can disable this mechanism by creating the bitmap with the ALLEGRO_NO_PRESERVE_TEXTURE flag. The bitmap contents are lost when you get the ALLEGRO_EVENT_DISPLAY_LOST and ALLEGRO_EVENT_DISPLAY_HALT_DRAWING and a should be restored when you get the ALLEGRO_EVENT_DISPLAY_FOUND and when you call al_acknowledge_drawing_resume on it to free any resources allocated for it. See also: al_set_new_bitmap_format, al_set_new_bitmap_flags, al_clone_bitmap, al_create_sub_bitmap, al_convert_memory_bitmaps, al_destroy_bitmap al_create_sub_bitmap ALLEGRO_BITMAP *al_create_sub_bitmap(ALLEGRO_BITMAP *parent, int x, int y, int w, int h) Creates a sub-bitmap of the parent, at the specified coordinates and of the specified size. A sub-bitmap is a bitmap that shares drawing memory with a pre-existing (parent) bitmap, but possibly with a different size and clipping settings. The sub-bitmap may originate off or extend past the parent bitmap. See the discussion in al_get_backbuffer about using sub-bitmaps of the backbuffer. The parent bitmap's clipping rectangles are ignored. If a sub-bitmap was not or cannot be created then NULL is returned. When you are done with using the sub-bitmap you must call al_destroy_bitmap on it to free any resources allocated for it. Note that destroying parents of sub-bitmaps will not destroy the sub-bitmaps; instead the sub-bitmaps become invalid and should no longer be used for drawing - they still must be destroyed with al_destroy_bitmap however. It does not matter whether you destroy a sub-bitmap before or after its parent otherwise. See also: al_create_bitmap al_clone_bitmap ALLEGRO_BITMAP *al_clone_bitmap(ALLEGRO_BITMAP *bitmap) Create a new bitmap with al_create_bitmap, and copy the pixel data from the old bitmap across. If the new bitmap is a memory bitmap, its projection bitmap is reset to be orthographic. See also: al_create_bitmap, al_set_new_bitmap_format, al_set_new_bitmap_flags, al_convert_bitmap al_convert_bitmap void al_convert_bitmap(ALLEGRO_BITMAP *bitmap) Converts the bitmap to the current bitmap flags and format. The bitmap will be as if it was created anew with al_create_bitmap but retain its contents. All of this bitmap's sub-bitmaps are also converted. If the new bitmap type is memory, then the bitmap's projection bitmap is reset to be orthographic. If this bitmap is a sub-bitmap, then it, its parent and all the sibling sub-bitmaps are also converted. Since: 5.1.0 See also: al_create_bitmap, al_set_new_bitmap_format, al_set_new_bitmap_flags, al_clone_bitmap al_convert_memory_bitmaps void al_convert_memory_bitmaps(void) If you create a bitmap when there is no current display (for example because you have not called al_create_display in the current thread) and are using the ALLEGRO_CONVERT_BITMAP bitmap flag (which is set by default) then the bitmap will be created successfully, but as a memory bitmap. This function converts all such bitmaps to proper video bitmaps belonging to the current display. Note that video bitmaps get automatically converted back to memory bitmaps when the last display is destroyed. This operation will preserve all bitmap flags except ALLEGRO_VIDEO_BITMAP and ALLEGRO_MEMORY_BITMAP. Since: 5.2.0 See also: al_convert_bitmap, al_create_bitmap al_destroy_bitmap void al_destroy_bitmap(ALLEGRO_BITMAP *bitmap) Destroys the given bitmap, freeing all resources used by it. This function does nothing if the bitmap argument is NULL. As a convenience, if the calling thread is currently targeting the bitmap then the bitmap will be untargeted first. The new target bitmap is unspecified. (since: 5.0.10, 5.1.6) Otherwise, it is an error to destroy a bitmap while it (or a sub-bitmap) is the target bitmap of any thread. See also: al_create_bitmap al_get_new_bitmap_flags int al_get_new_bitmap_flags(void) Returns the flags used for newly created bitmaps. See also: al_set_new_bitmap_flags al_get_new_bitmap_format int al_get_new_bitmap_format(void) Returns the format used for newly created bitmaps. See also: ALLEGRO_PIXEL_FORMAT, al_set_new_bitmap_format al_set_new_bitmap_flags void al_set_new_bitmap_flags(int flags) Sets the flags to use for newly created bitmaps. Valid flags are: - ALLEGRO_MEMORY_BITMAP Create a bitmap residing in system memory. Operations on, and with, memory bitmaps will not be hardware accelerated. However, direct pixel access can be relatively quick compared to video bitmaps, which depend on the display driver in use. Note: Allegro's software rendering routines are currently very unoptimised. - ALLEGRO_VIDEO_BITMAP Creates a bitmap that resides in the video card memory. These types of bitmaps receive the greatest benefit from hardware acceleration. Note: Creating a video bitmap will fail if there is no current display or the current display driver cannot create the bitmap. The latter will happen if for example the format or dimensions are not supported. Note: Bitmaps created with this flag will be converted to memory bitmaps when the last display is destroyed. In most cases it is therefore easier to use the ALLEGRO_CONVERT_BITMAP flag instead. - ALLEGRO_CONVERT_BITMAP This is the default. It will try to create a video bitmap and if that fails create a memory bitmap. Bitmaps created with this flag when there is no active display will be converted to video bitmaps next time a display is created. They also will remain video bitmaps if the last display is destroyed and then another is created again. Since 5.1.0. Note: You can combine this flag with ALLEGRO_MEMORY_BITMAP or ALLEGRO_VIDEO_BITMAP to force the initial type (and fail in the latter case if no video bitmap can be created) - but usually neither of those combinations is very useful. You can use the display option ALLEGRO_AUTO_CONVERT_BITMAPS to control which displays will try to auto-convert bitmaps. - ALLEGRO_FORCE_LOCKING Does nothing since 5.1.8. Kept for backwards compatibility only. - ALLEGRO_NO_PRESERVE_TEXTURE Normally, every effort is taken to preserve the contents of bitmaps, since some platforms may forget them. This can take extra processing time. If you know it doesn't matter if a bitmap keeps its pixel data, for example when it's a temporary buffer, use this flag to tell Allegro not to attempt to preserve its contents. - ALLEGRO_ALPHA_TEST This is a driver hint only. It tells the graphics driver to do alpha testing instead of alpha blending on bitmaps created with this flag. Alpha testing is usually faster and preferred if your bitmaps have only one level of alpha (0). This flag is currently not widely implemented (i.e., only for memory bitmaps). - ALLEGRO_MIN_LINEAR When drawing a scaled down version of the bitmap, use linear filtering. This usually looks better. You can also combine it with the MIPMAP flag for even better quality. - ALLEGRO_MAG_LINEAR When drawing a magnified version of a bitmap, use linear filtering. This will cause the picture to get blurry instead of creating a big rectangle for each pixel. It depends on how you want things to look like whether you want to use this or not. - ALLEGRO_MIPMAP This can only be used for bitmaps whose width and height is a power of two. In that case, it will generate mipmaps and use them when drawing scaled down versions. For example if the bitmap is 64x64, then extra bitmaps of sizes 32x32, 16x16, 8x8, 4x4, 2x2 and 1x1 will be created always containing a scaled down version of the original. See also: al_get_new_bitmap_flags, al_get_bitmap_flags al_add_new_bitmap_flag void al_add_new_bitmap_flag(int flag) A convenience function which does the same as al_set_new_bitmap_flags(al_get_new_bitmap_flags() | flag); See also: al_set_new_bitmap_flags, al_get_new_bitmap_flags, al_get_bitmap_flags al_set_new_bitmap_format void al_set_new_bitmap_format(int format) Sets the pixel format (ALLEGRO_PIXEL_FORMAT) for newly created bitmaps. The default format is 0 and means the display driver will choose the best format. See also: ALLEGRO_PIXEL_FORMAT, al_get_new_bitmap_format, al_get_bitmap_format Bitmap properties al_get_bitmap_flags int al_get_bitmap_flags(ALLEGRO_BITMAP *bitmap) Return the flags used to create the bitmap. See also: al_set_new_bitmap_flags al_get_bitmap_format int al_get_bitmap_format(ALLEGRO_BITMAP *bitmap) Returns the pixel format of a bitmap. See also: ALLEGRO_PIXEL_FORMAT, al_set_new_bitmap_flags al_get_bitmap_height int al_get_bitmap_height(ALLEGRO_BITMAP *bitmap) Returns the height of a bitmap in pixels. al_get_bitmap_width int al_get_bitmap_width(ALLEGRO_BITMAP *bitmap) Returns the width of a bitmap in pixels. al_get_pixel ALLEG, al_lock_bitmap al_is_bitmap_locked bool al_is_bitmap_locked(ALLEGRO_BITMAP *bitmap) Returns whether or not a bitmap is already locked. See also: al_lock_bitmap, al_lock_bitmap_region, al_unlock_bitmap al_is_compatible_bitmap bool al_is_compatible_bitmap(ALLEGRO_BITMAP *bitmap) D3D and OpenGL allow sharing a texture in a way so it can be used for multiple windows. Each ALLEGRO_BITMAP created with al_create_bitmap. al_is_sub_bitmap bool al_is_sub_bitmap(ALLEGRO_BITMAP *bitmap) Returns true if the specified bitmap is a sub-bitmap, false otherwise. See also: al_create_sub_bitmap, al_get_parent_bitmap al_get_parent_bitmap ALLEGRO_BITMAP *al_get_parent_bitmap(ALLEGRO_BITMAP *bitmap) Returns the bitmap this bitmap is a sub-bitmap of. Returns NULL if this bitmap is not a sub-bitmap. This function always returns the real bitmap, and never a sub-bitmap. This might NOT match what was passed to al_create_sub_bitmap. Consider this code, for instance: ALLEGRO_BITMAP* a = al_create_bitmap(512, 512); ALLEGRO_BITMAP* b = al_create_sub_bitmap(a, 128, 128, 256, 256); ALLEGRO_BITMAP* c = al_create_sub_bitmap(b, 64, 64, 128, 128); ASSERT(al_get_parent_bitmap(b) == a && al_get_parent_bitmap(c) == a); The assertion will pass because only a is a real bitmap, and both b and c are its sub-bitmaps. Since: 5.0.6, 5.1.2 See also: al_create_sub_bitmap, al_is_sub_bitmap al_get_bitmap_x int al_get_bitmap_x(ALLEGRO_BITMAP *bitmap) For a sub-bitmap, return it's x position within the parent. See also: al_create_sub_bitmap, al_get_parent_bitmap, al_get_bitmap_y Since: 5.1.12 al_get_bitmap_y int al_get_bitmap_y(ALLEGRO_BITMAP *bitmap) For a sub-bitmap, return it's y position within the parent. See also: al_create_sub_bitmap, al_get_parent_bitmap, al_get_bitmap_x Since: 5.1.12 al_reparent_bitmap void al_reparent_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_BITMAP *parent, int x, int y, int w, int h) For a sub-bitmap, changes the parent, position and size. This is the same as destroying the bitmap and re-creating it with al_create_sub_bitmap - except the bitmap pointer stays the same. This has many uses, for example an animation player could return a single bitmap which can just be re-parented to different animation frames without having to re-draw the contents. Or a sprite atlas could re-arrange its sprites without having to invalidate all existing bitmaps. See also: al_create_sub_bitmap, al_get_parent_bitmap Since: 5.1.12 Drawing operations All drawing operations draw to the current "target bitmap" of the current thread. Initially, the target bitmap will be the backbuffer of the last display created in a thread. al_clear_to_color void al_clear_to_color(ALLEGRO_COLOR color) Clear the complete target bitmap, but confined by the clipping rectangle. See also: ALLEGRO_COLOR, al_set_clipping_rectangle, al_clear_depth_buffer al_clear_depth_buffer void al_clear_depth_buffer(float z) Clear the depth buffer (confined by the clipping rectangle) to the given value. A depth buffer is only available if it was requested with al_set_new_display_option and the requirement could be met by the al_create_display call creating the current display. Operations involving the depth buffer are also affected by al_set_render_state. For example, if ALLEGRO_DEPTH_FUNCTION is set to ALLEGRO_RENDER_LESS then depth buffer value of 1 represents infinite distance, and thus is a good value to use when clearing the depth buffer. Since: 5.1.2 See also: al_clear_to_color, al_set_clipping_rectangle, al_set_render_state, al_set_new_display_option al_draw_bitmap void al_draw_tinted_bitmap void(0.5, 0.5, 0.5, 0.5), x, y, 0); The above will draw the bitmap 50% transparently (r/g/b values need to be pre-multiplied with the alpha component with the default blend mode). al_draw_tinted_bitmap(bitmap, al_map_rgba_f(1, 0, 0, 1), x, y, 0); The above will only draw the red component of the bitmap. See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_bitmap al_draw_bitmap_region void al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_bitmap, al_draw_scaled_bitmap, al_draw_rotated_bitmap, al_draw_scaled_rotated_bitmap al_draw_tinted_bitmap_region void al_draw_tinted_bitmap_region(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, int flags) Like al_draw_bitmap_region but multiplies all colors in the bitmap with the given color. See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_tinted_bitmap al_draw_pixel void al_draw_pixel(float x, float y, ALLEGRO_COLOR color) Draws a single pixel at x, y. This function, unlike al_put_pixel, does blending and, unlike al_put_blended_pixel, respects the transformations (that is, the pixel's position is transformed, but its size is unaffected - it remains a pixel). This function can be slow if called often; if you need to draw a lot of pixels consider using al_draw_prim with ALLEGRO_PRIM_POINT_LIST from al_draw_rotated_bitmap void al_draw_rotated_bitmap(ALLEGRO_BITMAP *bitmap, float cx, float cy, float dx, float dy, float angle, int flags) for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_bitmap, al_draw_bitmap_region, al_draw_scaled_bitmap, al_draw_scaled_rotated_bitmap al_draw_tinted_rotated_bitmap void al_draw_tinted_rotated_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float angle, int flags) Like al_draw_rotated_bitmap but multiplies all colors in the bitmap with the given color. See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_tinted_bitmap al_draw_scaled_rotated_bitmap void al_draw_scaled_rotated_bitmap(ALLEGRO_BITMAP *bitmap, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) Like al_draw_rotated_bitmap, but can also scale the bitmap. The point at cx/cy in the bitmap will be drawn at dx/dy and the bitmap is rotated and scaled around this point. - cx - center x - cy - center y - dx - destination x - dy - destination y - xscale - how much to scale on the x-axis (e.g. 2 for twice the size) - yscale - how much to scale on the y-axis - angle - angle by which to rotate (radians) - flags - same as for al_draw_bitmap See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_bitmap, al_draw_bitmap_region, al_draw_scaled_bitmap, al_draw_rotated_bitmap al_draw_tinted_scaled_rotated_bitmap void al_draw_tinted_scaled_rotated_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) Like al_draw_scaled_rotated_bitmap but multiplies all colors in the bitmap with the given color. See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_tinted_bitmap al_draw_tinted_scaled_rotated_bitmap_region void al_draw_tinted_scaled_rotated_bitmap_region(ALLEGRO_BITMAP *bitmap, float sx, float sy, float sw, float sh, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) Like al_draw_tinted_scaled_rotated_bitmap but you specify an area within the bitmap to be drawn. You can get the same effect with a sub bitmap: al_draw_tinted_scaled_rotated_bitmap(bitmap, sx, sy, sw, sh, tint, cx, cy, dx, dy, xscale, yscale, angle, flags); /* This draws the same: */ sub_bitmap = al_create_sub_bitmap(bitmap, sx, sy, sw, sh); al_draw_tinted_scaled_rotated_bitmap(sub_bitmap, tint, cx, cy, dx, dy, xscale, yscale, angle, flags); See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. Since: 5.0.6, 5.1.0 See also: al_draw_tinted_bitmap al_draw_scaled_bitmap void al_draw_scaled_bitmap(ALLEGRO_BITMAP *bitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags) Draws a scaled version of the given bitmap to the target bitmap. - sx - source x - sy - source y - sw - source width - sh - source height - dx - destination x - dy - destination y - dw - destination width - dh - destination height - flags - same as for al_draw_bitmap See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_bitmap, al_draw_bitmap_region, al_draw_rotated_bitmap, al_draw_scaled_rotated_bitmap, al_draw_tinted_scaled_bitmap void al_draw_tinted_scaled_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags) Like al_draw_scaled_bitmap but multiplies all colors in the bitmap with the given color. See al_draw_bitmap for a note on restrictions on which bitmaps can be drawn where. See also: al_draw_tinted_bitmap al_get_target_bitmap ALLEGRO_BITMAP *al_get_target_bitmap(void) Return the target bitmap of the calling thread. See also: al_set_target_bitmap al_put_pixel void al_put_pixel(int x, int y, ALLEGRO_COLOR color) Draw a single pixel on the target bitmap. This operation is slow on non-memory bitmaps. Consider locking the bitmap if you are going to use this function multiple times on the same bitmap. This function is not affected by the transformations or the color blenders. See also: ALLEGRO_COLOR, al_get_pixel, al_put_blended_pixel, al_lock_bitmap al_put_blended_pixel void al_put_blended_pixel(int x, int y, ALLEGRO_COLOR color) Like al_put_pixel, but the pixel color is blended using the current blenders before being drawn. See also: ALLEGRO_COLOR, al_put_pixel al_set_target_bitmap void al_set_target_bitmap(ALLEGRO_BITMAP *bitmap) This function selects the bitmap to which all subsequent drawing operations in the calling thread will draw to. To return to drawing to a display, set the backbuffer of the display as the target bitmap, using al_get_backbuffer. As a convenience, you may also use al_set_target_backbuffer. al_set_target_backbuffer void al_set_target_backbuffer(ALLEGRO_DISPLAY *display) Same as al_set_target_bitmap(al_get_backbuffer(display)); See also: al_set_target_bitmap, al_get_backbuffer al_get_current_display ALLEGRO_DISPLAY *al_get_current_display(void) Return the display that is "current" for the calling thread, or NULL if there is none. See also: al_set_target_bitmap Blending modes al_get_blender void al_get_blender(int *op, int *src, int *dst) Returns the active blender for the current thread. You can pass NULL for values you are not interested in. See also: al_set_blender, al_get_separate_blender al_get_separate_blender void al_get_separate_blender(int *op, int *src, int *dst, int *alpha_op, int *alpha_src, int *alpha_dst) Returns the active blender for the current thread. You can pass NULL for values you are not interested in. See also: al_set_separate_blender, al_get_blender al_get_blend_color ALLEGRO_COLOR al_get_blend_color(void) Returns the color currently used for constant color blending (white by default). See also: al_set_blend_color, al_set_blender Since: 5.1.12 al_set_blender void al_set_blender(int op, int src, int dst) Sets the function to use for blending for the current thread. Blending means, the source and destination colors are combined in drawing operations. Assume the source color (e.g. color of a rectangle to draw, or pixel of a bitmap to draw) is given as its red/green/blue/alpha components (if the bitmap has no alpha it always is assumed to be fully opaque, so 255 for 8-bit or 1.0 for floating point): s = s.r, s.g, s.b, s.a. And this color is drawn to a destination, which already has a color: d = d.r, d.g, d.b, d.a. The conceptional formula used by Allegro to draw any pixel then depends on the op parameter: ALLEGRO_ADD r = d.r * df.r + s.r * sf.r g = d.g * df.g + s.g * sf.g b = d.b * df.b + s.b * sf.b a = d.a * df.a + s.a * sf.a ALLEGRO_DEST_MINUS_SRC r = d.r * df.r - s.r * sf.r g = d.g * df.g - s.g * sf.g b = d.b * df.b - s.b * sf.b a = d.a * df.a - s.a * sf.a ALLEGRO_SRC_MINUS_DEST r = s.r * sf.r - d.r * df.r g = s.g * sf.g - d.g * df.g b = s.b * sf.b - d.b * df.b a = s.a * sf.a - d.a * df.a Valid values for the factors sf and df passed to this function are as follows, where s is the source color, d the destination color and cc the color set with al_set_blend_color (white by default) ALLEGRO_ZERO f = 0, 0, 0, 0 ALLEGRO_ONE f = 1, 1, 1, 1 ALLEGRO_ALPHA f = s.a, s.a, s.a, s.a ALLEGRO_INVERSE_ALPHA f = 1 - s.a, 1 - s.a, 1 - s.a, 1 - s.a ALLEGRO_SRC_COLOR (since: 5.0.10, 5.1.0) f = s.r, s.g, s.b, s.a ALLEGRO_DEST_COLOR (since: 5.0.10, 5.1.8) f = d.r, d.g, d.b, d.a ALLEGRO_INVERSE_SRC_COLOR (since: 5.0.10, 5.1.0) f = 1 - s.r, 1 - s.g, 1 - s.b, 1 - s.a ALLEGRO_INVERSE_DEST_COLOR (since: 5.0.10, 5.1.8) f = 1 - d.r, 1 - d.g, 1 - d.b, 1 - d.a ALLEGRO_CONST_COLOR (since: 5.1.12, not supported on OpenGLES 1.0) f = cc.r, cc.g, cc.b, cc.a ALLEGRO_INVERSE_CONST_COLOR (since: 5.1.12, not supported on OpenGLES 1.0) f = 1 - cc.r, 1 - cc.g, 1 - cc.b, 1 - cc.a Blending examples: So for example, to restore the default of using premultiplied alpha blending, you would use: al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); As formula: r = d.r * (1 - s.a) + s.r * 1 g = d.g * (1 - s.a) + s.g * 1 b = d.b * (1 - s.a) + s.b * 1 a = d.a * (1 - s.a) + s.a * 1 If you are using non-pre-multiplied alpha, you could use al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); Additive blending would be achieved with al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ONE); Copying the source to the destination (including alpha) unmodified al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO); Multiplying source and destination components al_set_blender(ALLEGRO_ADD, ALLEGRO_DEST_COLOR, ALLEGRO_ZERO) Tinting the source (like al_draw_tinted_bitmap) al_set_blender(ALLEGRO_ADD, ALLEGRO_CONST_COLOR, ALLEGRO_ONE); al_set_blend_color(al_map_rgb(0, 96, 255)); /* nice Chrysler blue */ Averaging source and destination pixels al_set_blender(ALLEGRO_ADD, ALLEGRO_CONST_COLOR, ALLEGRO_CONST_COLOR); al_set_blend_color(al_map_rgba_f(0.5, 0.5, 0.5, 0.5)); As formula: r = d.r * 0 + s.r * d.r g = d.g * 0 + s.g * d.g b = d.b * 0 + s.b * d.b a = d.a * 0 + s.a * d.a See also: al_set_separate_blender, al_set_blend_color, al_get_blender al_set_separate_blender void al_set_separate_blender(int op, int src, int dst, int alpha_op, int alpha_src, int alpha_dst) Like al_set_blender, but allows specifying a separate blending operation for the alpha channel. This is useful if your target bitmap also has an alpha channel and the two alpha channels need to be combined in a different way than the color components. See also: al_set_blender, al_get_blender, al_get_separate_blender al_set_blend_color void al_set_blend_color(ALLEGRO_COLOR color) Sets the color to use for blending when using the ALLEGRO_CONST_COLOR or ALLEGRO_INVERSE_CONST_COLOR blend functions. See al_set_blender for more information. See also: al_set_blender, al_get_blend_color Since: 5.1.12 Clipping al_get_clipping_rectangle void al_get_clipping_rectangle(int *x, int *y, int *w, int *h) Gets the clipping rectangle of the target bitmap. See also: al_set_clipping_rectangle al_set_clipping_rectangle void al_set_clipping_rectangle(int x, int y, int width, int height) Set the region of the target bitmap or display that pixels get clipped to. The default is to clip pixels to the entire bitmap. See also: al_get_clipping_rectangle, al_reset_clipping_rectangle al_reset_clipping_rectangle void al_reset_clipping_rectangle(void) Equivalent to calling `al_set_clipping_rectangle(0, 0, w, h)' where w and h are the width and height of the target bitmap respectively. Does nothing if there is no target bitmap. See also: al_set_clipping_rectangle Since: 5.0.6, 5.1.0 Graphics utility functions al_convert_mask_to_alpha void al_convert_mask_to_alpha(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR mask_color) Convert the given mask color to an alpha channel in the bitmap. Can be used to convert older 4.2-style bitmaps with magic pink to alpha-ready bitmaps. See also: ALLEGRO_COLOR Deferred drawing al_hold_bitmap_drawing void al_hold_bitmap_drawing(bool hold) Enables or disables deferred bitmap drawing. This allows for efficient drawing of many bitmaps that share a parent bitmap, such as sub-bitmaps from a tilesheet or simply identical bitmaps. Drawing bitmaps that do not share a parent is less efficient, so it is advisable to stagger bitmap drawing calls such that the parent bitmap is the same for large number of those calls. While deferred bitmap drawing is enabled, the only functions that can be used are the bitmap drawing functions and font drawing functions. Changing the state such as the blending modes will result in undefined behaviour. One exception to this rule are the non-projection transformations. It is possible to set a new transformation while the drawing is held. No drawing is guaranteed to take place until you disable the hold. Thus, the idiom of this function's usage is to enable the deferred bitmap drawing, draw as many bitmaps as possible, taking care to stagger bitmaps that share parent bitmaps, and then disable deferred drawing. As mentioned above, this function also works with bitmap and truetype fonts, so if multiple lines of text need to be drawn, this function can speed things up. See also: al_is_bitmap_drawing_held al_is_bitmap_drawing_held bool al_is_bitmap_drawing_held(void) Returns whether the deferred bitmap drawing mode is turned on or off. See also: al_hold_bitmap_drawing Image I/O al_register_bitmap_loader bool al_register_bitmap_loader(const char *extension, ALLEGRO_BITMAP *(*loader)(const char *filename, int flags)) Register a handler for al_load_bitmap. The given function will be used to handle the loading of bitmaps files with the given extension. The extension should include the leading dot ('.') character. It will be matched case-insensitively. The loader argument may be NULL to unregister an entry. Returns true on success, false on error. Returns false if unregistering an entry that doesn't exist. See also: al_register_bitmap_saver, al_register_bitmap_loader_f al_register_bitmap_saver bool al_register_bitmap_saver(const char *extension, bool (*saver)(const char *filename, ALLEGRO_BITMAP *bmp)) Register a handler for al_save_bitmap. The given function will be used to handle the saving of bitmaps_bitmap_loader, al_register_bitmap_saver_f al_register_bitmap_loader_f bool al_register_bitmap_loader_f(const char *extension, ALLEGRO_BITMAP *(*fs_loader)(ALLEGRO_FILE *fp, int flags)) Register a handler for al_load_bitmap_f. The given function will be used to handle the loading of bitmaps files with the given extension. The extension should include the leading dot ('.') character. It will be matched case-insensitively. The fs_loader argument may be NULL to unregister an entry. Returns true on success, false on error. Returns false if unregistering an entry that doesn't exist. See also: al_register_bitmap_loader al_register_bitmap_saver_f bool al_register_bitmap_saver_f(const char *extension, bool (*fs_saver)(ALLEGRO_FILE *fp, ALLEGRO_BITMAP *bmp)) Register a handler for al_save_bitmap_f. The given function will be used to handle the saving of bitmaps files with the given extension. The extension should include the leading dot ('.') character. It will be matched case-insensitively. The saver_f argument may be NULL to unregister an entry. Returns true on success, false on error. Returns false if unregistering an entry that doesn't exist. See also: al_register_bitmap_saver al_load_bitmap ALLEGRO_BITMAP *al_load_bitmap(const char *filename) Loads an image file into a new ALLEGRO_BITMAP. The file type is determined by the extension, except if the file has no extension in which case al_identify_bitmap is used instead. Returns NULL on error. This is the same as calling al_load_bitmap_flags with a flags parameter of 0. Note: the core Allegro library does not support any image file formats by default. You must use the allegro_image addon, or register your own format handler. See also: al_load_bitmap_flags, al_load_bitmap_f, al_register_bitmap_loader, al_set_new_bitmap_format, al_set_new_bitmap_flags, al_init_image_addon al_load_bitmap_flags ALLEGRO_BITMAP *al_load_bitmap_flags(const char *filename, int flags) Loads an image file into a new ALLEGRO_BITMAP. The file type is determined by the extension, except if the file has no extension in which case al_identify_bitmap is used instead. Returns NULL on error. The flags parameter may be a combination of the following constants: - ALLEGRO_NO_PREMULTIPLIED_ALPHA By default, Allegro pre-multiplies the alpha channel of an image with the images color data when it loads it. Typically that would look something like this: r = get_float_byte(); g = get_float_byte(); b = get_float_byte(); a = get_float_byte(); r = r * a; g = g * a; b = b * a; set_image_pixel(x, y, r, g, b, a); The reason for this can be seen in the Allegro example ex_premulalpha, ie, using pre-multiplied alpha gives more accurate color results in some cases. To use alpha blending with images loaded with pre-multiplied alpha, you would use the default blending mode, which is set with al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA). The ALLEGRO_NO_PREMULTIPLIED_ALPHA flag being set will ensure that images are not loaded with alpha pre-multiplied, but are loaded with color values direct from the image. That looks like this: r = get_float_byte(); g = get_float_byte(); b = get_float_byte(); a = get_float_byte(); set_image_pixel(x, y, r, g, b, a); To draw such an image using regular alpha blending, you would use al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA) to set the correct blender. This has some caveats. First, as mentioned above, drawing such an image can result in less accurate color blending (when drawing an image with linear filtering on, the edges will be darker than they should be). Second, the behaviour is somewhat confusing, which is explained in the example below. // Load and create bitmaps with an alpha channel al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA); // Load some bitmap with alpha in it bmp = al_load_bitmap("some_alpha_bitmap.png"); // We will draw to this buffer and then draw this buffer to the screen tmp_buffer = al_create_bitmap(SCREEN_W, SCREEN_H); // Set the buffer as the target and clear it al_set_target_bitmap(tmp_buffer); al_clear_to_color(al_map_rgba_f(0, 0, 0, 1)); // Draw the bitmap to the temporary buffer al_draw_bitmap(bmp, 0, 0, 0); // Finally, draw the buffer to the screen // The output will look incorrect (may take close inspection // depending on the bitmap -- it may also be very obvious) al_set_target_bitmap(al_get_backbuffer(display)); al_draw_bitmap(tmp_buffer, 0, 0, 0); To explain further, if you have a pixel with 0.5 alpha, and you're using (ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA) for blending, the formula is: a = da * dst + sa * src Expands to: result_a = dst_a * (1-0.5) + 0.5 * 0.5 So if you draw the image to the temporary buffer, it is blended once resulting in 0.75 alpha, then drawn again to the screen, blended in the same way, resulting in a pixel has 0.1875 as an alpha value. - ALLEGRO_KEEP_INDEX Load the palette indices of 8-bit .bmp and .pcx files instead of the rgb colors. Since 5.1.0. - ALLEGRO_KEEP_BITMAP_FORMAT Force the resulting ALLEGRO_BITMAP to use the same format as the file. This is not yet honoured. Note: the core Allegro library does not support any image file formats by default. You must use the allegro_image addon, or register your own format handler. Since: 5.1.0 See also: al_load_bitmap al_load_bitmap_f ALLEGRO_BITMAP *al_load_bitmap_f(ALLEGRO_FILE *fp, const char *ident). This is the same as calling al_load_bitmap_flags_f with 0 for the flags parameter. Returns NULL on error. The file remains open afterwards. Note: the core Allegro library does not support any image file formats by default. You must use the allegro_image addon, or register your own format handler. See also: al_load_bitmap_flags_f, al_load_bitmap, al_register_bitmap_loader_f, al_init_image_addon al_load_bitmap_flags_f ALLEGRO_BITMAP *al_load_bitmap_flags_f(ALLEGRO_FILE *fp, const char *ident, int flags). The flags parameter is the same as for al_load_bitmap_flags. Returns NULL on error. The file remains open afterwards. Note: the core Allegro library does not support any image file formats by default. You must use the allegro_image addon, or register your own format handler. Since: 5.1.0 See also: al_load_bitmap_f, al_load_bitmap_flags al_save_bitmap bool al_save_bitmap_f bool al_save_bitmap_f(ALLEGRO_FILE *fp, const char *ident, ALLEGRO_BITMAP *bitmap) Saves an ALLEGRO_BITMAP to an ALLEGRO_FILE stream. The file type is determined by the passed 'ident' parameter, which is a file name extension including the leading dot. Returns true on success, false on error. The file remains open afterwards. Note: the core Allegro library does not support any image file formats by default. You must use the allegro_image addon, or register your own format handler. See also: al_save_bitmap, al_register_bitmap_saver_f, al_init_image_addon al_register_bitmap_identifier bool al_register_bitmap_identifier(const char *extension, bool (*identifier)(ALLEGRO_FILE *f)) Register an identify handler for al_identify_bitmap. The given function will be used to detect files for the given extension. It will be called with a single argument of type ALLEGRO_FILE which is a file handle opened for reading and located at the first byte of the file. The handler should try to read as few bytes as possible to safely determine if the given file contents correspond to the type with the extension and return true in that case, false otherwise. The file handle must not be closed but there is no need to reset it to the beginning. The extension should include the leading dot ('.') character. It will be matched case-insensitively. The identifier argument may be NULL to unregister an entry. Returns true on success, false on error. Returns false if unregistering an entry that doesn't exist. Since: 5.1.12 See also: al_identify_bitmap al_identify_bitmap char const *al_identify_bitmap(char const *filename) This works exactly as al_identify_bitmap_f but you specify the filename of the file for which to detect the type and not a file handle. The extension, if any, of the passed filename is not taken into account - only the file contents. Since: 5.1.12 See also: al_init_image_addon, al_identify_bitmap_f, al_register_bitmap_identifier al_identify_bitmap_f char const *al_identify_bitmap_f(ALLEGRO_FILE *fp) Tries to guess the bitmap file type of the open ALLEGRO_FILE by reading the first few bytes. By default Allegro cannot recognize any file types, but calling al_init_image_addon will add detection of (some of) the types it can read. You can also use al_register_bitmap_identifier to add identification for custom file types. Returns a pointer to a static string with a file extension for the type, including the leading dot. For example ".png" or ".jpg". Returns NULL if the bitmap type cannot be determined. Since: 5.1.12 See also: al_init_image_addon, al_identify_bitmap, al_register_bitmap_identifier Render State ALLEGRO_RENDER_STATE typedef enum ALLEGRO_RENDER_STATE { Possible render states which can be set with al_set_render_state: - ALLEGRO_ALPHA_TEST If this is set to 1, the values of ALLEGRO_ALPHA_FUNCTION and ALLEGRO_ALPHA_TEST_VALUE define a comparison function which is performed for each pixel. Only if it evaluates to true the pixel is written. Otherwise no subsequent processing (like depth test or blending) is performed. - ALLEGRO_ALPHA_FUNCTION One of ALLEGRO_RENDER_FUNCTION, only used when ALLEGRO_ALPHA_TEST is 1. - ALLEGRO_ALPHA_TEST_VALUE Only used when ALLEGRO_ALPHA_TEST is 1. - ALLEGRO_WRITE_MASK This determines how the framebuffer and depthbuffer are updated whenever a pixel is written (in case alpha and/or depth testing is enabled: after all such enabled tests succeed). Depth values are only written if ALLEGRO_DEPTH_TEST is 1, in addition to the write mask flag being set. - ALLEGRO_DEPTH_TEST If this is set to 1, compare the depth value of any newly written pixels with the depth value already in the buffer, according to ALLEGRO_DEPTH_FUNCTION. Allegro primitives with no explicit z coordinate will write a value of 0 into the depth buffer. - ALLEGRO_DEPTH_FUNCTION One of ALLEGRO_RENDER_FUNCTION, only used when ALLEGRO_DEPTH_TEST is 1. Since: 5.1.2 See also: al_set_render_state, ALLEGRO_RENDER_FUNCTION, ALLEGRO_WRITE_MASK_FLAGS ALLEGRO_RENDER_FUNCTION typedef enum ALLEGRO_RENDER_FUNCTION { Possible functions are: - ALLEGRO_RENDER_NEVER - ALLEGRO_RENDER_ALWAYS - ALLEGRO_RENDER_LESS - ALLEGRO_RENDER_EQUAL - ALLEGRO_RENDER_LESS_EQUAL - ALLEGRO_RENDER_GREATER - ALLEGRO_RENDER_NOT_EQUAL - ALLEGRO_RENDER_GREATER_EQUAL Since: 5.1.2 See also: al_set_render_state ALLEGRO_WRITE_MASK_FLAGS typedef enum ALLEGRO_WRITE_MASK_FLAGS { Each enabled bit means the corresponding value is written, a disabled bit means it is not. - ALLEGRO_MASK_RED - ALLEGRO_MASK_GREEN - ALLEGRO_MASK_BLUE - ALLEGRO_MASK_ALPHA - ALLEGRO_MASK_DEPTH - ALLEGRO_MASK_RGB - Same as RED | GREEN | BLUE. - ALLEGRO_MASK_RGBA - Same as RGB | ALPHA. Since: 5.1.2 See also: al_set_render_state al_set_render_state void al_set_render_state(ALLEGRO_RENDER_STATE state, int value) Set one of several render attributes; see ALLEGRO_RENDER_STATE for details. This function does nothing if the target bitmap is a memory bitmap. Since: 5.1.2 See also: ALLEGRO_RENDER_STATE, ALLEGRO_RENDER_FUNCTION, ALLEGRO_WRITE_MASK_FLAGS
http://liballeg.org/a5docs/5.2.0/graphics.html
CC-MAIN-2017-39
en
refinedweb
Introducing Spring Scala Last October, at SpringOne2GX, I introduced the Spring Scala project to the world. Since then, I’ve also presented this project at Devoxx. In this blog post, I would like to give further details about this project and how you can use it in your Scala projects. Why. Obviously, you can use the (Java) Spring Framework in Scala today, without Spring Scala. But doing so will be awkward in certain places. Just like any programming language, Scala has its own, different way of doing things, and using a pure Java framework like Spring in Scala will just feel “too Java-esque”. Spring Scala tries to fix this by making Spring a first-class citizen of the Scala language. Spring Scala Overview Spring Scala is a work in progress. In the rest of this post, I will focus on the features that are currently implemented. However, we expect many additional features to be added in the coming months, hopefully through feedback that you provide us. So if you have an idea for a feature that will make Spring more enjoyable to use in Scala, please let us know by filing a JIRA issue or leaving a comment. Wiring up beans in XML The easiest and preferred way to wire up a Scala Bean in a Spring XML application context is to use constructor injection. For example, imagine we have the following Scala class: class Person(val firstName: String, val lastName: String) You can wire up this class like so, using the c namespace: <bean id="person" class="Person" c: Note that, by using constructor injection in combination with a val, we also made the Person class immutable. Functional languages, such as Scala, encourage immutable data structures. As such, constructor injection is preferred when using Spring in Scala. Also note that constructor injection works out-of-the-box; you do not need the Spring Scala jar on the class path for it to work. When it comes to setter injection, things become a bit more complicated. By default, Scala classes do not follow the JavaBeans property contract (eg. String getFoo() and void setFoo(String)). Instead, Scala has its own property contract: “getters” aren’t prefixed by get, but rather use the field name as method name (eg. foo: String). Scala setters suffix the field name with _= (eg. foo_=(String): Unit). To work around this issue, you can either instruct the Scala compiler to generate JavaBeans getters and setters by using the @scala.reflect.BeanProperty annotation; or you can add Spring Scala to your class path to enable support for Scala setters. Using @BeanProperty is as simple as annotating a var with it: class Person(@BeanProperty var firstName: String, @BeanProperty var lastName: String) This will result in JavaBean-style setters being created for this class, so that you can wire it up in XML quite simply: <bean id="constructor" class="Person" p: As alternative to using this annotation, as of version 3.2, Spring supports arbitrary getters and setters using the BeanInfoFactory strategy interface. The Spring Scala project contains an implementation of this interface that supports Scala getters and setters. This implementation will automatically be detected by Spring, there is no need for additional configuration. In practical terms, this means that putting the Spring Scala jar on the class path will enable support for Scala properties, and that you can use the above XML configuration to wire up the Person class without adding @BeanProperty annotations. For more information about wiring up Scala beans in Spring XML, refer to the relevant section of the Spring Scala documentation wiki. Also take a look at the section on wiring up Scala Collections in Spring XML. Wiring up beans in Scala In addition to defining beans in XML, Spring Scala offers an alternative that uses Scala classes instead of XML files to configure your Spring beans. This approach is similar to using @Configuration in Spring Java, except that it is based on functions rather than annotations. To create a functional Spring configuration, you simply have to mix in the FunctionalConfiguration trait into your configuration class. Beans are defined by calling the bean method on the trait and passing on a function that creates the bean. Given the Person class shown above, we can wire it up in a functional configuration as follows: class PersonConfiguration extends FunctionalConfiguration { bean() { new Person("John", "Doe") } } Of course, you can also register a bean under a specific name, provide aliases, or set the scope: class PersonConfiguration extends FunctionalConfiguration { bean("john", aliases = Seq("doe"), scope = BeanDefinition.SCOPE_PROTOTYPE) { new Person("John", "Doe") } } You can then use this configuration class to create a Spring application context: object PersonConfigurationDriver extends App { val applicationContext = new FunctionalConfigApplicationContext(classOf[PersonConfiguration]) val john = applicationContext.getBean(classOf[Person]) println(john.firstName) } For more information about Functional Bean Configurations, including sections on strongly-typed bean references, how to import XML files and @Configuration classes and how to wrap bean definitions in profiles, refer to the relevant section of the Spring Scala documentation wiki. Using Spring Templates in Scala Spring’s templates are helpful utility classes that facilitate any sort of data access, or resource handling in general. Spring Scala contains wrappers that adapt the (Java) templates to be more Scala friendly. In general, these Scala template wrapper contain three improvements over the Java version when in comes to usage in the Scala language: - Use of functions instead of callback interfaces - Use of Optionwhere the Java version could return null - Use class manifests instead of class parameters With these three improvements, you can use the JmsTemplate, for example, as follows: val connectionFactory : ConnectionFactory = ... val template = new JmsTemplate(connectionFactory) template.send("queue") { session: Session => session.createTextMessage("Hello World") } template.receive("queue") match { case Some(textMessage: TextMessage) => println(textMessage.getText) case _ => println("No text message received") } In general, the Scala version of the template wrappers live in the same package as their Java counterparts, except that there is a scala package in between. So the Scala version of the JmsTemplate lives in org.springframework.scala.jms.core, for instance. As of writing this post, the following Scala-friendly templates exist: - SimpleJdbcTemplate - JmsTemplate - RestTemplate - TransactionTemplate For more information about using the Spring Templates in Scala, refer to the relevant section of the Spring Scala documentation wiki. Availability A first milestone of Spring Scala is available for download at our milestone repository,. For Maven users: <repositories> <repository> <id>milestone.repo.springsource.org</id> <name>repo.springsource.org-milestone</name> <url></url> </repository> </repositories> <dependency> <groupId>org.springframework.scala</groupId> <artifactId>spring-scala</artifactId> <version>1.0.0.M2</version> </dependency> The project itself is available at GitHub. If you would like to contribute, you can do so by filing a JIRA for a feature request, or by leaving a pul request at GitHub. Note that as of 2013-04-02, a new milestone has been published. Read the forum announcement.
http://spring.io/blog/2012/12/10/introducing-spring-scala
CC-MAIN-2017-39
en
refinedweb
Welcome to Cisco Support Community. We would love to have your feedback. For an introduction to the new site, click here. If you'd prefer to explore, try our test area to get started. And see here for current known issues. When you say the issue has "gone away", do you mean thats it gone away for all the users or just the two that moved themselves back to VLAN98. If its the two users only it would suggest that the clients are using broadcasts to find the mail servers (or a service on the servers) and since a router will not usually propogate broadcast traffic - except when you have an ip helper address to point it in the right direction - the broadcast is failing or getting through on a hit or miss basis. Try putting IP HELPER entries on to the VLAN 98 definition to point to the servers - this may not solve the problem, but will highlight if the clients are using broadcasts for something. It went away for the 2 users that were moved to VLAN98 (same VLAN as Exchange servers). But... as I mentioned earlier, there is an ip helper-address command on the core switch's Interface VLAN90 pointing all users to the DHCP server on VLAN98, which in turn provides all users with a DHCP config (IP addy, def/gtwy, WINS, DNS, etc..) providing each user's Outlook client with the ability to connect to their respective Exchange server (WINS converts Exchange server name to an IP address). So to recap, all users are able to fire up Outlook and connect to their respective mailboxes which reside on their respective Exchange server on a different VLAN. The problem is that several users are experiencing frequent delays with Outlook (typical message of requesting data from Exchange server). Moving 2 users to VLAN98 APPEARS to have stopped the symptoms... ...but what problem has this resolved? NOTE: it just so happens that the DHCP server IP identified in my IP Helper-Address command is also the old Exchange server... coincidence?? Cheers, Al Al I'm not a windows expert but when they migrated to new exchange servers at my place we had intermittent connectivity issues. The way i solved it was to load up ethereal on my laptop and then monitored the link when i was using outlook. What was happening on my PC was that even tho my mail had been migrated i still had links to the old servers as well as the new so it would intermittently time out while it tried to contact the old server. I'm not suggesting this is your problem but you could try the same thing to troubleshoot HTH Jon Yep, I hear ya Jon... I've been telling people that it must be an 'application layer' problem, but I'm just baffled on how changing VLANs could stop the symptoms... anyway, yes we will surely need to sniff this one out, thanks. Al Al If it works on the same vlan but not on a remote one sounds like a broadcast vs unicast issue going on. A sniffer would help with this. Good luck Jon Hi Can u verify weather intervaln routing is working fine.Check weather portfast is configure on u r access ports.Check speed/duplex issues.check mtu sizes. Thanks Mahmood Mahmoood, I already checked all that... everything appears to be fine. I also believe that if such items were a problem (mismatch, etc..), I'd see a lot more people having this issue... especially if inter-vlan routing wasn't working. ;-) Thanks, Al The issue is most likely a DNS/WINS/NETBIOS issue, I will explain. The M$ outlook client usually truncates whatever you type in to be just the hostname (FQDN need not apply). This means if the workstation isn't in the same DNS namespace as the email server then the workstation will not find the email server's hostname to IP address translation in its own DNS space and thus will fail. The next thing a workstation will do is attempt netbios broadcast to locate the hostname to IP address translation and if it is in the same subnet, voila it works if not it then queries WINS. Two items to do that will confirm this behavior are "ipconfig /displaydns" to check for DNS resolution and "nbtstat -c" to confirm NETBIOS/WINS name resolution. If DNS issue then fix the DNS or create and ALIAS, if NETBIOS is your only option then get a WINS server, sorry:( Yes I have done M$ work and certs in the past but its not something I am proud of. Cheers, Brian Did you upgrade to Outlook 2003 clients when you moved to the new Exchange Servers? We see this behavior with Outlook 2003 on our flat network. This doesn't exactly answer your question why moving back to vlan98 fixed the problem, but I bet if you moved more clients back to vlan98 you would start seeing the problem on that VLAN. Mike This is ironic, we just had the same problem. The difference being that we tried moving users from one VLAN to another VLAN, but neither being the VLAN that the exchange servers are in. The result was the same, the problem went away. I am curious to know if anyone has any insight into this. Hi Sir, Thanx a lot for your support. I am explaning a problem again as I am new users in cisco, CCNA certified . I have three switches two 2950 and one 3550 . 3550 is connected to 2950(1st) as a trunk port at both side and another 2950 (2nd) is also connected to 29501st as a trunk. 3550 is in vtp server domain and having 4 vlan---vlan 2 , vlan 3 , vlan 4 and vlan 5. Now I want in 2950(1st Switch) that 4 pc in vlan 2 and 4 pc in vlan 3. And in 2950(2nd Switch) 4 pc in vlan 4 and 4 pc in vlan 5 . When I did all the configuration I found ,not able to ping management IP also found problem in intervlan routing in switches. Not able to ping intervlan .What to do I am so confuse that how to do intervlan routing in switches. So please provide me solution : As please use any of the Ip address in switch as u want and please provide me the fully configuration in both cisco 3550 server and 2950 client configuration with step by step command as I am trying this last 3 days but not getting any succsess . Please do the needful . Please provide complete solution with Ip address as you want to use . step by step configuration in swtiches _______ I will wait for your kind response. Regards, coolpopsun
https://supportforums.cisco.com/t5/lan-switching-and-routing/makes-no-sense-outlook-inter-vlan-issue/td-p/665967
CC-MAIN-2017-39
en
refinedweb
Learn Ruby Metaprogramming for Great Good Ruby Metaprogramming can be a good thing. Recently, I was reviewing one of my student’s code. He had a program with many methods that printed out various messages, for example: class MyClass def calculate(a) result = a ** 2 puts "The result is #{result}" end end class MyOtherClass def some_action(a, b) puts "The first value is #{a}, the second is #{b}" end def greet puts "Welcome!" end end I suggested that he store these messages in a separate file to simplify the process working with them. Then, I remembered how I18n translations are stored in Rails and got an idea. Why don’t we create a YAML file (a so-called dictionary) with all the messages and a helper method to fetch them properly, all while supporting additional features like interpolation? This is totally possible with Ruby’s metaprogramming! That’s how the messages_dictionary gem (created mostly for studying purposes) was born – I even used it in couple of my other projects. So, in this article, we will see Ruby’s metaprogramming in action while writing this gem from scratch. Basic Gem Structure Let me quickly cover the files and folders for the gem: - Gemfile - A gemspec that contains system information. You can check out the gem’s source code on GitHub to see how they look. - The Rakefile contains instructions to boot tests written in RSpec. - .rspec contains options for RSpec. In this case, for example, I want the tests to run in a random order, the spec_helper.rb file should be required by default, and the output should be colored verbose. Of course, these options can be set when running RSpec from the terminal, as well. - .travis.yml contains configuration for the Travis CI service that automatically runs tests for each commit or pull request. This is a really great service, so give it a try if you have never seen it before. - README.md contains the gem’s documentation. - spec/ contains all the tests written in RSpec. I won’t cover tests in this article, but you may study them on your own. - lib/ contains the gem’s main code. Let’s start work in the lib directory. First of all, create a messages_dictionary.rb file and a messages_dictionary folder. messages_dictionary.rb will require all third-party gems, as well as some other files, and define our module. Sometimes configuration is also placed inside this file, but we won’t do this. lib/messages_dictionary.rb require 'yaml' require 'hashie' module MessagesDictionary end Pretty minimalistic. Note that this gem has two dependencies: YAML and Hashie. YAML will be used for parsing .yml files whereas Hashie provides a bunch of really cool extensions for the basic Array and Hash classes. Open this RubyGems page and note that Hashie is placed under the Dependencies section. This is because inside the gemspec we have the following line: spec.add_dependency 'hashie', '~> 3.4' YAML parser is a part of Ruby core, but Hashie is a custom solution, therefore we have to specify it as a dependency. Now inside the lib/messages_dictionary create a version.rb file: lib/messages_dictionary/version.rb module MessagesDictionary VERSION = 'GEM_VERSION_HERE' end It’s a common practice to define the gem’s version as a constant. Next, inside the gemspec file reference this constant: spec.version = MessagesDictionary::VERSION Also note that all the gem’s code is namespaced under the module MessagesDictionary. Namespacing is very important because otherwise, you may introduce naming collisions. Suppose someone wishes to use this gem in their own project, but there is already a VERSION constant defined somewhere (after all, this is a very common name). Placing the gem’s version outside of a module may re-write this constant and introduce bugs that are hard to detect. Therefore, think of a name for your gem and make sure that this name is not yet in use by Googling a bit, then namespace all your code under this name. Okay, so preparations are done and we can start coding! Dynamically Defining a Method First of all, let’s discuss how we want this gem to be used. Of course, before doing anything else it has to be required: require 'messages_dictionary' Next, our module has to be included: class MyClass include MessagesDictionary end Then there should be a method to tell MessagesDictionary to do its job. Let’s call this method has_messages_dictionary, inspired by Rails’ hassecurepassword: class MyClass include MessagesDictionary has_messages_dictionary end The next step for the user is to create a .yml file containing messages: hi: "Hello there!" Finally, in order to display this message, a special method has to be called: class MyClass include MessagesDictionary has_messages_dictionary def greet pretty_output(:hi) # Prints "Hello there!" in the terminal end end This is somewhat basic functionality, but we will extend it later. Create a new file called injector.rb inside the lib/messages_dictionary directory. The big question is how to equip a class with an additional method has_messages_dictionary on the fly? Luckily for us, Ruby presents a special hook method called included that runs once a module is included into a class. lib/messages_dictionary/injector.rb module MessagesDictionary def self.included(klass) end end included is a class method, so I need to prefix it with self. This method accepts an object representing the class which has included this module. Note that I intentionally called this local variable klass, because class is a reserved word in Ruby. What do we want to do next? Obviously, define a new method called has_messages_dictionary. However, we can’t use def for that – this has to be done dynamically at runtime. Also, note that the has_messages_dictionary has to be a class method, therefore we have to use the definesingletonmethod. If you wish to learn more about singleton methods, watch my screencast about them. To put it simply, class methods are singleton methods. There is a small gotcha, however. If I use define_singleton_method like this module MessagesDictionary def self.included(klass) define_singleton_method :has_messages_dictionary do |opts = {}| end end end Then this method will be defined inside the MessagesDictionary module but not inside the class! Therefore we have to use yet another method called class_exec that, as you’ve probably guessed, evaluates some code in the context of some class: lib/messages_dictionary/injector.rb module MessagesDictionary def self.included(klass) klass.class_exec do define_singleton_method :has_messages_dictionary do |opts = {}| end end end end Note that define_singleton_method has a local variable called opts set to an empty hash by default. If we did not have to define this method dynamically, the corresponding code would look more familiar: def self.has_messages_dictionary(opts = {}) end This concept of using the included hook and defining some method in the context of another class is pretty common and, for example, is used in Devise. Opening a File Next, our code should open a file with messages. Why don’t we expect this file to be named after the class name? For example, if the class if called MyClass then the file should be my_class.yml. The only thing we need to do is convert the class name from camel to snake case. Whereas Rails does have such method, Ruby does not provide it, so let’s just define a separate class for that. The code for the snake_case case method was taken from the Rails ActiveSupport module: lib/messages_dictionary/utils/snake_case.rb module MessagesDictionary class SpecialString attr_accessor :string def initialize(string) @string = string end def snake_case string.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end Of course, we might have reopened an existing String class, but a user’s application may already have such method defined and we don’t want to redefine it. Use this new helper class: injector.rb # ... define_singleton_method :has_messages_dictionary do |opts = {}| file = "#{SpecialString.new(klass.name).snake_case}.yml" end The next step is to load a file and halt the program’s execution if it was not found: injector.rb # ... define_singleton_method :has_messages_dictionary do |opts = {}| file = "#{SpecialString.new(klass.name).snake_case}.yml" begin messages = YAML.load_file(file) rescue Errno::ENOENT abort "File #{file} does not exist..." # you may raise some custom error instead end end messages will contain a hash based on the file’s contents but I’d like to offer some flexibility for the users, allowing them to access a message by either providing a symbol or a string as the key. This is called indifferent access and Hashie does support it. In order to add this feature, define a special class called Dict and add the proper modules there: lib/messages_dictionary/utils/dict.rb module MessagesDictionary class Dict < Hash include Hashie::Extensions::MergeInitializer include Hashie::Extensions::IndifferentAccess end end Now tweak the main file a bit: injector.rb # ... messages = Dict.new(YAML.load_file(file)) # ... The last step in this section is storing these messages somewhere. Let’s use a class constant for that. Here is the resulting code: injector.rb module MessagesDictionary def self.included(klass) klass.class_exec do define_singleton_method :has_messages_dictionary do |opts = {}| file = "#{SpecialString.new(klass.name).snake_case}.yml" begin messages = Dict.new(YAML.load_file(file)) rescue Errno::ENOENT abort "File #{file} does not exist..." end klass.const_set(:DICTIONARY_CONF, {msgs: messages}) end end end end const_set dynamically creates a constant named DICTIONARY_CONF for the class. This constant contains a hash with our messages. Later we will store additional options in this constant. Support for Options Our script is starting to gain some shape, but it is way too rigid. Here are some obvious enhancements that need to be introduced: - It should be possible to provide a custom messages file - Currently, the messages file has to placed into the same directory as the script, which it is not very convenient. Therefore, it should be possible to define a custom path to the file. - In some cases, it might be more convenient to pass a hash with messages directly to the script instead of creating a file. - It should be possible to store nested messages, just like in Rails’ locale files. - By default all messages will be printed out into STDOUTusing the putsmethod, but users may want to change that. Some of these features might seem complex but, in reality, they are somewhat simple to implement. Let’s start with the custom path and file names. Providing a Custom Path We are going to instruct users to provide the :dir and :file options if they want to redefine the default path name. Here is the new version of the script: injector.rb # ... define_singleton_method :has_messages_dictionary do |opts = {}| file = "#{SpecialString.new(klass.name).snake_case}.yml" begin file = opts[:file] || "#{SpecialString.new(klass.name).snake_case}.yml" file = File.expand_path(file, opts[:dir]) if opts[:dir] rescue Errno::ENOENT abort "File #{file} does not exist..." end klass.const_set(:DICTIONARY_CONF, {msgs: messages}) end Basically we’ve changed only two lines of code. We either fetch user-provided file name or generate it based on the class name, then use the expand_path method if they supply a directory. Now the user can provide options like this: has_messages_dictionary file: 'test.yml', dir: 'my_dir/nested_dir' Passing a Hash of Messages This is a simple feature to implement. Just provide support for the messages option: injector.rb # ... define_singleton_method :has_messages_dictionary do |opts = {}| if opts[:messages] messages = Dict.new(opts[:messages]) else file = opts[:file] || "#{SpecialString.new(klass.name).snake_case}.yml" file = File.expand_path(file, opts[:dir]) if opts[:dir] begin # ... end end end Now messages can be provided in the form of a hash: has_messages_dictionary messages: {hi: 'hello!'} Support Nesting and Displaying the Messages This feature is a bit trickier, but totally feasible with the help of Hashie’s deep_fetch method. It takes one or more arguments representing the hash’s keys (or array’s indexes) and does its best to find the corresponding value. For example, if we have this hash: user = { name: { first: 'Bob', last: 'Smith' } } You can say: user.deep_fetch :name, :first to fetch “Bob”. This method also accepts a block that will be run when the requested value cannot be found: user.deep_fetch(:name, :middle) { |key| 'default' } Before employing this method, however, we need to extend our object with new functionality: injector.rb # ... klass.const_set(:DICTIONARY_CONF, {msgs: messages.extend(Hashie::Extensions::DeepFetch)}) # ... Let’s decide how the users should provide a path to the nested value. Why don’t we use Rails’ I18n approach where keys are delimited with .: pretty_output('some_key.nested_key') It’s high time to add the actual pretty_output method: injector.rb # ... define_method :pretty_output do |key| msg = klass::DICTIONARY_CONF[:msgs].deep_fetch(*key.to_s.split('.')) do raise KeyError, "#{key} cannot be found in the provided file..." end end Take the key and split it by . resulting in an array. The array’s elements should then be converted to the method’s arguments, which is why we prefix this command with *. Next, fetch the requested value or raise an error if nothing was found. Outputting the Message Lastly we’ll display the message while allowing the redefinition of the output location and the method to be used. Let’s call these two new options output (default is STDOUT) and method (default is :puts): injector.rb # ... klass.const_set(:DICTIONARY_CONF, {msgs: messages.extend(Hashie::Extensions::DeepFetch), output: opts[:output] || STDOUT, method: opts[:method] || :puts}) # ... Next just user these options. As long as we are calling a method dynamically, without knowing its name, use send: injector.rb # ... define_method :pretty_output do |key| msg = klass::DICTIONARY_CONF[:msgs].deep_fetch(*key.to_s.split('.')) do raise KeyError, "#{key} cannot be found in the provided file..." end klass::DICTIONARY_CONF[:output].send(klass::DICTIONARY_CONF[:method].to_sym, msg) end The gem is nearly finished, there are just a few more items. Interpolation Interpolating values into a string is a very common practice, so, of course, our program should support it. We only need to pick some special symbols to mark an interpolation placeholder. I’ll go for Handlebars-style {{ and }} but of course you may choose anything else: show_result: "The result is {{result}}. Another value is {{value}}" The values will then be passed as a hash: pretty_output(:show_result, result: 2, value: 50) This means that the pretty_output method should accept one more argument: injector.rb # ... define_method :pretty_output do |key, values = {}| end In order to replace a placeholder with an actual value we will stick with the gsub!: injector.rb # ... define_method :pretty_output do |key, values = {}| msg = klass::DICTIONARY_CONF[:msgs].deep_fetch(*key.to_s.split('.')) do raise KeyError, "#{key} cannot be found in the provided file..." end values.each do |k, v| msg.gsub!(Regexp.new('\{\{' + k.to_s + '\}\}'), v.to_s) end klass::DICTIONARY_CONF[:output].send(klass::DICTIONARY_CONF[:method].to_sym, msg) end Custom Transformations and Finalizing the Gem The last feature to implement is the ability to provide custom transformations for the messages. By that, I mean user-defined operations that should be applied to the fetched string. For example, sometimes you might want to just fetch the string without displaying it anywhere. Other times you may wish to capitalize it or strip out some symbols, etc. Therefore I would like our pretty_output method to accept an optional block with some custom code: injector.rb # ... define_method :pretty_output do |key, values = {}, &block| end Simply run the code if the block is provided, otherwise, perform the default operation: injector.rb # ... define_method :pretty_output do |key, values = {}, &block| # ... block ? block.call(msg) : klass::DICTIONARY_CONF[:output].send(klass::DICTIONARY_CONF[:method].to_sym, msg) end By removing the & symbol from the block’s name we turn it into a procedure. Next, simply use the call method to run this procedure and pass our message to it. The transformations can now be provided like this: pretty_output(:welcome) do |msg| msg.upcase! msg # => Returns "WELCOME", does not print anything end Sometimes it might be better to provide transformation logic for the whole class, instead of passing a block individually: injector.rb # ... define_singleton_method :has_messages_dictionary do |opts = {}| # ... klass.const_set(:DICTIONARY_CONF, {msgs: messages.extend(Hashie::Extensions::DeepFetch), output: opts[:output] || STDOUT, method: opts[:method] || :puts, transform: opts[:transform]}) end define_method :pretty_output do |key, values = {}, &block| # ... transform = klass::DICTIONARY_CONF[:transform] || block transform ? transform.call(msg) : klass::DICTIONARY_CONF[:output].send(klass::DICTIONARY_CONF[:method].to_sym, msg) end You may say block || klass::DICTIONARY_CONF[:transform] instead to make the block passed for an individual method more prioritized. We are done with the gem’s features, so let’s finalize it now. pretty_output is an instance method, but we probably don’t want it to be called from outside of the class. Therefore, let’s make it private: injector.rb # ... define_method :pretty_output do |key, values = {}, &block| # ... end private :pretty_output The name pretty_output is nice, but a bit too long, so let’s provide an alias for it: injector.rb # ... private :pretty_output alias_method :pou, :pretty_output Now displaying a message is as simple as saying pou(:welcome) The very last step is to require all the files in the proper order: lib/messages_dictionary.rb require 'yaml' require 'hashie' require_relative 'messages_dictionary/utils/snake_case' require_relative 'messages_dictionary/utils/dict' require_relative 'messages_dictionary/injector' module MessagesDictionary end Conclusion In this article we’ve seen how Ruby’s metaprogramming can be used in the real world and wrote a MessagesDictionary gem that allows us to easily fetch and work with strings. Hopefully, you now feel a bit more confident about using methods like included, define_singleton_method, send, as well as working with blocks. The final result is available on GitHub along with thorough documentation. You can also find RSpec tests there. Feel free to suggest your own enhancement for this gem, after all, it was created for studying purposes. As always, I thank you for staying with me and see you soon!
https://www.sitepoint.com/learn-ruby-metaprogramming-for-great-good/
CC-MAIN-2017-39
en
refinedweb
I got the first part correct but how do I put the get height into the second part? Like would I just repeat everything the base did.. like "private double height" " public void setHeight " etc... The design is this: RightTriangle variables: base, height methods: setBase - changes the base setHeight - changes the height getBase - returns the base getHeight - returns the height area - returns the rea of the triangle(1/2bh) The output is suppose to be: The base of the right triangle is 4.0 the height of the right triangle is 5.0 The area of the right triable is 10.0 My code so far is: public class RightTriangle { public static void main(String[] args) { Triangle shape = new Triangle(); shape.setBase(4.0); shape.setHeight(5.0); System.out.println("The base of the right triangle is " + shape.getBase()); System.out.println("The height of the right triangle is " + shape.getHeight()); System.out.println("The area of the right triangle is " + shape.area()); } } The class code is: public class Triangle { private double base; public Triangle() { base = 1; } public void setBase(double newBase) { base = newBase; } public double area() { double triangleArea; triangleArea = 1/2 * base * height; return(triangleArea); } public double getBase() { return(base); } }
https://www.daniweb.com/programming/software-development/threads/228438/how-to-add-the-setheight-method
CC-MAIN-2018-43
en
refinedweb
Purpose parser*.bas: Parsing/compilation functions: lexer tokens -> AST nodes. symb*.bas: Symbol tables and lookup, namespace/scope handling. rtl*.bas: Helpers to build AST calls to rtlib/gfxlib functions. The structure of the parser has a very close relation to the FreeBASIC grammar. Basically there is a parsing function for every element of the grammar. The parser retrieves tokens from the lexer and validates the input source code. Most error messages (besides command line and file access errors) come from here. Additionally the parser functions build up the corresponding AST. This is the heart of the compilation process. Many of the parser's (or rather compiler's) functions (prefixed with a 'c') parse and skip the grammar element they represent, or show an error if they don't find it. The parser is fairly recursive, mostly because of the expression parser and the #include parsing. From parsing to emitting When parsing code a corresponding AST is built up to represent the program. The AST is used to represent executable code, but also to hold temporary expressions, for example the values of constants or the initializers found while parsing type or procedure declarations. The AST does not contain nodes for code flow constructs like IF, DO/LOOP, GOTO, RETURN, EXIT DO, etc., but it contains labels and branches. Likewise, several operations (like IIF(), ANDALSO, ORELSE, field dereference, member access) are replaced by the corresponding set of lower-level operations in the AST. After parsing a function, the AST for this function is optimized, and then emitted recursively via astLoad*() calls on each node, from the top down. Note that each AST node has its own implementation of astLoad(). After parsing a function, the AST for this function is optimized, and then emitted recursively via astLoad*() calls on each node, from the top down. Note that each AST node has its own implementation of astLoad(). Back to FreeBASIC Developer Information Back to Table of Contents
https://www.freebasic.net/wiki/wikka.php?wakka=DevFbcParser
CC-MAIN-2018-43
en
refinedweb
Session Invalidation in JBoss Portal Portal vs Portlet Session - Invalidating the portal session will not invalidate the different portlet sessions. The main reason is that those are two different sessions. However we do know that it may be a potential security issue and we have a mechanism in place that on sign out will trigger the invalidation of all the portlet sessions that the user has used during its session. Alternatively you could invalidate that specific portlet session. You need tomake a request dispatch to the target war file containing your portlet and invalidate the session in a special servlet, pretty much like : in the code located in the portal (your servlet filter) : RequestDispatcher rd = servletContext.getContext("/myapp").getRequestDispatcher("MyServlet"); rd.include(req, resp); where myapp is the context name of the web application containing the special servlet. (Please beware the value "/myapp" could be "myapp" without the "/" in front of it. I am not very sure of it) then you need a servlet which will only do : service(Req, Resp) { req.getSession().invalidate(); } and declare it as MyServlet in your web.xml Signout Command - In JBoss Portal 2.6 you can use the SignOut command to invalidate the Session (which is the default behavior when you click on the LogOut link)! The SignOut command essentially destroys all the sessions of the various portlet web applications visited by the user. If you write a JBoss Portlet, you can call the signOut() method on a actionResponse object to call the SignOut Command. myLogout(JBossActionRequest req, JBossActionResponse resp) { resp.signOut(); } Portal Environment Session Diagnosis - Most often we run into a point where our session data is not getting invalidated. In those cases, please use the following guidelines to check what is happening behind our backs! You are dealing with at least 3 different sessions when you are using JBoss Portal with JBossAS: your webapp session the portal's webapp session the portlet's webapp session To check if the sessions are invalidated add a SessionListener in the 3 webapps. Write a class like the following: import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MySessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { System.out.println("Portal [CHANGEME FOR OTHER WEBAPPS] Session created"); } public void sessionDestroyed(HttpSessionEvent se) { System.out.println("Portal [CHANGEME FOR OTHER WEBAPPS] Session destroyed"); } } put it in WEB-INF/classes and add in the web.xml: <listener> <listener-class>MySessionListener</listener-class> </listener> Do it for all the 3 webapps. It will help you diagnose the problem!
https://developer.jboss.org/wiki/SessionInvalidate
CC-MAIN-2018-43
en
refinedweb
How to deploy models from Azure Machine Learning service to Azure Kubernetes Service For high-scale production scenarios, you can deploy your model to the Azure Kubernetes Service (AKS). Azure Machine Learning can use an existing AKS cluster or a new cluster created during deployment. The model is deployed to ASK as a web service. Deploying to AKS provides auto-scaling, logging, model data collection, and fast response times for your web service. Prerequisites An Azure subscription. If you don't have one, create a free account before you begin. An Azure Machine Learning service workspace, a local directory containing your scripts, and the Azure Machine Learning SDK for Python installed. Learn how to get these prerequisites using the How to configure a development environment document. A trained machine learning model. If you don't have one, see the train image classification model tutorial. Initialize the workspace To initialize the workspace, load the config.json file that contains your workspace information. from azureml.coreazureml import Workspace # Load existing workspace from the config file info. ws = Workspace.from_config() Register the model To register an existing model, specify the model path, description, and tags. from azureml.core.model import Model model = Model.register(model_path = "model.pkl", # this points to a local file model_name = "best_model", # this is the name the model is registered as tags = {"data": "diabetes", "type": "regression"}, description = "Ridge regression model to predict diabetes", workspace = ws) Create a Docker image Azure Kubernetes Service uses Docker images. To create the image, use the following steps: To configure the image, you must create a scoring script and environment file. For an example of creating the script and environment file, see the following sections of the image classification example: The following example uses these files to configure the image: from azureml.core.image import ContainerImage # Image configuration image_config = ContainerImage.image_configuration(execution_script = "score.py", runtime = "python", conda_file = "myenv.yml", description = "Image with ridge regression model", tags = {"data": "diabetes", "type": "regression"} ) To create the image, use the model and image configuration. This operation may take around 5 minutes to complete: image = ContainerImage.create(name = "myimage1", # this is the model object models = [model], image_config = image_config, workspace = ws) # Wait for the create process to complete image.wait_for_creation(show_output = True) Create the AKS Cluster The following code snippet demonstrates how to create the AKS cluster. This process takes around 20 minutes to complete:) Attach existing AKS cluster (optional) If you have existing AKS cluster in your Azure subscription, you can use it to deploy your image. The following code snippet demonstrates how to attach a cluster to your workspace. Important Only AKS version 1.11.2 is supported. # Get the resource id from -> Find your resource group -> click on the Kubernetes service -> Properties resource_id = '/subscriptions/<your subscription id>/resourcegroups/<your resource group>/providers/Microsoft.ContainerService/managedClusters/<your aks service name>' # Set to the name of the cluster cluster_name='my-existing-aks' # Attatch the cluster to your workgroup aks_target = AksCompute.attach(workspace=ws, name=cluster_name, resource_id=resource_id) # Wait for the operation to complete aks_target.wait_for_completion(True) Deploy your web service The following code snippet demonstrates how to deploy the image to the AKS cluster: from azureml.core.webservice import Webservice, AksWebservice # Set configuration and service name aks_config = AksWebservice.deploy_configuration() aks_service_name ='aks-service-1' # Deploy from image aks_service = Webservice.deploy_from_image(workspace = ws, name = aks_service_name, image = image, deployment_config = aks_config, deployment_target = aks_target) # Wait for the deployment to complete aks_service.wait_for_deployment(show_output = True) print(aks_service.state) Tip If there are errors during deployment, use aks_service.get_logs() to view the AKS service logs. The logged information may indicate the cause of the error. Test the web service Use aks_service.run() to test the web service. The following code snippet demonstrates how to pass data to the service and display the prediction: import json test_sample = json.dumps({'data': [ [1,2,3,4,5,6,7,8,9,10], [10,9,8,7,6,5,4,3,2,1] ]}) test_sample = bytes(test_sample,encoding = 'utf8') prediction = aks_service.run(input_data = test_sample) print(prediction) Cleanup To delete the service, image, and model, use the following code snippet: aks_service.delete() image.delete() model.delete()
https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-to-aks?WT.mc_id=Revolutions-blog-davidsmi
CC-MAIN-2018-43
en
refinedweb
Q&A with Bryan Cantrill: Running Containers on Bare Metal with Triton - | - - - - - - Read later Reading List Infrastructure" at Container Camp SF 2015, and "The Peril and Promise of Early Adoption: Arriving 10 Years Early to Containers" at the O'Reilly Software Architecture conference 2015. A frequent topic of these talks is the benefit of running containers on bare metal, the advantages of which may be obvious (i.e. removing any performance overhead of running within a virtual machine), but there are several outstanding security issues. InfoQ asked Cantrill about his thought on these issues, and also recent work he has been doing at Joyent. InfoQ: We understand that Joyent have been working with container technology for quite some time. Could you tell us more about this please? Cantrill: Joyent has been using containers as high-performance alternatives to hardware VMs for almost ten years. It was apparent to us early on that their operational and economic benefits far outweighed what VMs could ever provide. Uniquely, we're the only cloud that offers secure, elastic, bare metal containers. The security that makes this possible can be traced back to the Zones technology developed by Sun Microsystems and released as open source in Open Solaris. Many aspects of containers in Linux are still very new (user namespaces, for example, are not fully supported in all distros to this day), but by building on the mature foundations of Zones in Open Solaris, Joyent's SmartOS container hypervisor can offer strengthened security and enhanced resource isolation that's a decade ahead of other approaches. With Triton, we bring the maturity and security of Zones to Docker and Linux. You can easily fire up containers on Triton from the Docker client. Or, for those that want the benefits of OS virtualization without having to Dockerize their workloads, we offer certified Ubuntu, with the support of Canonical, as well as CentOS, Debian, and other container-native Linux options. InfoQ: The Joyent website states that users of your 'Triton Elastic Container Infrastructure' can expect bare metal performance at the scale of a virtual machine. What exactly does this mean - are containers actually being run on bare metal? Cantrill: Both infrastructure containers and Docker containers really do run on bare metal on Triton, offering both higher performance and better utilization of the hardware. For I/O intensive workloads the performance benefits can be dramatic. And, the combination of better performance and higher utilization reduces costs for both the customer and the provider -- an especially interesting prospect for our customers operating private clouds. Again, we can run containers on bare metal because our compute infrastructure is built on the secure foundations of Zones, which frees us from the dependency other vendors have on VMs. InfoQ: How do your offerings compare to the likes of IBM SoftLayer or Packet, both of which offer bare metal server management through an API? Cantrill: There are a number of bare metal providers that will allow you to provision a whole server, but Triton's container infrastructure offers bare metal performance with elasticity that can't be matched by those providers. From containers as small as 128 megabytes and scaling up to 64 gigabytes or even up to 224 gigabytes, you have the flexibility to use a container that offers exactly the performance and price you need. Triton also offers a rich, integrated set of infrastructure automation tools that streamline provisioning the container, including all the networking and storage, as well as imaging it with exactly the software you need. In the public cloud, this means you get bare metal performance with all the elasticity and security you expect of hardware virtual machines, and in the private cloud this means you can get newly racked compute nodes serving real workloads in as little as 60 seconds. The bottom line here is that bare metal gets you just that, bare metal. You still need to fill the gap between the metal and the application, to create a platform for running and managing containers. That is what Triton does. InfoQ: The Joyent website states the key differentiators for Triton are security, networking and introspection/debugging. Is there anything else you would like to mention? Cantrill: Simplicity. Triton delivers operational robustness in the areas of security, networking and debugging, but the real trick is that we do it in a way that makes deploying and operating a container-based architecture simple. Additionally, we are the only solution that is 100% open source and available on-premise as enterprise-supported software, and in the cloud as a service. InfoQ: How does Triton relate to (or work with) other container orchestration and scheduling platforms, such as Mesos, Kubernetes or the Docker suite of Engine/Compose/Swarm etc? Cantrill: Mesos and Kubernetes both offer great tools to help manage application lifecycle and composition, and I think Docker's suite will grow to offer similar capabilities, but they don't solve infrastructure problems. Scaling and load balancing containers or swapping new versions for old are important problems, but where do those containers run? How do you manage the underlying compute nodes? How do you deliver storage, network, and compute to those applications? We draw a clear line between the infrastructure and the application framework. Our goal is to provide the best infrastructure underneath your application orchestration tool of choice. Today we offer the best production environment for Docker containers and the Docker suite of tools, and we're working fast to do the same for Kubernetes and Mesos. InfoQ: What would you expect the typical workflow (and tooling) to be from development to production with Docker and Triton? Cantrill: One of the reasons we fell in love with Docker, along with so many other devs, is that it makes development on our laptops easy. That's why we've worked so hard to make sure deploying applications in our cloud is as easy as doing "docker run" on your laptop. Adding Docker Compose and Swarm makes this even easier. Take a look at the screencast in our blueprint for building apps based on Couchbase. The sophisticated networking and host management features of our cloud make deployments easy and scaling easier. But remember: you don't have to Dockerize an app to enjoy bare metal container performance. See our alternative example for how to deploy Couchbase in infrastructure containers as well. InfoQ: The Cloud Native Computing Foundation (CNCF), in combination with the Open Container Initiative (OCI), seems quite interesting. As a founding member of both, and one of three initial ToC members for the CNCF, what is your ambition for these organizations? Cantrill: We think that broad adoption of container-native architectures will accelerate if the key vendors and open source projects in the space can work together to articulate an opinionated reference architecture, and that the CNCF can provide a forum for creating that kind of collaboration. For example, Triton can be combined with the CNCF management software components to deliver a vendor neutral, 100% open source, 100% container-native, "complete stack" for demos, POCs, and on premise production deployments of container-native solutions. Because Triton natively supports the standard API set of the CNCF management software components, choice is preserved for users that may want to substitute a proprietary run time environment, while providing an easy on ramp to "cloud native" for the majority of the market that values, more than anything else, speed and simplicity. InfoQ: Many thanks for taking the time to answer these questions. Is there anything else you would like to add? Cantrill: To sum it all up, Triton software turns commodity hardware into "hyper-converged" infrastructure, optimized to securely run container-native architectures with bare metal speed. Triton is easy to deploy on a laptop, server, or racks of servers, and can scale to support the demands of a multi-region public cloud. Or, you can leverage Triton in the Joyent public cloud as a service. Additional information about Joyent's Triton can be found on the developer FAQ pages within the Joyent website. Rate this Article - Editor Review - Chief Editor Action
https://www.infoq.com/news/2015/08/cantrill-containers-bare-metal
CC-MAIN-2018-43
en
refinedweb
Killer 0 Posted July 28, 2007 Hi. I have 1 to 20. I need to take these numbers and rearrange them in random order. How do I do the code without getting duplicates? Meaning if 5 is selected, it should skip 5. I tried create a code to do this but somehow it just got trapped in its own loop at the last few nos. Here is my code. If anyone can do a simpler and better than mine I would appricate it. Else can someone help me untangle the loop? My Code: ============== AutoItSetOption ("TrayIconDebug", 1) $cycle_no=20 $cycle=0 $numleft=$cycle_no $file="" $ran_num=0 while $numleft<>0 $ran_num=Random(1, $cycle_no, 1)+1 do if StringInStr($file, $ran_num&"!")<>0 then msgbox(0,"ran_num",$ran_num) $ran_num=$ran_num+1 if $ran_num>20 then $ran_num=1 endif until StringInStr($file, $ran_num&"!")=0 $file=$file&$ran_num&"!"&@CR $numleft=$numleft-1 msgbox(0,$numleft,$file) WEnd Share this post Link to post Share on other sites
https://www.autoitscript.com/forum/topic/50282-need-help-in-my-coding/
CC-MAIN-2018-43
en
refinedweb
Hello, wanted to retrieve things from the data base and perform mathmatical operations on it then post it to the user, so i was told to use the bullited list and bind it to the object dataSource how to perform such thing?? ... Hello All, I would like to identifying the source & destination tables of the data flow or the transformation task. I need to create a custom component which i can put into existing packages which can do some validation. Please suggest ways i can accomplish this. thanks namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public class FlatAndHouse { public int flatID; public int HouseID; } public MainWindow() { InitializeComponent(); IList<FlatAndHouse> data = new List<FlatAndHouse>(); data.Add(new FlatAndHouse() { flatID = 1, HouseID = 2 }); data.Add(new FlatA. Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/38135-could-not-list-tables-from-db-when-creating.aspx
CC-MAIN-2017-47
en
refinedweb
Hello, This probably seems simple, well I'm sure all of mine seem simple, so here it goes. I am having trouble constructing strings. str1, str3, and str4 give pre-compile errors and show up yellow in my IDE. The pre-compile errors are commented in the code below. str2 gives a pre-compile error (commented in code below) and also a runtime error. The runtime error was: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any> at hsstringdemo.HSStringDemo.main(HSStringDemo.java:1 4) Line 14 is where the string is declared and initialized, which I think is also called the string constructor. I imported java.lang.Object and java.lang.String in hopes that something was not defined, but to no avail. I tried using the code tags this time, seems simple, but tell me how I am doing. Code java: package hsstringdemo; import java.lang.Object; import java.lang.String; public class HSStringDemo { public static void main(String[] args) { // Declare strings in various ways. String str1 = new String("Java strings are objects."); //Pre-Compile Error: String constructor invocation String str2 = new "They are constructed in various ways."; //Pre-Compile Error: <identifier> expected String str3 = new String(str1); //Pre-Compile Error: String constructor invocation String str4 = new String(str1 + str3); //Pre-Compile Error: String constructor invocation System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); } }
http://www.javaprogrammingforums.com/%20loops-control-statements/10239-constructing-strings-printingthethread.html
CC-MAIN-2017-47
en
refinedweb
A blazing fast Python URL parser Project DescriptionRelease History Download Files A blazing fast URL parser for Python How to use ? First: Install it via pip pip install bfurlparser Then, use it from bfurlparser import urlparse print urlparse('') Can I replace Python’s builtin urlparse module with bfurlparser? Probably not… but it’s really, really fast! Support Please raise an issue or send a pull request. 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/bfurlparser/
CC-MAIN-2017-47
en
refinedweb
Systems Research Group – NetOS Student Projects (2014-2015) NetOS This page collects together various Part II. Note: there are a number of stumbling blocks in Part II project selection, proposal generation and execution. Some useful guidance from a CST alumnus (and current NetOS PhD student) is here. Current project suggestions Project Title A Contact: Name Surname(with Name2 Surname2) Project description here More description here References [1] Authors here, Title here, Venue here, date here. Pre-requisites: Pre-requisities go here. Reproducing network experiments with improved fidelity Contact: Charalampos Rotsos, Dimosthenis Pediaditakis Keywords: network emulation, reproducibility, time-dilation, xen, mininet In the recent years experimental reproducibility has become an important goal for research in network systems. Efforts like Mininet[1], provide a highly flexible and performant framework to describe network experiments, using container-based OS emulation and namespaces-based network virtualisation. Mininet has created a large user community and is actively used in a series of network courses[2], providing a large library of experimental definitions which replicate the measurement apparatus for numerous network testbeds. In a similar effort, SELENA[3] provides a flexible environment for experimental reproducibility with additional focus on the repeatability of results with a higher degree of fidelity. SELENA uses Xen [4] hypervisor to support a wider spectrum of network hosts and device functionality. It also implements the technique of time-dilation [5] and it slows-down the time-progression in experimental nodes in order to achieve better fidelity for network experiments of growing size. This technique effectively increases the perceived resource availability in a unit of experimental time, from a guest OS perspective. This project aims to explore mechanisms which bridge the API abstractions of SELENA and Mininet. We are primarily interested to port the abstraction of Mininet over the SELENA experimental definition API, and thus port a large number of network experiments developed originally in Mininet. In addition, we are interested to focus on a series of experimental scenarios and perform a comparison of the degree of fidelity achieved by each system. Required skills: - good knowledge of C and Python - good understanding of common internet protocols - familiarity with Linux networking and Xen virtualisation References [1] Mininet, [2] Stanford University, CS244: Advanced Topics in Networking, [3] SELENA, [4] Xen, [5] To infinity and beyond: time warped network emulation, [6] Reproducing Network Research, More Systems Projects at the DTG Project Page Please see the DTG project suggestions page for a number of interesting systems projects.
https://www.cl.cam.ac.uk/research/srg/netos/stud-projs/studproj-14/
CC-MAIN-2017-47
en
refinedweb
One of Silverlight 4’s new feature is commanding support. Commanding and the MVVM pattern allow clean separation of XAML and C# code: an action can be associated to a control using the {Binding} markup, just as it is done with data. Silverlight 4’s buttons support commanding through the Command property. The following example shows how a ConfirmPurchaseCommand can be executed when the user clicks on the button. Note that there is no event handler for Click, no code for enabling/disabling the button, and no XAML code-behind at all: lean and mean stuff! <Button Content="{Binding Path=ConfirmPurchaseDescription}" Command="{Binding Path=ConfirmPurchase}" CommandParameter="{Binding CouponCode}"/> Commanding is supported by making certain controls automatically call members of the ICommand interface. Execute is called to invoke the action, while CanExecute is called to know wether the action is possible (for example, a button will disable itself if CanExecute returns false). But, where do I put my code ? The attached example implements two commands. 1. ConfirmOrderCommand implements ICommand directly in a class and toggles the result of CanExecute depending on the parameter (OrderId). Implementing ICommand directly should generally be avoided, but it is nevertheless a good exercise to grasp how ICommand works: public class CancelOrderCommand: ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return ((parameter as string) == "0123456789"); } public void Execute(object parameter) { /* CancelOrder(parameter..); */ } } 2. CommandImpl on the other hand, is a very simple ICommand implementation that defers ICommand’s calls to delegates (similar to Prism’s DelegateCommand or MVVM Light’s RelayCommand), to simplify the sample's code its CanExecute always returns true. Using delegates is the recommended way to go as it results in shorter, more readable code explicitely called from the view model: this.ConfirmOrderCommand = new CommandImpl<string>(ConfirmOrder); void ConfirmOrder(string orderId) { ConfirmOrder(orderId); } Silverlight 4 beta makes commands available only on controls deriving from ButtonBase, and they are executed only when buttons are clicked. The next post will demonstrate how to execute commands on any controls from any event using Blend triggers. Silverlight4Commanding.zip
https://blogs.msdn.microsoft.com/luc/2010/01/23/commanding-with-silverlight-4/
CC-MAIN-2017-47
en
refinedweb
bool repeatedSubstringPattern(string& s) { return (s+s).find(s,1) < s.size(); } Since neither string::find nor std::strstr specify complexity, the algorithm is up to whatever their implementation is. (e.g., O(N) time and space if using KMP, where N = s.size()) Why condition return (s+s).find(s,1) < s.size() is equivalent to substring repetition? Proof: Let N = s.size() and L := (s+s).find(s,1), actually we can prove that the following 2 statements are equivalent: 0 < L < N; N%L == 0and s[i] == s[i%L]is true for any iin [0, N). (which means s.substr(0,L)is the repetitive substring) Consider function char f(int i) { return s[i%N]; }, obviously it has a period N. "1 => 2": From condition 1, we have for any i in [0,N) s[i] == (s+s)[i+L] == s[(i+L)%N], which means Lis also a positive period of function f. Note that N == L*(N/L)+N%L, so we have f(i) == f(i+N) == f(i+L*(N/L)+N%L) == f(i+N%L), which means N%Lis also a period of f. Note that N%L < Lbut L := (s+s).find(s,1)is the minimum positive period of function f, so we must have N%L == 0. Note that i == L*(i/L)+i%L, so we have s[i] == f(i) == f(L*(i/L)+i%L) == f(i%L) == s[i%L], so condition 2 is obtained. "2=>1": If condition 2 holds, for any i in [0,N), note that N%L == 0, we have (s+s)[i+L] == s[(i+L)%N] == s[((i+L)%N)%L] == s[(i+L)%L] == s[i], which means (s+s).substr(L,N) == s, so condition 1 is obtained.
https://discuss.leetcode.com/topic/72712/1-line-c-solution-return-s-s-find-s-1-s-size-with-proof
CC-MAIN-2017-47
en
refinedweb
MergeSort Explanation: In each round, we divide our array into two parts and sort them. So after "int cnt = mergeSort(nums, s, mid) + mergeSort(nums, mid+1, e); ", the left part and the right part are sorted and now our only job is to count how many pairs of number (leftPart[i], rightPart[j]) satisfies leftPart[i] <= 2*rightPart[j]. For example, left: 4 6 8 right: 1 2 3 so we use two pointers to travel left and right parts. For each leftPart[i], if j<=e && nums[i]/2.0 > nums[j], we just continue to move j to the end, to increase rightPart[j], until it is valid. Like in our example, left's 4 can match 1 and 2; left's 6 can match 1, 2, 3, and left's 8 can match 1, 2, 3. So in this particular round, there are 8 pairs found, so we increases our total by 8. public class Solution { public int reversePairs(int[] nums) {); return cnt; } } Or: Because left part and right part are sorted, you can replace the Arrays.sort() part with a actual merge sort process. The previous version is easy to write, while this one is faster. public class Solution { int[] helper; public int reversePairs(int[] nums) { this.helper = new int[nums.length];); myMerge(nums, s, mid, e); return cnt; } private void myMerge(int[] nums, int s, int mid, int e){ for(int i = s; i<=e; i++) helper[i] = nums[i]; int p1 = s;//pointer for left part int p2 = mid+1;//pointer for rigth part int i = s;//pointer for sorted array while(p1<=mid || p2<=e){ if(p1>mid || (p2<=e && helper[p1] >= helper[p2])){ nums[i++] = helper[p2++]; }else{ nums[i++] = helper[p1++]; } } } } BST BST solution is no longer acceptable, because it's performance can be very bad, O(n^2) actually, for extreme cases like [1,2,3,4......49999], due to the its unbalance, but I am still providing it below just FYI. We build the Binary Search Tree from right to left, and at the same time, search the partially built tree with nums[i]/2.0. The code below should be clear enough. public class Solution { public int reversePairs(int[] nums) { Node root = null; int[] cnt = new int[1]; for(int i = nums.length-1; i>=0; i--){ search(cnt, root, nums[i]/2.0);//search and count the partially built tree root = build(nums[i], root);//add nums[i] to BST } return cnt[0]; } private void search(int[] cnt, Node node, double target){ if(node==null) return; else if(target == node.val) cnt[0] += node.less; else if(target < node.val) search(cnt, node.left, target); else{ cnt[0]+=node.less + node.same; search(cnt, node.right, target); } } private Node build(int val, Node n){ if(n==null) return new Node(val); else if(val == n.val) n.same+=1; else if(val > n.val) n.right = build(val, n.right); else{ n.less += 1; n.left = build(val, n.left); } return n; } class Node{ int val, less = 0, same = 1;//less: number of nodes that less than this node.val Node left, right; public Node(int v){ this.val = v; } } } Similar to this. But the main difference is: here, the number to add and the number to search are different (add nums[i], but search nums[i]/2.0), so not a good idea to combine build and search together. This is nice, I find the BST a clear approach. I wonder if anybody did it in python? Sadly mine was Time Limit Exceeded and I even translated your code into python below but it still gets TLE. class TreeNode: def __init__(self, val): self.val = val self.less = 0 self.same = 1 self.left = None self.right = None class Solution(object): def reversePairs(self, nums): root = None cnt = [0] for i in range(len(nums)-1, -1, -1): self.search(cnt, root, nums[i]/2.0) root = self.build(nums[i], root) return cnt[0] def search(self, cnt, node, target): if not node: return if target == node.val: cnt[0] += node.less elif target < node.val: self.search(cnt, node.left, target) else: cnt[0] += (node.less + node.same) self.search(cnt, node.right, target) def build(self, val, n): if not n: return TreeNode(val) elif val == n.val: n.same += 1 elif val > n.val: n.right = self.build(val, n.right) else: n.less += 1 n.left = self.build(val, n.left) return n Impressive!!! Your solution reminds me how much practice I still need to do.... I did count of smaller numbers after self before, but I even cannot remember it during the contest....WTF Below is my solution using merge sort. public class Solution { public int reversePairs(int[] nums) { if (nums == null || nums.length == 0) return 0; return mergeSort(nums, 0, nums.length - 1); } private int mergeSort(int[] nums, int l, int r) { if (l >= r) return 0; int mid = l + (r - l)/2; int count = mergeSort(nums, l, mid) + mergeSort(nums, mid + 1, r); int[] cache = new int[r - l + 1]; int i = l, t = l, c = 0; for (int j = mid + 1; j <= r; j++, c++) { while (i <= mid && nums[i] <= 2 * (long)nums[j]) i++; while (t <= mid && nums[t] < nums[j]) cache[c++] = nums[t++]; cache[c] = nums[j]; count += mid - i + 1; } while (t <= mid) cache[c++] = nums[t++]; System.arraycopy(cache, 0, nums, l, r - l + 1); return count; } } @yorkshire Try not to use recursive. I had the same issue when I used recursive method. So I rewrited it using while loops, which speeds up the code by x1.5, and now it finishes within time limit. class TreeNode(object): def __init__(self, val): self.val = val #the value at this node self.same = 1 #number of keys with this value self.less = 0 #number of keys in the left subtree self.left = None #left subtree (nodes with less value) self.right = None #right subtree (nodes with higher value) def search(node, val): n_temp = 0 while node != None: if node.val == val: n_temp += node.less #keys with the same value doesn't count node = None elif val > node.val: n_temp += node.less + node.same node = node.right else: node = node.left return n_temp def insert(node, val): while True: if node.val == val: node.same += 1 return elif val > node.val: if node.right == None: node.right = TreeNode(val) return else: node = node.right else: node.less += 1 if node.left == None: node.left = TreeNode(val) return else: node = node.left class Solution(object): def reversePairs(self, nums): length = len(nums) if length <= 1: return 0 n = 0 root = TreeNode(2*nums[-1]) for i in reversed(xrange(length - 1)): a = nums[i] n += search(root, a) insert(root, 2*a) return n @louis925 The python code you posted does not pass the TLE. I wrote my own code and also test directly with your posted code. Neither passed the test. Thus, the BST method should not be considered as standard solution. @tbjc The original java code from @Chidong now also gives a Time Limit Exceeded for the test case where nums = [i for i in range(5000)]. In this situation the tree is effectively linear and so O(n**2) time complexity. At least the results are standardised now so that both languages are not accepted and we have to use something like mergesort that is O(n log n). It's just a shame that Java was accepted in the contest and Python was not. @tbjc @yorkshire Thanks for notifying me this! I think they change the test cases. In the contest, the person who got second place actually only used binary sort and passed all the test cases simply because it was written in C++. I try to do the same thing in python and it got TLE. Anyway, now I will try the mergesort method next. @Chidong Hi, thanks for posting your solution. I'm just confused about one thing..maybe I'm missing something but where is the merge in your mergeSort? I see Arrays.sort()..isn't that O(nlogn) so total time complexity would be O(nlognlogn)? @jonathan82 The process is first partitioning [s, e] to [s, mid] and [mid+1, e]. Then the entire [s, e] are "merged/sorted. The merging process in merge sort is essentially a sorting process. Yes you can use Arrays.sort() to do the job, which is easier to write but take more time to run. Or you can implement this part yourself, since left and right parts are all sorted, it only it takes O(n) to finish the merge/sort job. I added that in my post. @Chidong oh, got it thx. I also thought about using a fenwick tree but couldn't seem to get it to fit this problem. Why is it Arrays.sort(nums, s, e+1); instead of Arrays.sort(nums, s, e); ? How is that +1 coming from? I tried to remove that +1 but get error. I can debug it to find out why. But how did you know it before debugging? Thank you very much! @coder2 Java Api says: "public static void sort(short[] a, int fromIndex, int toIndex) Sorts the specified range of the array into ascending order. The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive. If fromIndex == toIndex, the range to be sorted is empty. .... " My Python merge sort solution: class Solution(object): def reversePairs(self, nums): def mergeSort(s,e): if s >= e: return 0 mid = (s+e)/2 cnt,j = mergeSort(s,mid) + mergeSort(mid+1,e),mid+1 for i in xrange(s,mid+1): while j <= e and nums[i] > 2*nums[j]: j += 1 cnt += j-(mid+1) nums[s:e+1] = sorted(nums[s:e+1]) return cnt return mergeSort(0,len(nums)-1) Thanks for the explanations. Post my 239ms C++ version: class Solution { public: int reversePairs(vector<int>& nums) { return mergeSort(nums, 0, nums.size()-1); } int mergeSort(vector<int>& nums, int l, int r) { if (l >= r) return 0; int mid = l + (r - l) / 2; int res = 0; res = mergeSort(nums, l, mid) + mergeSort(nums, mid+1, r); for (int i = mid+1; i <= r; i++) { auto it = upper_bound(nums.begin()+l, nums.begin()+mid+1, nums[i] * 2L); int dis = distance(nums.begin()+l, it); if (dis > mid-l) break; res += mid-l+1 - dis; } inplace_merge(nums.begin()+l, nums.begin()+mid+1, nums.begin()+r+1); return res; } }; @Chidong Thanks for your post, I have a question: When you work on this solution, how do you know whether your sorting could introduce duplicate or miss counting, since sorting changes the position of numbers in original array? Thanks for advance. @Chidong For the MergeSort Solution, could you explain the complexity? I think it's not O(nlogn), since the recurrence seems to be T(n) = 2T(n/2) + O(n^2), instead of T(n) = 2T(n/2) + O(n). Thanks. 两种merge sort 都是O(nlgn) Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/78933/very-short-and-clear-mergesort-bst-java-solutions
CC-MAIN-2017-47
en
refinedweb
#include "ltwrappr.h" virtual L_DOUBLE LAnnotation::GetScalarY() Gets the vertical scaling factor that is applied to the annotation object. The vertical scaling factor. Typically, the scaling factors are applied to a root container so that the annotations will match the displayed image. Offset values, which are set by the LAnnotation::SetOffsetX and LAnnotation::SetOffsetY functions, are applied after the scalar properties. For more information, refer to Low-Level Coordinate System for Annotations. Required DLLs and Libraries Win32, x64. For an example, refer to LAnnotation::GetScalarX.
https://www.leadtools.com/help/leadtools/v19/main/clib/lannotation-getscalary.html
CC-MAIN-2017-47
en
refinedweb
Led Blinking using Raspberry Pi – PythonVivek Kartha Contents Led blinking is one of the beginner circuits which helps one to get acquainted with GPIO pins of Raspberry Pi. Here we use Python language to write the code for blinking Led at one second intervals. Components required - One led - 100 ohm resistor - Jumper cables Raspberry Pi GPIO Specifications - Output Voltage : 3.3V - Maximum Output Current : 16mA per pin with total current from all pins not exceeding 50mA For controlling a Led using Raspberry Pi, both python and the GPIO library is needed. Installing Python GPIO Library Note: Python and GPIO library are preinstalled if you are using Raspbian. - Make sure your Rasperry Pi is connected to the internet using either a LAN cable or a WiFi adapter. - Open the terminal by double clicking the LXTerminal icon - Type the following command to download the GPIO library as a tarball wget - Unzip the tarball tar zxvf RPi.GPIO-0.4.1a.tar.gz - Change the directory to unzipped location cd RPi.GPIO-0.4.1a - Install the GPIO library in python sudo python setup.py install Raspberry Pi GPIO Pin Out Raspberry Pi has 17 GPIO pins out of 26 pins Circuit Diagram - Connect the Led to 6 (ground) and 11 (gpio) with a 100Ω resistor in series Python Programming - Open Terminal - Launch IDLE IDE by typing sudo idle This launches IDLE with superuser privileges which is necessary execute scripts for controlling the GPIO pins - After the IDLE launches, open a new window by FILE>OPEN or Ctrl+N - Type the code below in the window import time import RPi.GPIO as GPIO ## Import GPIO library GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(11, GPIO.OUT) ## Setup GPIO Pin 11 to OUT while True: GPIO.output(11,True) ## Turn on Led time.sleep(1) ## Wait for one second GPIO.output(11,False) ## Turn off Led time.sleep(1) ## Wait for one second - Save the code by FILE>SAVE or Ctrl+S - To run your code RUN>RUN or Ctrl+F5 - The Led will start blinking now.
https://electrosome.com/led-blinking-raspberry-pi/
CC-MAIN-2017-47
en
refinedweb
Log4c stream2 appender interface. More... #include <log4c/defs.h> #include <log4c/appender.h> Go to the source code of this file. Log4c stream2 appender interface. The stream2 appender uses a file handle FILE* for logging. It can be used with stdout, stderr or a normal file. It is pretty primitive as it does not do file rotation, or have a maximum configurable file size etc. It improves on the stream appender in a few ways that make it a better starting point for new stream based appenders. It enhances the stream appender by allowing the default file pointer to be used in buffered or unbuffered mode. Also when you set the file pointer stream2 will not attempt to close it on exit which avoids it fighting with the owner of the file pointer. stream2 is configured via setter functions–the udata is not exposed directly. This means that new options (eg. configure the open mode ) could be added to stream2 while maintaining backward compatability. The appender can be used with default values, for example as follows: In this case the appender will be configured automatically with default values: "/var/logs/mymlog.log" setbuf()) in buffered mode The stream2 appender can be configured by passing it a file pointer to use. In this case you manage the file pointer yourself–open, option setting, closing. If you set the file pointer log4c will not close the file on exiting–you must do this: The default file pointer can be configured to use unbuffered mode. Buffered mode is typically 25%-50% faster than unbuffered mode but unbuffered mode is useful if your preference is for a more synchronized log file: Get the flags for this appender. Get the file pointer for this appender. Set the flags for this appender. Set the file pointer for this appender. Stream2 appender type definition. This should be used as a parameter to the log4c_appender_set_type() routine to set the type of the appender.
http://log4c.sourceforge.net/appender__type__stream2_8h.html
CC-MAIN-2017-47
en
refinedweb
Opened 7 years ago Closed 5 years ago Last modified 4 years ago #4256 closed Bugs (fixed) boost::make_shared() may issue stack overflow while constructing large objects Description By default stack size for windows executable is 1Mb. The program below fails with stack overflow exception. In debug builds the stack overflow exception issued with A_Size >= "stack size" / 3. In release builds due to optimizations, the stack overflow exception issued with A_Size >= "stack size" / 2. #include <cstddef> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> const std::size_t A_Size = 512; struct A { char buf_[A_Size * 1024]; }; int main() { boost::shared_ptr<A> pa(boost::make_shared<A>()); //boost::shared_ptr<A> pa(new A()); return 0; } Attachments (0) Change History (12) comment:1 Changed 7 years ago by comment:2 Changed 7 years ago by comment:4 Changed 6 years ago by I ran into this using 1.47 yesterday I was in debug mode VS2010. I needed a pretty large receive buffer for a TCPReceiver. The first enum caused a stack overflow error. Reducing the size stopped the error. Release mode did not complain about either size. struct TCPRawData{ void* pParent; this blew the stack - enum{max_length = 1048576}; this was fine - enum{max_length = 500000}; char buffer[max_length]; int bytesReceived; TCPRawData(void* parent): pParent(parent){} }; comment:5 Changed 6 years ago by This was the offending code from the TCPReceiver. TCPReadBuff = boost::make_shared<TCPRawData>(this); comment:6 Changed 5 years ago by This is not fixed, at least in Boost 1.50. It's reproducible in VS2008 Debug build. Please reopen. comment:7 Changed 5 years ago by The above example (with A_Size = 512) works for me with the latest Boost and VS2005 Debug. comment:8 Changed 5 years ago by It does fail with A_Size=1024 though, which is probably what you mean. comment:9 Changed 5 years ago by comment:10 Changed 5 years ago by comment:11 Changed 4 years ago by Not fixed in boost 1.55 either comment:12 Changed 4 years ago by Can you please tell me how to reproduce? (In [69250]) Fix make_shared to not copy the deleter. Refs #4256. Refs #3875.
https://svn.boost.org/trac10/ticket/4256
CC-MAIN-2017-47
en
refinedweb
In any interactive application, dependency tracking is one of the most significant problems you must solve. Usually, you apply some manual mechanism to update user interface (UI) components when the information model changes. For example, you might use the Observer pattern to notify registered objects of changes to a given subject. Or you might use the Publish/Subscribe pattern to broadcast changes to all listeners. Or you can route update messages with appropriate hints to all views. All these mechanisms work, but they all require effort by a person -- and that person will be you, the overworked programmer. An automatic dependency tracking mechanism can handle most of that work for you. Using the automatic mechanism resembles programming with a spreadsheet; you simply enter formulas, and the computer figures out when to calculate them. The major difference is that the automatic mechanism is object-oriented and speaks Java. The choice to track dependencies automatically is not based on laziness -- well, not entirely. By relieving the programmer from manually tracking dependencies, an automatic dependency mechanism removes a potential bug source. It also reduces the work needed to add features to the program. With a manual dependency mechanism, a program addition usually requires you to revisit prior dependencies to keep the user interface in sync with the model. However, when dependency is tracked automatically, the program discovers new dependencies on its own at runtime, with no programmer intervention. Of course, setting up such a mechanism takes some preparation. In this series, you will learn what it takes to create an interactive application using automatic dependency tracking. Automatic dependency tracking separates the information model (IM) from the UI so that the UI discovers dependencies upon the IM and automatically updates itself. In this first installment, you will find out how to construct the IM for a dependency-tracking application. In Part 2, you will see how to build the UI on top of the IM. In Part 3, you will use dependency to solve some common application problems. Part 1 lays the groundwork for automatic dependency tracking. You won't actually see automatic dependency tracking in action until Part 2, but your patience will be rewarded. Throughout the series we will develop Nebula, a drag-and-drop application for visually designing computer networks. With this application, network designers can model a physical network, determine addressing, and run simulations to discover problems. Admittedly, this is a complex example, but as you will see by the end of the series, automatic dependency tracking makes even complex problems quite manageable. Read the whole series on automatic dependency tracking: - Part 1: Design an information model for automatically discovering dependencies in interactive object-oriented applications - Part 2: Automatic dependency tracking discovers dependencies at runtime and updates the user interface - Part 3: Create a rich, interactive experience for your user Let's start at the beginning: a properly designed information model. Design the information model An information model is a system of software objects that models a set of problems in a given domain. Because our problem domain is network design, our IM consists of objects such as computers, routers, cables, and hubs. An IM's client is a person or software system that understands the problem domain. The IM interface (public class methods) should be designed specifically for someone knowledgeable in that domain. In other words, a network designer with the Nebula IM, a Java compiler, and a working knowledge of programming should be able to construct a network simulation straight from the source code. The UML diagram in Figure 1 depicts the information model for Nebula. Like any good software system, an information model is designed to accomplish specific tasks. Particularly, an IM must provide means for performing three activities: - Build: The client must be able to construct a model to the required degree of complexity to represent the problem. - Traverse: The client must be able to browse or search a given model to identify objects of interest, discover their information, and make required changes. - Apply: The client must be able to solve problems using the model, usually by evoking its predictive abilities. Nebula, for example, can predict the path a packet will take through a network, identifying every device it reaches along the way. Notice that an information model is not specifically designed for any given user interface. An IM has no presentation knowledge and doesn't create its own UI components such as visual proxies. This decision reduces coupling between the IM and UI, making the application design more maintainable; IM changes have little impact on UI code, just as UI changes have little impact on the IM. When designing the information model for an automatic dependency tracking application, observe three guidelines: - Clearly define ownership - Rely on object relationships to store information - Favor abstract data types over native types Clearly define object ownership Every object has exactly one owner, and ownership is not transferable. An object's owner is responsible for its creation and destruction. With clearly defined ownership, each object's responsibilities become more apparent. The owner provides means for building and traversing the objects under its control. (The owned objects themselves provide the third activity -- apply.) In Nebula, the Network object forms the root of the ownership tree. The Network owns all the Devices as well as the Cables that connect them. Devices in turn own Ports. Different kinds of devices -- Hubs, Computers, and Routers -- own different kinds of ports. The Network provides a method for creating each device and methods for traversing the collection of devices. Whether port, device, or cable, each object has exactly one owner; at the top of the ownership hierarchy is the Network. Object relationships store information The second guideline to follow when designing the IM is to rely on object relationships to store information. The alternative, storing identifying attributes, leads to unnecessary searching and potential referential errors. Object relationships offer a much richer traversal mechanism than searches, perform better, and ensure data integrity. They also greatly simplify the UI's job, as you will see in Part 2. In Nebula, a network interface card ( NIC) has a default gateway, which tells it where to forward packets destined for addresses outside the local subnet. When configuring a single computer, you identify the default gateway by IP address. An IP address represents identity in the real network; it uniquely identifies a network node. However, in Nebula we can take advantage of true object identity. The Nebula information model already includes an object -- Hop -- that represents a packet's target. Therefore, a reference to a Hop object, not an IP address, identifies the default gateway. There are many advantages to such a representation. For instance, we know for certain that a reference identifies an existing Hop object. If we relied upon an IP address, we would have to perform a search to validate the information. Second, each IP address is stored in only one place, the Hop object that it identifies. The network designer can easily change the address strategy without compromising the information's integrity. Third, we have direct access to the object that we wish to identify. We can use object references to traverse the network and immediately make requests of its various devices -- for example, to accept a packet. Favor abstract data types The IM's goal, remember, is to permit a client knowledgeable in the problem domain to access the information. To that end, you must expose information from the IM with access and mutate methods. The task for which it was designed demands it: build implies mutate; traverse implies access. However, you should not expose your classes' inner workings, as that would violate one of the fundamental rules of object-oriented design: information hiding. The trick is to hide the classes' inner workings while exposing information meaningful in the problem domain. Abstract data types (ADTs) do that well. An ADT provides a set of values and the operations that can be performed over that value set. An ADT might be restrictive, represented only by a small set of values (such as an enumeration), or it may be quite general, with a large or infinite set of values (like a stack). An ADT represents its values and operations in the most appropriate form for the desired application. Most likely the set of values and operations defined by int or double don't exactly match your desired problem domain. An ADT lets you be more precise. The ADT IP represents both IP addresses and subnets in Nebula. The IP ADT defines the set of 32-bit IP addresses with subnet masks. It includes a few utility operations, such as conversion to and from a string, and a few application-specific operations, such as testing for an address's inclusion in a given subnet. The information appropriate to the problem domain is available, as the client can obtain any Hop's IP address. But information is also hidden, in that you cannot see from the interface how an IP is actually represented. Clearly defined ownership, reliance on object relationships, and preference for ADTs govern the IM's design. Committing that design to code requires an additional set of disciplines. Code the information model When constructing the information model for an automatic dependency tracking application, apply three coding patterns: - Distinguish between definitive and dynamic state - Accept visitors to discover derived class type - Treat object relationships as identities and ADTs as values Definitive versus dynamic state Dynamic state is state that can change. It is typically modified in a mutate method and retrieved by an access method. Definitive state, on the other hand, does not change at any point during an object's lifetime. It is typically passed in as a constructor parameter and either used internally or exposed via an access method. For automatic dependency tracking to work, you must tell the dependency system when a dynamic attribute is accessed or mutated. To accomplish that, create a dynamic sentry, an object of type Dynamic that rides alongside the actual dynamic attribute. Whenever the dynamic attribute is accessed, you must invoke the dynamic sentry's onGet() method. Whenever the dynamic attribute mutates, invoke the dynamic sentry's onSet() method. However, definitive state requires no such sentry. Because definitive state does not change during an object's lifetime, it will never mutate. Dependence upon definitive state resembles dependence upon a constant: since you know it will never change, you don't need to track it. Therefore, you don't waste any effort tracking dependencies on definitive state. In Nebula, a Hop's IP address is dynamic. The Hop class has a mutate method setAddress(), which changes the address attribute, and an access method getAddress(), which retrieves it. Therefore, each method invokes a dynamic sentry. The Hop class appears below, complete with access and mutate methods: abstract public class Hop extends Port { public Hop() { } public IP getAddress() { m_dynAddress.onGet(); return m_address; } public void setAddress( IP address ) { if ( !m_address.equals(address) ) { m_dynAddress.onSet(); m_address = address; } } // Dynamic data private IP m_address = new IP(); // Dynamic sentries private Dynamic m_dynAddress = new Dynamic(); } Note that the above mutate method performs some redundancy checking. It only invokes onSet() if the attribute actually changes. This optimization saves some update time if an attribute's value is simply reasserted. Collections can also be dynamic. For instance, the device collection in the Network is dynamic because the collection itself can change. The methods that add and remove devices are mutators, while the one that retrieves the device iterator is an accessor. These methods, too, invoke a dynamic sentry, as shown below: public class Network { public Network() { } // Device access public Hub createHub() { // Add a new hub to the device collection. m_dynDevices.onSet(); Hub pNew = new Hub(); m_lDevices.add( pNew ); return pNew; } ... public void deleteDevice( Device victim ) { // Remove a device from the device collection. if ( m_lDevices.remove(victim) ) { m_dynDevices.onSet(); } } public Device.ConstantIterator getDeviceIterator() { // Traverse the device collection. m_dynDevices.onGet(); return new Device.ConstantIterator( m_lDevices.iterator() ); } // Data values private List m_lDevices = new LinkedList(); // of Devices ... // Dynamic sentries private Dynamic m_dynDevices = new Dynamic(); ... }
http://www.javaworld.com/article/2075515/swing-gui-programming/automate-dependency-tracking--part-1.html
CC-MAIN-2017-26
en
refinedweb
Complete code is available at Developer Code Samples It is common scenario to have the need to upload/download large files to/from server. There are mainly two options to upload/download large files in WCF applications - WCF Streaming - WCF Chunking In this blog post we will discuss how to implement WCF Streaming and WCF Chunking. We will use WCF Chunking to upload a large file and download it using WCF Streaming. Here is the WCF Service Contract [ServiceContract] public interface IService1 { [OperationContract] string FileUpload(FileData fileData); [OperationContract] bool FileUploadDone(string filename); [OperationContract] Stream DownloadFile(); } We will use FileUpload() function to upload the file. (Note: the return value is string as I don’t like throwing exceptions, I always like to return Boolean or string with error message). To download the file we will use DownloadFile() function. FileUpload() takes a WCF Data Contract as parameter, lets review its data structure : [DataContract] public class FileData { [DataMember] public string Filename { get; set; } [DataMember] public int Offset { get; set; } [DataMember] public byte[] Buffer { get; set; } } The most important member in this data structure is Buffer which holds the file buffer and Offset is used to determine the current buffer’s offset from the beginning of the file. Lets look at the implementation of the FileUpdate() function private static Dictionary<string, FileStream> wcfFileStreams = new Dictionary<string, FileStream>(); public string FileUpload(FileData fileData) { FileStream fs; string filepath = "c:\\temp\\" + fileData.Filename; try { lock (wcfFileStreams) { wcfFileStreams.TryGetValue(filepath, out fs); if (fs == null) { fs = File.Open(filepath, FileMode.Create, FileAccess.ReadWrite); wcfFileStreams.Add(filepath, fs); } } fs.Write(fileData.Buffer, 0, fileData.Buffer.Length); fs.Flush(); return string.Empty; } catch (System.Exception ex) { FileUploadDone(filepath); return ex.ToString(); } } Here we are going to save the uploaded file to c:\temp folder. Note: we have Dictionary object to store our FileStream, if multiple clients upload different files at the same time, we know which FileStream to update. We will close the FileStream object when the client invokes WCF Operation – FileUploadDone() Now, lets look at the client code ServiceReference1.FileData fileData = new ServiceReference1.FileData(); fileData.Filename = fileInfo.Name; fileData.Offset = offset; fileData.Buffer = new byte[BUFFER_SIZE]; FileStream fs = fileInfo.OpenRead(); newOffset = fs.Seek(offset, SeekOrigin.Begin); int read = fs.Read(fileData.Buffer, 0, BUFFER_SIZE); if (read != 0) { offset += read; c.FileUploadAsync(fileData); } else { c.FileUploadDoneAsync(fileInfo.Name); } Client is going to read small chunks of the file and is going to upload them using the FileData – WCF Data Contract. When the file Read() returns zero bytes, the client is going to call FileUploadDone() to tell the server that all pieces of the file are uploaded. Note : here I am using Async-pattern so that client’s calling thread doesn’t have to wait for response from the server. WCF Streaming Now lets look at WCF Streaming implementation. Streaming implementation is very easy, we just have to return the stream object to the WCF. Note: here the sample code is returning the last uploaded file public Stream DownloadFile() { if (!string.IsNullOrEmpty(_LastUploadedFilename)) { return File.OpenRead(_LastUploadedFilename); } return null; } Lets review the client code. The client code calls DownloadFile() and when the completed event is fired, it will call the EndDownloadFile() to get the file buffer private void buttonDownloadFile_Click(object sender, RoutedEventArgs e) { c.DownloadFileAsync(); } void DownloadFileCallback(IAsyncResult asyncResult) { SLWCFChunking.ServiceReference1.IService1 proxy = (SLWCFChunking.ServiceReference1.IService1)asyncResult.AsyncState; byte[] buffer = proxy.EndDownloadFile(asyncResult); } We will learn more about WCF Streaming in the next post. Complete code Complete code is available at Developer Code Samples
https://blogs.msdn.microsoft.com/webapps/2012/09/06/wcf-chunking/
CC-MAIN-2017-26
en
refinedweb
CodePlexProject Hosting for Open Source Software Is is recommended to use HTML5 with Composite C1? If I'm not mistaken, XSLT templates require XML... so you'd have to serve xHTML5... and as far as I can gather, IE doesn't do XHTML5. Am I totally off base, here? We have the folllowing known issues with html5 You should be good to go with html 5 if you can live without the SEO assistant (for now) and your users are not required to build up html 5 based page content in the WYSIWYG editor. Your layout templates, XSLTs, Web Forms, MVC views etc. can emit html 5 just fine. AFAIK html 5 documents can be both 'XML' and 'sloppy' so the fact that Composite C1 is 'XML' should not be a problem. You should be able to get there by just adding the doctype and then use the tags you want. If you find more html5 issues than the two listed above, please post about it. I assume you mean the standard HTML DOCTYPE, <!DOCTYPE html> Instead of this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: For HTML5: <!DOCTYPE html> <html xmlns="" xmlns: I noticed that when you remove the XML Namespace xmlns="" from the <html> tag, the composite system doesn't seem to recognize the layout and no server side stuff is done. HTML5 doesn't require the xmlns because HTML5 is by default in that namespace. This is what I have and it works: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="" xmlns: It would be really nice to see a list of gotchas when it comes to HTML5 and Composite C1 Since the rendering of all our C1 websites is done through the use of ASP.NET Master Pages we don't have this problem. But it should be an easy fix to attach a Filter that will remove the namespace from the <html> tag before the content is sent to the client. Yeah, it's not a huge deal, just interesting. How did you find the transition to using Master Pages? This is a pattern that I'm definitely used to, and I've seen some documentation on it here, but were there many roadblocks that you ran into? Were there things that didn't work in the Composite C1 ecosystem? Would love to see any references that you used. well, im the one behind so i would love to hear if you're having problems using it. Using Master Pages is very simple and the implementation in CompositeC1Contrib simply relies on a .master file being present with the same name as the Template in C1. If its not there, it will default back to using normal XLST Template rendering so the two methods can easily co-exist. Hopefully this will make into C1 very soon... 2.1 just had to get out the door with the scheduled features so we can look forward on new exciting stuff. A pure MVC rendering engine is also on the drawing board. Should we have a separate topic for html5? There are a few small things (or not so small) we've come across so far, and it might be good to segment it all off? Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://c1cms.codeplex.com/discussions/248386
CC-MAIN-2017-26
en
refinedweb
First Example Classes¶ To define a class in Java use the keywords (words that Java already understands) public class followed by a ClassName. Then the body of the class is enclosed in a starting { and ending } as shown below. public class ClassName { } Note In Java every open curly brace { must have a matched close curly brace }. These are used to start and end class definitions and method definitions. The following is an example class in Java. A class in Java can have fields (data or properties), constructors (ways to initialize the fields), methods (behaviors), and a main method for testing the class. It does not have to have any of these items. The following would compile, but what do you think would happen if you tried to have a computer execute it? public class FirstClass { } The class FirstClass doesn’t have anything inside of it, so the computer wouldn’t know what to do if we asked it to execute the class. When you ask the Java run-time to run a class (java ClassName) it will start execution in the main method. Click on the button below to have the computer execute the main method (starts with public static void main(String[] args)) in the following class. You can also click on the button to listen to a line by line description of the code. Note System.out.println is just the way that you ask Java to print out the value of something. In the case above we are just printing the characters between the first " and the second ". The "Hi there!" is called a string literal. A string literal is zero to many characters enclosed in starting and ending double quotes in Java. Try to change the code above to print your name. Be sure to keep the starting " and ending ". Click on the button to run the modified code. Mixed up programs 2-3-1: The following has all the correct code to print out "Hi my friend!" when the code is run, but the code is mixed up. Drag the blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution.public class ThirdClass { --- public static void main(String[] args) { --- System.out.println("Hi my friend!"); --- } --- } 2-3-2: The following has all the correct code to print out "Hi there!" when the code is run, but the code is mixed up and contains some extra blocks with errors. Drag the needed blocks from left to right and put them in the correct order. Click on the "Check Me" button to check your solution.public class FourthClass { --- public Class FourthClass { #paired --- public static void main(String[] args) { --- public static void main() { #paired --- System.out.println("Hi there!"); --- System.out.println("Hi there!") #paired --- } --- }
http://interactivepython.org/runestone/static/JavaReview/JavaBasics/firstClass.html
CC-MAIN-2017-26
en
refinedweb
This bug has been spun off from bug 510035. I fear we're heading for a Java train wreck on OS X on the 1.9.2 branch (what will become Firefox 3.6). We currently don't have a usable Java plugin for the 1.9.2 branch (or the trunk) on OS X, and none is likely to be available before next year -- some time between January and March, 2010, or possibly even later. This is well after the planned release of Firefox 3.6 (currently scheduled for November of this year). There are really only two feasible ways of dealing with this problem: 1) Postpone the 3.6 release until after Apple releases its port of Sun's Java Plugin2. 2) Restore OJI, Liveconnect and the JEP on the 1.9.2 branch. I have no control and little influence over whether or not we choose option 1. But I *can* show that option 2, though somewhat clumsy, is feasible. In my next comment I'll post a patch that restores OJI, the JEP and Liveconnect on the 1.9.2 branch. A developer preview of Apple's Java Plugin2 is actually present on OS X 10.6.X, and on OS X 10.5.8 if you've installed a recent Java update (Update 4 or Update 5). But it's not release quality -- Apple acknowledges this and doesn't provide a GUI for ordinary users to turn it on. "Not release quality" is in fact quite an understatement -- see bug 510035 comment #41. There's no way we can tell people to use that Java plugin in a Firefox release. Created attachment 401338 [details] Patch v1.0, full Here's a preliminary patch. It's quite large, so I'm going to make it available in three different copies -- the full patch, a full patch without the JEP, and a patch containing only revisions to existing files. The full patch is the one you'd want to apply. But the part corresponding to the JEP is a bunch of base64-encoded files, some of them quite large -- so this patch isn't exactly readable. (If you don't want to bother building from the full patch, a tryserver build should be available in a few hours.) The full patch without the JEP contains many "new" files (those containing the implementations of OJI and Liveconnect). It contains nothing but text files, so it's somewhat more readable. But most readable of all is the copy of the patch that contains only revisions to existing files. Created attachment 401340 [details] Patch v1.0, without JEP Created attachment 401342 [details] [diff] [review] Patch v1.0, changed files only I should say a little about my patch: I didn't restore things to the way they were before OJI, Liveconnect and the JEP were removed -- there have been too many changes in the underlying code for that to be possible (for example lots of interfaces have been changed or removed). Intead I made existing objects also (conditionally) support the old interfaces. I wrapped all my changes with define macros, so that none of them have any effect on other platforms than OS X. Even on the Mac, I haven't made any changes in how ordinary NPAPI plugins are handled. My restoration of OJI and Liveconnect are only meant to support the JEP, and have only been tested with the JEP (on OS X 10.5.8 and 10.6.1). If other OJI plugins existed they might cause trouble ... but I don't believe any others do exist. Here's a tryserver build made with the full copy of my v1.0 patch: But it somehow doesn't bundle the JEP. So (to test it) you'll need to download a copy of JEP 0.9.7.2 from and copy that to /Library/Internet Plug-Ins. I don't know why the JEP didn't get bundled -- possibly the tryserver doesn't like base64-encoded binary files in a patch. My tryserver build (based on my v1.0 patch) passed all tests (save for a spurious "broken pipe" error on the Linux unit test machine). My local build passed all tests locally, except for some reftest failures that also happen without my patch (and so are presumably due to problems with the tests). Created attachment 403558 [details] Patch v1.1, full Here's a new patch, with some minor changes. Once again I'm going to post three copies of it. A tryserver build should follow in a few hours. The previous patch made *almost* no changes except on the Mac, with one very small exception -- three "extern C" JavaScript methods were explicitly exported on all platforms. Now these methods are only explicitly exported on the Mac (only when OJI is defined) (this is needed by LiveConnect). My v1.1 patch now refuses to load any XPCOM plugin but the Java Embedding Plugin. If a plugin fails to load as an NPAPI plugin, the code now checks if it's a Java plugin, an XPCOM plugin (with an NSGetFactory() entry point), and if the plugin's name contains "Java Embedding Plugin". Only if all three tests pass does the plugin get loaded. I've also made a few other changes to tighten things up. For example I now always try to load a plugin as an NPAPI plugin before I try loading it as an OJI plugin (so a plugin that supports both APIs would have a chance to be loaded as an NPAPI plugin). And I've made a few more of the "old" interfaces' methods return errors if no XPCOM plugin has been loaded or instantiated. There's no way to stop the "old" interfaces being present -- which might confuse plugins/extensions that test for their presence. But, where possible, I've made these interfaces inoperable unless they're being used by an XPCOM plugin (i.e. by the JEP, which is the only XPCOM plugin that can get loaded/instantiated). Created attachment 403561 [details] Patch v1.1, without JEP Created attachment 403563 [details] [diff] [review] Patch v1.1, changed files only Comment on attachment 403558 [details] Patch v1.1, full Josh, I'm asking you to review this patch. But if you think parts of it should also be reviewed by other people, please add them. Here's a tryserver build made with my full v1.1 patch: Once again it doesn't (for some reason) bundle the JEP. So to test it you'll you'll need to download JEP 0.9.7.2 from and copy its binaries (JavaEmbeddingPlugin.bundle and MRJPlugin.plugin) to /Library/Internet Plug-Ins (or to the Contents/MacOS/plugins directory of my tryserver build's bundle). My v1.1 build passed all the tryserver tests except for two apparently spurious failures on a Linux box ("Linux try hg unit test") and a Windows box ("WINNT 5.2 try hg unit test"). Need this for beta. This patch needs at least one more revision.. I've opened bug 519734 to get Java Applet.plugin blocklisted on the 1.9.2 branch. But I need to figure out why 1.9.2-branch FF now prefers the Java Applet.plugin over the JEP (as earlier versions of the browser never did). I'll be working on this today and (probably) into tomorrow. (In reply to comment #14) >. Isn't this because OJI & friends aren't there, so the part of the JEP distro that handles Java 1.4 and above (even if installed manually) "can't be loaded"? That's the way I read bug 510035 comment 4, 9, etc., and specifically bug 510035 comment 12: > I'd forgotten that the MRJPlugin.plugin included with the JEP is able > to use Java 1.3.1 (where present), and when doing so doesn't use the > OJI API. Or have you done subsequent tests on your tryserver builds with the JEP and OJI restored and are still seeing only Java 1.3.1 loaded; comment 14 isn't clear about that. > I'd forgotten that the MRJPlugin.plugin included with the JEP is > able to use Java 1.3.1 (where present), and when doing so doesn't > use the OJI API. This comment of mine is (I now think) simply wrong. Sorry :-( The JEP's MRJPlugin.plugin *is* able to use Java 1.3.1 when JavaEmbeddingPlugin.plugin isn't present. But it still needs OJI. Scott Field at bug 510035 was definitely running Apple's Java 1.3.1. But I'm now pretty sure this was because he'd loaded Apple's Java Applet.plugin -- i.e. he wasn't getting it via the JEP's MRJPlugin.plugin. > Or have you done subsequent tests on your tryserver builds with the > JEP and OJI restored and are still seeing only Java 1.3.1 loaded; Yes. But there's more to the story. This only happens (as I now realize) with builds (made from my patch) that don't bundle the JEP. In other words, 1.9.2-branch Firefox (with my patch) only prefers Java Applet.plugin over the JEP when both are installed to /Library/Internet Plug-Ins/ (and no JEP exists in the distro's Contents/MacOS/plugins directory). This is because of a bug that's been introduced on the 1.9.2 branch (and also the trunk) -- FF now chooses the *older* of two plugins that support the same MIME type. Tomorrow I'll have more to say about all this. > FF now chooses the *older* of two plugins that support the same MIME > type. And have been installed to the same location (e.g. both installed to /Library/Internet Plug-Ins/, or both installed to the distro's Contents/MacOS/plugins/). Created attachment 404057 [details] Patch v1.2, full Here's a new patch with just one change: I discovered that 'make package' doesn't include the JEP in the resulting distro. (This is presumably the reason my previous patches' tryserver builds didn't bundle the JEP.) To fix this I needed to make a change to browser/installer/package-manifest.in. As I mentioned previously (comment #16), the problem I described in comment #14 doesn't happen when the JEP is bundled with a 1.9.2-branch distro (in its Contents/MacOS/plugins/ directory). There's definitely a bug on the trunk and 1.9.2 branch that makes the browser prefer older plugins for a given MIME type, but it doesn't effect the JEP in the default case (when it's bundled with FF). So fixing this bug doesn't depend on fixing the preference-order bug. So I'll address the preference-order bug elsewhere -- in another bug. I'm doing a tryserver build. But the tryservers are severely backed up, so it'll be quite a while before I can post a link here. Created attachment 404058 [details] Patch v1.2, without JEP Created attachment 404059 [details] [diff] [review] Patch v1.2, changed files only"). Steven: Forgive my ignorance - I assume this tryserver build is supposed to show the JEP in about:plugins? (In reply to comment #21) >"). > I assume this tryserver build is supposed to show the JEP in > about:plugins? It should ... but now I see that it doesn't. You *do* see JavaEmbeddingPlugin.bundle and MRJPlugin.plugin when you right-click on the app bundle, choose "Show Package Contents" and browse to Contents/MacOS/plugins. But now I see that the tryserver didn't "build" them properly -- these two bundles are missing all their "binaries"!!! This must (presumably) be because the tryservers can't deal with base64-encoded binaries in patches. 'make package' works properly with my local build (made with my v1.2 patch) -- when you install the app bundle from the resulting *.dmg file, it contains all the needed binaries and works correctly. For now I guess you've got to test in the following way: 1) Remove JavaEmbeddingPlugin.bundle and MRJPlugin.plugin from the Contents/MacOS/plugins/ directory of the tryserver build you downloaded and installed. 2) Download JEP 0.9.7.2 from and drag its binaries (JavaEmbeddingPlugin.bundle and MRJPlugin.plugin) to your tryserver download's Contents/MacOS/plugins/ directory. (I missed the lost binaries problem because I already have a copy of the JEP in my /Library/Internet Plug-Ins/ directory, and (on my system) the tryserver download silently failed over to using that.) For what it's worth, here's a link to a build I made locally with 'make package': It's too bad the tryservers won't let you do "push to try" on the 1.9.2 branch (only on the trunk). That's the only way I can think of to get around the problem of the tryservers not being able to deal with binaries in patches. > a bug that's been introduced on the 1.9.2 branch (and also the > trunk) -- FF now chooses the *older* of two plugins that support the > same MIME type. I've opened bug 520085 to deal with this. Comment on attachment 404057 [details] Patch v1.2, full I've looked over this and didn't see anything wrong but there is a lot here. The best thing to do is land it ASAP for testing but please get review from jst first. To be clear since I'm marking this r+, this is an inherently dangerous patch. Steven did a good job writing it as far as I can tell, but this is a lot of code that nobody understood well even when it was in the tree the first time. Comment on attachment 404057 [details] Patch v1.2, full Looks good to me. I asked Waldo to glance over the JS engine API changes here as well. #endif // __cplusplus Speaking only for JS code, I'm sure we want these to be C-style /* */ comments, as they likely cause build warnings (might not even build on particularly pedantic compilers). Line 298-ish of the new jsfun.cpp has this: ... } #ifdef OJI JS_END_EXTERN_C #endif #ifdef OJI JS_BEGIN_EXTERN_C JS_EXPORT_API(void) #else void #endif js_PutArgsObject(JSContext *cx, JSStackFrame *fp) ... The end/begin here is pointless, right? Please get rid of it. The comment /* Allow inclusion from LiveConnect C files */ (passim) should include a trailing period, throughout, because it's not a sentence fragment. With those changes js/src looks fine. > The end/begin here is pointless, right? What do you mean? JS_BEGIN_EXTERN_C and JS_END_EXTERN_C? Are you telling me that's pointless? I don't know myself. I believe it should be; those macros are just gunk that expands to extern "C" { and } if __cplusplus and nothing otherwise, so I think they can be omitted. It'd only be necessary if there were something between the two, but there's only whitespace there after the preprocessor does its thing. Oh now I see (I think). You're just saying I shouldn't have a JS_END_EXTERN_C just before a JS_BEGIN_EXTERN_C. I should consolidate the two blocks. What I'm saying is that this: ... } #ifdef OJI JS_END_EXTERN_C #endif #ifdef OJI JS_BEGIN_EXTERN_C JS_EXPORT_API(void) #else void #endif js_PutArgsObject(JSContext *cx, JSStackFrame *fp) ... expands to this in C++ with OJI: ... } } extern "C" { JS_EXPORT_API(void) js_PutArgsObject(JSContext *cx, JSStackFrame *fp) ... but since there's nothing between the } that closed the extern "C" started way above and the extern "C" that starts a new such block, there's no reason to close and reopen -- just do: ... } #ifdef OJI JS_EXPORT_API(void) #else void #endif js_PutArgsObject(JSContext *cx, JSStackFrame *fp) ... I understand now. Will do. Created attachment 404993 [details] Patch v1.3, full I've run into trouble. There've been many changes to JS code since my v1.2 patch, and I've had to make changes to JS header files (and sometimes to *.cpp) files to get Liveconnect to compile and link properly. But now I crash in a JS trace stack every time I load a Java applet. I don't *think* this is caused by anything in my patch (even the newest one). Rather I suspect there's been some kind of change to JS tracing in the last week, and that's the source of the trouble. But I don't know a whole lot about JS code, so I'm asking for help from the JS people. Andreas Gal, your name popped up. So I'm cc-ing you on this bug. Thanks in advance for whatever suggestions you can come up with! I'll post a stack trace of my crashes in a later comment. Created attachment 404994 [details] [diff] [review] Patch v1.3, changed files only (In reply to comment #35) > Created an attachment (id=404993) [details] > Patch v1.3, full > > I've run into trouble. ... > But now I crash in a > JS trace stack every time I load a Java applet. Attach the stacks here. Created attachment 404995 [details] Gdb stack of js trace crash (In reply to comment #38) > Created an attachment (id=404995) [details] > Gdb stack of js trace crash That's a GC bug, confusing also called "tracer". not related to the JIT. 2688 else 2689 JS_TraceChildren(trc, thing, kind); 2690 } else { Not sure how we end up at pc == 0x00000000 with that. Maybe that gets inlined? 2416 /* If obj has no map, it must be a newborn. */ 2417 JSObject *obj = (JSObject *) thing; 2418 if (!obj->map) 2419 break; 2420 obj->map->ops->trace(trc, obj); Maybe ops->trace is NULL? A bunch of wrappers are on the call stack. Maybe one of them isn't implemented right? 2421 break; I'll be using 'hg bisect' on this. I should know more later today. Steven, update here? I'm closing in on the guilty patch. I should have it within an hour. I have no idea how close I am to a fix, though. I'll know more once I've identified the patch that triggered the crashes. 'hg bisect' found the patch that triggers my crashes: "bug 511425 - removal of JSObjectOps.(get|set)RequiredSlot" Igor Bukanov <[email protected]> I'll look through the patch for something more specific. But I'm likely to need help from JS developers. The first comment in bug 511425 makes me think that you should just back it out on 1.9.2 to start. #45: thats the plan, mrbkap agrees too, working on it (In reply to comment #45) > The first comment in bug 511425 makes me think that you should just back it out > on 1.9.2 to start. This is not necessary, implementing JSObjectOps.trace in liveconnect is enough to fix this. (In reply to comment #47) > This is not necessary, implementing JSObjectOps.trace in liveconnect is enough > to fix this. Beat you to that one: bug 521135 has that patch. Its not clear that that is enough though. We are crashing in the cycle collector now. Created attachment 405296 [details] Patch v1.4, full Here's a new revision to my patch, which updates it to current code. It still crashes, of course -- so I won't do a tryserver build. But here's a user repository with the patch on top of it: Created attachment 405297 [details] [diff] [review] Patch v1.4, changed files only I've spun off bug 521338 to follow gal's and mrbkap's current work on fixing the crashes. mrbkap has been adding patches to my user repository (). After a couple hours of testing, I've concluded that the patches at bug 521338 completely fix the problems triggered by the patch for bug 511425 (the crash I reported at comment #38, and another crash reported at bug 521338 comment #1). The patches at bug 521338 still need to be reviewed. But once that happens I think they can land on the 1.9.2 branch, either on top of or in combination with my patch for this bug. (My v1.4 patch will once again need to be updated to current code, but that shouldn't be difficult -- there haven't been many changes since I posted it.) Landed on the 1.9.2 branch, together with mrbkap's patch for bug 521338: Dbaron just pointed out to me that some OJI/Liveconnect-related leaks were triggered by this landing: I'll try to figure out what's going on next week (starting Monday). Steven, do you have a collection of web pages which use Java Applets and we can use for testing? Probably the best place to start is bug 371084 comment #3. Four or five of those applets have by now disappeared from the web, but the rest give you quite a bit to work with. Also look at Sun's demo applets at. The ones I use most often are the Clock (of course), plus ArcTest, ImageMap and Molecule Viewer's "example3". ImageMap is currently partially broken (in Namoroka after my patch) -- clicking on the developer's face doesn't take you to. This may be a bug in the JEP, which I'll be working on as I have the time. Clicking on the developer's face? Don't ask me, I didn't write it :-) (In reply to comment #55) > Dbaron just pointed out to me that some OJI/Liveconnect-related leaks > were triggered by this landing: Is there a bug filed on the leak? Now there is -- bug 521599. Verified fixed on the 1.9.2 branch using Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2b1pre) Gecko/20091013 Namoroka/3.6b1pre as well as the equivalent build on 10.5 and 10.4. This bug is 1.9.2 only so switching to verified fixed too. (Following up comment #57) > ImageMap is currently partially broken (in Namoroka after my patch) > -- clicking on the developer's face doesn't take you to >. This may be a bug in the JEP, which I'll be > working on as I have the time. I've found out this is a Firefox bug, and I've opened bug 523129.
https://bugzilla.mozilla.org/show_bug.cgi?id=517355
CC-MAIN-2017-26
en
refinedweb
gnutls_cipher_tag(3) gnutls gnutls_cipher_tag(3) gnutls_cipher_tag - API function #include <gnutls/crypto.h> int gnutls_cipher_tag(gnutls_cipher_hd_t handle, void * tag, size_t tag_size); gnutls_cipher_hd_t handle is a gnutls_cipher_hd_t type void * tag will hold the tag size_t tag_size the length of the tag to return This function operates on authenticated encryption with associated data (AEAD) ciphers and will return the output tag. Zero or a negative error code on error._tag(3)
http://man7.org/linux/man-pages/man3/gnutls_cipher_tag.3.html
CC-MAIN-2017-26
en
refinedweb
PMIERRSTR(3) Library Functions Manual PMIERRSTR(3) pmiErrStr - convert a LOGIMPORT error code into a string #include <pcp/pmapi.h> #include <pcp/import.h> const char *pmiErrStr(int code); char *pmiErrStr_r(int code, char buf, int buflen); cc ... -lpcp_import -lpcp use PCP::LogImport; pmiErrStr($code); As part of the Performance Co-Pilot Log Import API (see LOGIMPORT(3)), pmiErrStr translates error codes returned from the other routines in the Log Import library into printable error messages. code would normally have a negative value. As a special case, if code is -1 then the error code returned from the last routine called in the LOGIMPORT library for this context will be used. The pmiErrStr_r function does the same, but stores the result in a user-supplied buffer buf of length buflen, which should have room for at least PMI_MAXERRMSGLEN bytes. The set of possible error codes and messages is all those defined by pmErrStr(3) and PCPIntro(3), plus the additonal ones defined in <pcp/import.h> with error code names of the form PMI_ERR_.... None. LOGIMPORT(3), PCPIntro(3) and pmErrIERRSTR(3) Pages that refer to this page: logimport(3), pmiaddinstance(3), pmiaddmetric(3), pmiend(3), pmigethandle(3), pmiputmark(3), pmiputresult(3), pmiputvalue(3), pmiputvaluehandle(3), pmisethostname(3), pmisettimezone(3), pmistart(3), pmiusecontext(3), pmiwrite(3)
http://man7.org/linux/man-pages/man3/pmierrstr.3.html
CC-MAIN-2017-26
en
refinedweb
Implementing iOS 10 TableView Navigation using Storyboards in Xcode 8 The objective of this chapter is to extend the application created in the previous chapter (entitled Using Xcode 8 Storyboards to Build Dynamic TableViews) and, in so doing, demonstrate the steps involved in implementing table view navigation within a storyboard. In other words, we will be modifying the attractions example from the previous chapter such that selecting a row from the table view displays a second scene in which a web page providing information about the chosen location will be displayed to the user. new View Controller Cocoa Touch Class option from the iOS Source category. On the options screen, make sure that the Subclass of menu is set to UIViewController, name the new class AttractionDetailViewController and make sure that the Also create XIB file option is switched 30 1. With the new view controller added, select it and display the identity inspector (View -> Utilities -> Show Identity Inspector) and change the class setting from UIViewController to AttractionDetailViewController. Figure 30 Attraction Table View Controller item in the storyboard so that it highlights in blue, and then selecting the Xcode Editor -> Embed In -> Navigation Controller menu option. Once performed, the storyboard will appear as outlined in Figure 30-2: Figure 30-2 Establishing the Storyboard Segue When the user selects a row within the table view, a segue needs to be triggered to display the attraction detail view controller. In order to establish this segue, Ctrl-click on the prototype cell located in the Attraction Table View Controller scene and drag the resulting line to the Attraction Detail View Controller scene. Upon releasing the line, select the show Attraction Table View Controller and Attraction Detail View Controller, display the Attributes Inspector (View -> Utilities -> Show Attributes Inspector) and change the Identifier value to ShowAttractionDetails. In addition, a toolbar should have appeared in both scenes. Double-click on the center of the Attraction Table View Controller toolbar and change the title to “Attractions”. Next, drag a Navigation Item view from the Object Library and drop it onto the toolbar of the Attraction Detail View Controller. Double-click on the Title and change it to “Attraction Details”: Figure 30-3 Build and run the application and note that selecting a row in the table view now displays the second view controller which, in turn, has a button in the toolbar to return to the “Attractions” table view. Clearly, we now need to do some work on the AttractionDetailViewController class so that information about the selected tourist location is displayed in the view. Modifying the AttractionDetailViewController Class For the purposes of this example application, the attraction detail view is going to display a web view loaded with a web page relating to the selected tourist attraction. In order to achieve this, the class is going to need a UIWebView object which will later be added to the view. In addition to the web view, the class is also going to need an internal data model that contains the URL of the web page to be displayed. It will be the job of the table view controller to update this variable prior to the segue occurring so that it reflects the selected attraction. For the sake of simplicity, the data model will take the form of a String object. Select the AttractionDetailViewController.swift file and modify it as follows to declare this variable: import UIKit class AttractionDetailViewController: UIViewController { var webSite: String? . . .The next step is to add the Web View to the view controller. Select the storyboard file in the Project Navigator, and drag and drop a Web View from the Object Library onto the Attraction Detail scene. Resize the view so that it fills the entire scene area as illustrated in Figure 30-4: Figure 30-4 With the Web View selected in the storyboard canvas, display the Auto Layout Add New Constraints menu and add Spacing to nearest neighbor constraints on all four sides of the view with the Constrain to margins option disabled. Display the Assistant Editor panel and verify that the editor is displaying the contents of the AttractionDetailViewController.swift file. Ctrl-click on the Web View and drag to a position just below the class declaration line in the Assistant Editor. Release the line and in the resulting connection dialog establish an outlet connection named webView. When the detail view appears, the Web View will need to load the web page referenced by the webSite string variable. This can be achieved by adding code to the viewDidLoad method of the AttractionDetailViewController.swift file as follows: override func viewDidLoad() { super.viewDidLoad() if let address = webSite { let webURL = URL(string: address) let urlRequest = URLRequest(url: webURL!) webView.loadRequest(urlRequest) } } Using prepare(for segue:) to Pass Data between Storyboard Scenes The last step in the implementation of this project is to add code so that the data model contained within the AttractionDetailViewController class is updated with the URL of the selected attraction when a table view row is touched by the user. As previously outlined in Using Storyboards in Xcode 8, the prepare(for segue:) method on an originating scene is called prior to a segue being performed. This is the ideal place to add code to pass data between source and destination scenes. The prepare(for segue:) method needs to be added to the AttractionTableViewController.swift file as outlined in the following code fragment: override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowAttractionDetails" { let detailViewController = segue.destination as! AttractionDetailViewController let myIndexPath = self.tableView.indexPathForSelectedRow! let row = myIndexPath.row detailViewController.webSite = webAddresses[row] } }The first task performed by this method is to check that the triggering segue is the ShowAttractionDetails segue we added to the storyboard. Having verified that to be the case the code then obtains a reference to the view controller of the destination scene (in this case an instance of our AttractionDetailViewController class). The table view object is then interrogated to find out the index of the selected row which, in turn, is used to prime the URL string variable in the AttractionDetailViewController instance. Testing the Application The final step is to compile and run the application. Click on the run button located in the Xcode toolbar and wait for the application to launch. Select an entry from the table and watch as the second view controller appears and loads the appropriate web page: Figure 30(for segue:) method as a mechanism for passing data during a segue has also been explored and demonstrated.
http://www.techotopia.com/index.php/Implementing_iOS_8_TableView_Navigation_using_Storyboards_in_Xcode_6_and_Swift
CC-MAIN-2017-26
en
refinedweb
I am trying to use the rayshoot method on some objects in a rhino scene. geometry = rs.GetObject ("Pick object") intPt = Rhino.Geometry.Intersect.Intersection.RayShoot(ray, [geometry], bounce) print intPt currently I an just trying to get it to work by selecting the object (mesh or surface) and see the return value. This gives the error: Unable to cast object of type 'System.Guid' to type 'Rhino.Geometry.GeometryBase'. Is there a way to convert a Guid to a geometry base object? Ultimately I want to just parse the entire scene and go through all the objects, so the user wont be selecting each one, but for now, I can't find information on how to get the basetype and not the guid. Hi Matthew, If you have an object's id (e.g. Guid), then you can get the object. And from the object you can get the geometry. Also, rhinoscryptsyntax does have a ShootRay method. Check the help file for details. import rhinoscriptsyntax as rs def TestRayShooter(): corners = [] corners.append((0,0,0)) corners.append((10,0,0)) corners.append((10,10,0)) corners.append((0,10,0)) corners.append((0,0,10)) corners.append((10,0,10)) corners.append((10,10,10)) corners.append((0,10,10)) box = rs.AddBox(corners) dir = 10,7.5,7 reflections = rs.ShootRay(box, (0,0,0), dir) rs.AddPolyline( reflections ) rs.AddPoints( reflections ) TestRayShooter() More on Rhino.Python -- Dale For others, the function I was looking for was coerce geometry = rs.coercebrep(geometry)
https://discourse.mcneel.com/t/getting-geometrybase-from-guid/44665
CC-MAIN-2017-26
en
refinedweb
earier. Status Currently, most tools available here can be used to analyze code-size and attibution the .info.json files. You can parse the information using AllInfo.parseFromJson. For example: import 'dart:convert'; import 'dart:io'; import 'package:dart2js_info/info.dart'; main(args) { var infoPath = args[0]; var json = JSON.decode(new File(infoPath).readAsStringSync()); var info = AllInfo.parseFromJson). function_size_analysis: a tool that shows how much code was attributed to each function. This tool also uses depedency: pub global activate dart2js_info # only needed once pub global run pub global run dart2js_info:library_size_split out.js.info.json Libraries can be grouped using regular expressions. You can specify what regular expressions to use by providing a grouping.yaml file: pub global run of all libraries together, it is shown in # cluster #3, which happens to be the last cluster in this example: - name: "Total (excludes preambles, statics & consts)" regexp: ".*" cluster: 3 # This group shows the total size for all libraries that were loaded from # file:// urls: - {: "(.*)" Function size analysis tool This command-line tool presents how much each function contributes to the total code of your application. We use dependency information to compute dominance and reachability data as well. When you run: pub global activate dart2js_info # only needed once pub global run: pub global run excersize the entire code. Shut down the coverage server (Ctrl-C). This will emit a file named mail.dart.js.coverage.json Finally, run the live code analysis tool given it both the info and converage json files: pub global run dart2js_info:live_code_size_analysis main.dart.info.json main.dart.coverage.json Code location, features and bugs This package is developed in github. Please file feature requests and bugs at the issue tracker. Libraries - dart2js_info.info Data produced by dart2js when run with the --dump-infoflag.
https://www.dartdocs.org/documentation/dart2js_info/0.0.1/index.html
CC-MAIN-2017-26
en
refinedweb
I have several csv-files, some of which are compressed but others are not, all in a 7z archive. I want to read the csv files and save the content in a database. However, whenever py7zlib attemts to read the data from a csv file that is actually not compressed, I get the error data error during decompression import os import py7zlib scr = r'Y:\PathtoArchive' z7file = 'ArchiveName.7z' with open(os.path.join(scr,z7file),'rb') as f: archive = py7zlib.Archive7z(f) names = archive.filenames for mem in names: obj = archive.getmember(mem) print obj.compressed # prints None for uncompressed data try: data = obj.read() except Exception as er: print er # prints data error during decompression # whenever obj.compressed is None File "C:\Anaconda\lib\site-packages\py7zlib.py", line 608, in read data = getattr(self, decoder)(coder, data, level) File "C:\Anaconda\lib\site-packages\py7zlib.py", line 671, in _read_lzma return self._read_from_decompressor(coder, dec, input, level, checkremaining=True, with_cache=True) File "C:\Anaconda\lib\site-packages\py7zlib.py", line 646, in _read_from_decompressor tmp = decompressor.decompress(data) ValueError: data error during decompression Though I couldn't really figure out what the problem seemed to be, I found a workaround that solved the ultimate goal to obtain the data from csv-files from a 7z-archive. 7-zip comes with a command line tool. Communicating with that tool via the subprocess module, I could automatically extract the files that I wihsed to extract without any problems import subprocess import py7zlib archiveman = r'c:\Program Files\7-zip\7z' # 7z.exe comes with 7-zip archivepath = r'C:\Path\to\archive.7z' with open(archivepath,'rb') as f: archive = py7zlib.Archive7z(f) names = archive.filenames for name in names: _ = subprocess.check_output([archiveman, 'e', archivepath, '-o{}'.format(r'C:\Destination\of\copy'), name]) The different commands that can be used with 7z can be found here.
https://codedump.io/share/Fq7PxujFDgW8/1/python-extract-uncompressed-data-from-7z-file
CC-MAIN-2017-47
en
refinedweb
Making Your First Webapp with React. It is interesting to compare the results - the React version has a few more lines of code than the jQuery version, but we can both agree that it is much better organized. What you need to know about React - It is a popular client-side library/framework for building user interfaces, which is developed and used by Facebook. - With it, you organize your application around discrete components, with each handling its own rendering and state. Components can be nested within each other. - React is fast because it minimizes the number of writes to the DOM (the slowest part of any client-side application). - The recommended way to write React code is by using JSX - an extension to JavaScript which presents components as HTML elements. JSX needs to be compiled to JS in order to work in browsers. - It hasn't hit version 1.0 as of this writing, so there might be changes in the future. - We have a nice article with examples for learning react which you can check out. Also there is the official getting started guide here. What we will be building We will create a simple web app, which invites people to search for locations and to store them in their browsers' localStorage. The locations will be presented on a Google Map with the help of the GMaps plugin. We will use Bootstrap with the Flatly theme for the interface. In the process, we will break the application down into logical components and make them talk to each other. Running the demo If you don't want to read the entire tutorial, you can go ahead and download the source code from the download button above. To run it, you need to have Node.js and npm installed. Assuming that you have, here is what you need to do: - Download the zip with the source code from the button above. - Extract it to a folder somewhere on your computer. - Open a new terminal (command prompt), and navigate to that folder. - Execute npm install. This will download and install all dependencies that are needed. - Execute npm run build. This will compile the react components down to a regular JavaScript file named compiled.js. - Open index.html in your browser. You should see the app. There is one more npm command that I've prepared for you to make your development easier: npm run watch This will compile the JSX code down to JavaScript and will continue to monitor it for changes. If you change a file, the code will be recompiled automatically for you. You can see these commands in the package.json file. The source code is easy to follow and has plenty of comments, so for those of you who prefer to read the source, you can skip the rest of the article. Setting things up As I mentioned, the recommended way to write React code is by using a JavaScript extension called JSX, which needs to be transformed to JavaScript. There are a few tools that can do this but the one I recommend is reactify - a browserify transform. So in addition to compiling JSX down to JavaScript, you get access to the require() node.js call and with it the ability to install and use libraries from npm. To set up reactify, browserify and the rest, run this command: npm install browserify reactify watchify uglify-js react To create a production ready and minified JavaScript file, which you can put online, run this command in your terminal: NODE_ENV=production browserify -t [ reactify --es6 ] main.js | uglifyjs > compiled.min.js Reactify supports a limited set of the new ES6 features with the --es6 flag, which I've used in the source code (you will see it in a moment). While developing, use the following command: watchify -v -d -t [ reactify --es6 ] main.js -o compiled.js Watchify will monitor your files for changes and recompile your source code if it is needed. It also enables source maps, so you can use the Chrome Debugger to step through your code. Great! You can now write React modules, require() npm libraries and even use some ES6 features. You are ready for writing some code! The code Here are the components that we will be writing: - App is the main component. It contains methods for the actions that can be performed by the user like searching, adding a location to favorites and more. The other components are nested inside it. - CurrentLocation presents the currently visited address in the map. Addresses can be added or removed from favorites by clicking the star icon. - LocationList renders all favorite locations. It creates a LocationItem for each. - LocationItem is an individual location. When it is clicked, its corresponding address is searched for and highlighted in the map. - Map integrates with the GMaps library, and renders a map from Google Maps. - Search is a component that wraps around the search form. When it is submitted, a search for the location is triggered. App.js First up is App. In addition to the lifecycle methods that React requires, it has a few additional ones that reflect the main actions that can be performed by the user like adding and removing an address from favorites and searching. Notice that I am using the shorter ES6 syntax for defining functions in objects. var React = require('react'); var Search = require('./Search'); var Map = require('./Map'); var CurrentLocation = require('./CurrentLocation'); var LocationList = require('./LocationList'); var App = React.createClass({ getInitialState(){ // Extract the favorite locations from local storage var favorites = []; if(localStorage.favorites){ favorites = JSON.parse(localStorage.favorites); } // Nobody would get mad if we center it on Paris by default return { favorites: favorites, currentAddress: 'Paris, France', mapCoordinates: { lat: 48.856614, lng: 2.3522219 } }; }, toggleFavorite(address){ if(this.isAddressInFavorites(address)){ this.removeFromFavorites(address); } else{ this.addToFavorites(address); } }, addToFavorites(address){ var favorites = this.state.favorites; favorites.push({ address: address, timestamp: Date.now() }); this.setState({ favorites: favorites }); localStorage.favorites = JSON.stringify(favorites); }, removeFromFavorites(address){ var favorites = this.state.favorites; var index = -1; for(var i = 0; i < favorites.length; i++){ if(favorites[i].address == address){ index = i; break; } } // If it was found, remove it from the favorites array if(index !== -1){ favorites.splice(index, 1); this.setState({ favorites: favorites }); localStorage.favorites = JSON.stringify(favorites); } }, isAddressInFavorites(address){ var favorites = this.state.favorites; for(var i = 0; i < favorites.length; i++){ if(favorites[i].address == address){ return true; } } return false; }, searchForAddress(address){ var self = this; // We will use GMaps' geocode functionality, // which is built on top of the Google Maps API GMaps.geocode({ address: address, callback: function(results, status) { if (status !== 'OK') return; var latlng = results[0].geometry.location; self.setState({ currentAddress: results[0].formatted_address, mapCoordinates: { lat: latlng.lat(), lng: latlng.lng() } }); } }); }, render(){ return ( <div> <h1>Your Google Maps Locations</h1> <Search onSearch={this.searchForAddress} /> <Map lat={this.state.mapCoordinates.lat} lng={this.state.mapCoordinates.lng} /> <CurrentLocation address={this.state.currentAddress} favorite={this.isAddressInFavorites(this.state.currentAddress)} onFavoriteToggle={this.toggleFavorite} /> <LocationList locations={this.state.favorites} activeLocationAddress={this.state.currentAddress} onClick={this.searchForAddress} /> </div> ); } }); module.exports = App; In the render method, we initialize the other components. Each component receives only the data that it needs to get its job done, as attributes. In some places, we also pass methods which the child components will call, which is a good way for components to communicate while keeping them isolated from one another. CurrentLocation.js Next is CurrentLocation. This component presents the address of the currently displayed location in an H4 tag, and a clickable star icon. When the icon is clicked, the App's toggleFavorite method is called. var React = require('react'); var CurrentLocation = React.createClass({ toggleFavorite(){ this.props.onFavoriteToggle(this.props.address); }, render(){ var <h4 id="save-location">{this.props.address}</h4> <span className={starClassName} onClick={this.toggleFavorite}</span> </div> ); } }); module.exports = CurrentLocation; LocationList.js LocationList takes the array with favorite locations that was passed to it, creates a LocationItem object for each and presents it in a Bootstrap list group. var React = require('react'); var LocationItem = require('./LocationItem'); var LocationList = React.createClass({ render(){ var self = this; var locations = this.props.locations.map(function(l){ var active = self.props.activeLocationAddress == l.address; // Notice that we are passing the onClick callback of this // LocationList to each LocationItem. return <LocationItem address={l.address} timestamp={l.timestamp} active={active} onClick={self.props.onClick} /> }); if(!locations.length){ return null; } return ( <div className="list-group col-xs-12 col-md-6 col-md-offset-3"> <span className="list-group-item active">Saved Locations</span> {locations} </div> ) } }); module.exports = LocationList; LocationItem.js LocationItem represents an individual favorite location. It uses the moment library to calculate the relative time since the location was added as a favorite. var React = require('react'); var moment = require('moment'); var LocationItem = React.createClass({ handleClick(){ this.props.onClick(this.props.address); }, render(){ var{ moment(this.props.timestamp).fromNow() }</span> <span className="glyphicon glyphicon-menu-right"></span> </a> ) } }); module.exports = LocationItem; Map.js Map is a special component. It wraps the Gmaps plugin, which is not a React component by itself. By hooking to the Map's componentDidUpdate method, we can initialize a real map inside the #map div whenever the displayed location is changed. var React = require('react'); var Map = React.createClass({ componentDidMount(){ // Only componentDidMount is called when the component is first added to // the page. This is why we are calling the following method manually. // This makes sure that our map initialization code is run the first time. this.componentDidUpdate(); }, componentDidUpdate(){ if(this.lastLat == this.props.lat && this.lastLng == this.props.lng){ // The map has already been initialized at this address. // Return from this method so that we don't reinitialize it // (and cause it to flicker). return; } this.lastLat = this.props.lat; this.lastLng = this.props.lng var map = new GMaps({ el: '#map', lat: this.props.lat, lng: this.props.lng }); // Adding a marker to the location we are showing map.addMarker({ lat: this.props.lat, lng: this.props.lng }); }, render(){ return ( <div className="map-holder"> <p>Loading...</p> <div id="map"></div> </div> ); } }); module.exports = Map; Search.js The Search component consists of a Bootstrap form with an input group. When the form is submitted the App's var React = require('react'); var Search = React.createClass({ getInitialState() { return { value: '' }; }, handleChange(event) { this.setState({value: event.target.value}); }, handleSubmit(event){ event.preventDefault(); // When the form is submitted, call the onSearch callback that is passed to the component this.props.onSearch(this.state.value); // Unfocus the text input field this.getDOMNode().querySelector('input').blur(); }, render() { return ( <form id="geocoding_form" className="form-horizontal" onSubmit={this.handleSubmit}> <div className="form-group"> <div className="col-xs-12 col-md-6 col-md-offset-3"> <div className="input-group"> <input type="text" className="form-control" id="address" placeholder="Find a location..." value={this.state.value} onChange={this.handleChange} /> <span className="input-group-btn"> <span className="glyphicon glyphicon-search" aria-</span> </span> </div> </div> </div> </form> ); } }); module.exports = Search; main.js All that is left is to add the App component to the page. I am adding it to a container div with the #main id (you can see this element in index.html in the downloadable zip file). var React = require('react'); var App = require('./components/App'); React.render( <App />, document.getElementById('main') ); In addition to these files, I have included the GMaps library and the Google Maps JavaScript API on which it depends, as <script> tags in index.html. We're done! I hope that this tutorial gave you a better understanding of how to structure React applications. There is much more you can do with the library, including server-side rendering, which we hope to cover in the future. Presenting Bootstrap Studio a revolutionary tool that developers and designers use to create beautiful interfaces using the Bootstrap Framework. It's an amazing web app!! Can you add auto-complete or suggest location while typing in location text field?? Hi Guys, I have created a simple repo which has react integrated with server and i am using browserify for porting react code to client as well. Uses Grunt, Node, Less, Eslint, React on server and client (using browserify) Would love if people can contribute and make it better. Thanks, Pavan This is awesome! Please keep this up! React.js is a really interesting library, and I'd love to see more of it on this site. Thanks again! That's amazing app. I can learn a lot of from your article. Thanks Nick very much. Single Page App using React, FLUX, Node.js, Atomic CSS (Atomizer), Less.js, Grunt Atomizer is by Yahoo! and uses radical(crazy) approach of not bloating css It seems odd to me, as I'm learning this. Why do you define all your functions in the "app" level and pass them around from function to function? Shouldn't you let the component handle it's functionality? It seems strange and inefficient to define one giant list of functions and pass them around. When running NODE_ENV=production browserify -t [ reactify --es6 ] main.js | uglifyjs > compiled.min.js I get an error that it cannot find module 'moment' in the components directory. Bummer, I was looking forward to this. Also users need to globally install browserify and uglify-js, you might want to make sure people know that before doing the tutorial. Can't assume people have the exact preset dev environment as you. Hey Jake, try running $ npm install moment --save that should fix it! Awesome tutorial, bud! Laid it all out clean and concise. Since update of react to 0.14 version, it has been separted to react and react-dom. Maybe you should also update your tutorial and change the souce codes as well. Other than that, great tutorial. Hey all! I created an updated version of this tutorial () that complies with the new version. Using Redux and ES6, I built one here:. Based on this tutorial and why did you import "LocationItem" into LocationItem.js It's a mistake, thanks for spotting that out.
https://tutorialzine.com/2015/04/first-webapp-react
CC-MAIN-2017-47
en
refinedweb
Search Create Advertisement Upgrade to remove ads 29 terms bruendy FIN445 STUDY PLAY a poison pill a financial device designed to make unfriendly takeover attempts unappealing, if not impossible All else equal, the market value of a stock will tend to decrease by roughly the amount of the dividend on the: ex-dividend date All else constant, a bond will sell at ______ when the coupon rate is _____ the yield to maturity. a discount; less than... if YTM > cpn. rt --> par value > bond price an indenture is: the legal agreement between the bond issuer and the bondholders A bond that can be paid off early at the issuer's discretion is referred to as being what: callable The break-even tax rate between a taxable corporate bond yielding 7 percent and a comparable nontaxable municipal bond yielding 5 percent can be expressed as: 0.05(1-t ) = 0.07; rearranged from .07 (1-t ) = .05 A bond has a market price that exceeds its face value. What features currently apply to this bond? Premium price; YTM that is less than the coupon rate....premium bond, par value < bond price, YTM < cpn rate Which form of business structure is most associated with agency problems? Corporation Your grandmother has promised to give you $5,000 when you graduate from college. She is expecting you to graduate two years from now. What happens to the present value of this gift if you delay your graduation by one year and graduate three years from now? The present value decreases You are comparing two annuities which offer quarterly payments of $2,500 for five years and pay 0.75 percent interest per month. Annuity A will pay you on the first of each month while annuity B will pa you on the last day of each month. What statement is correct concerning these two annuities? Annuity B has a smaller present value than annuity A. Perpetuity unending equal payments paid at equal time intervals This morning, TL Trucking invested $80,000 to help fund a company expansion project planned for 4 years from now. How much additional money will the firm have 4 years from now if it can earn 5 percent rather than 4 percent on its savings? -80000 PV, N=4, I=4.....-80000 PV, N=4, I=5. "5" --> 97,240.50 vs "4"-->93,588.68. Thus, earning 5 percent instead of 4 leads to $3,651.82 more. What risk premium compensates for the possibility of nonpayment by the bond issuer? Default risk What best describes the "January effect" as we discussed it in class? The return in January allegedly predicts the return for the entire year. You want to have $1 million in your saving account when you retire. You plan on investing a single lump sum today to fund this goal. You are planning on investing in an account which will pay 7.5 percent annual interest. What will reduce the amount that you must deposit today if you are to have your desired $1 million on the day you retire? Invest in a different account paying a higher rate of interest; retire later What will help convince managers to work in the best interest of the stockholders? Compensation based on the value of the stock; stock option plans; threat of a company takeover; threat of prison Most loans are a form of a(n) annuity What is true with regard to CEO/Chairman duality as we discussed in class? When the CEO of the firm is also the chairman of the board; the new CEO of GM will also serve as the role Chairman of the Board; is usually found in low-growth, easily tractable businesses that the board would be able to understand easily The weighted average cost of capital for a firm is dependent upon the firm's: level of systematic risk, debt-equity ratio, and tax rate Incremental cash flow any and all changes in the firm's future cash flows that are a direct consequence of taking the project The internal rate of return (IRR) rule states that a project is acceptable when the IRR... exceeds the required rate of return The internal rate of return (IRR) is the rate that causes the net present value of a project to equal... zero A project's operating cash flow will increase when: depreciation expense increases The capital structure weights used in computing the weighted average cost of capital are based on: the market value of the firm's debt and equity securities The capital structure weights used in computing the weighted average cost of capital are based on the ______ value of the firm's debt and equity securities market Decreasing the required rate of return will ________ the net present value of a project. increase When calculating a firm's equity beta in practice, what should be considered? The estimation period over which you run the regression; the benchmark "market" index which you run your regression against. You are aware that your neighbor trades stocks based on confidential info he overhears at his workplace. This info is not available to the general public. This neighbor continually brags to you about the profits he earns on these trades. Given this, you tend to argue that the financial markets are, at best, ________ form efficient. semistrong In class, we spoke about a lawyer that buys variable annuities in the names of terminally ill patients. What is consistent with our discussion? The death benefit of the annuities provides a risk-free investment option. Advertisement Upgrade to remove ads
https://quizlet.com/2211241/fin445-flash-cards/
CC-MAIN-2017-47
en
refinedweb
test case Last edit: Anonymous 2014-03-23 $ i686-w64-mingw32-gcc --version i686-w64-mingw32-gcc (GCC) 4.7.0 20120224 (Fedora MinGW 4.7.0-0.5.20120224.fc16_cross) I am attaching test case that you can easily see the problem. $ gcc -m32 test-ps.c $ ./a.out size: 12 $ gcc -fpack-struct -m32 test-ps.c size: 6 $ i686-w64-mingw32-gcc test-ps.c $ wine ./a-1.exe size: 12 $ i686-w64-mingw32-gcc -fpack-struct test-ps.c $ wine ./a.exe size: 9 The gcc 4.7 gcc for mingw has by default -mms-bitfields activated. Which means struct-layout has changed and alignment in struct. You can force a specific layout by using attribute ms_struct or by attribute gcc_struct. The difference between those two layouts is in bitfield packing and in alignment of those field members. For example: struct { unsigned long long c : 1; unsigned int a : 1; unsigned int b : 1; } will be layout differently. For gcc-layout all bits geting merged together within one bitfield. gcc struct makes no difference in actual type-sizes for bitfields. For ms-layout c will end in a 8-byte field, and just a and b getting merged together as they have same type-size. This is to be expected behavior. You might want to try here -mno-ms-bitfields. Ah, I missed that default-alignment is treated now for ms_struct union/struct-s too. You can solve the issue also by additing explicit #pragma pack(1) of __attribute__ ((pack(1))). The cause why it gets aligned to 9 is that. Default alignment of fields is 4 on 32-bit. So first char a[1]; is placed in 4-bytes, long b also, and the last element has 4 too. By enabling struct-pack, All fields in structure getting merged. So char a[1]; has one byte size, long b has 4 byte size, plus char c[1] has 1. But by structure-alignment of 4, structure gets expanded in the last field to 4. I see that here alignment is one too big ... hmm, maybe an issue indeed. Work-a-round use explicit #pragma pack(1), if you don't want structure alignment at end. Adding -mno-ms-bitfields does fix the issue that I am having. I was expecting 6 and not 8 (or 9). I did not know about the defaults change. Should I report the 9 issue upstream (gcc)? I was too quick to say it is fixed. There seem to be other byte alignment issues. I will continue investigating. The general issue is that the __attribute__ ((__packed)) applies only to last field of struct. This is the cause for the size of 9. Trick is here '#pragma pack(1)'. By it you get expected sizes. The issue is that this field-alignment gets applied even for struct/union's marked to be packed (or via -fpack-struct option). The remark of "__attribute__ ((__packed)) applies only to last field of struct" is curious: I never experienced that before in any gcc versions, and if that is a gcc-4.7 thing it is a devastatingly incompatible change. For the record, I just compiled Michael's testcase with gcc45 for win32 and it prints 6 when ran under wine. Same when compiled for x86-linux. Is your remark accurate Kai? My last comment was a false alarm. Adding "-mno-ms-bitfields" solves all my issues. I use software that heavily relies on bitfields and packed structs (yes, it is very old). I agree with sezero, even if I am an outside nobody. This is a drastic change in defaults. Perhaps this "bug" needs to be changed to an "enhancement" to change the defaults back to pre-4.7 values to prevent further problems with other projects. I run into this as well and I don't think the change is correct. I get now _different_ results from compiling with Microsoft Compiler and packing when using -m-ms-bitfields while I get _identical_ results when compiling with -mno-ms-bitfields. And when __attribute__ ((__packed)) applies only to last field of struct then m[no]-ms-bitfields shouldn't really make a difference in my case: #include <cstdio> #if defined(_MSC_VER) #pragma pack( push, packing ) #pragma pack( 1 ) #endif struct Header { unsigned char IdLength; unsigned char ColorMapType; unsigned char ImageType; unsigned char FirstEntryIndex[2]; unsigned short ColorMapLength; unsigned char ColorMapEntrySize; unsigned char XOrigin[2]; unsigned char YOrigin[2]; unsigned short ImageWidth; } #if defined(__GNUC__) __attribute__((packed)) #endif ; #if defined(_MSC_VER) #pragma pack( pop, packing ) #endif int main () { printf("sizeof(Header): %d\n", sizeof(Header)); return 0; } But my results for size are: With VS 2010 (32 bit as well as 64-bit): 14 Compiled with gcc 4.7 and -mno-ms-bitfields: 14 gcc 4.7 and new default (or with -mms-bitfields explicitly): 16 So gcc 4.7 is now incompatible with MS compiler as well as with gcc 4.6 as far as I can see. Log in to post a comment.
https://sourceforge.net/p/mingw-w64/bugs/275/
CC-MAIN-2017-47
en
refinedweb
Selenium: Design Patterns Selenium: Design Patterns Join the DZone community and get the full member experience.Join For Free Selenium WebDriver is widely used as a first-choice framework when it comes to testing web applications. In this article I would like to introduce you: public class LoginPage { private static By userEmailLoginInput = By.id("email"); private static By userPasswordLoginInput = By.id("pass"); private static By loginSubmitBtn = By.id("u_0_n"); private WebDriver driver; public LoginPage(WebDriver driver) { this.driver = driver; driver.get(""); } public LoginPage enterUserLogin(String login) { WebElement emailBox = driver.findElement(userEmailLoginInput); emailBox.click(); emailBox.sendKeys(login); return this; } public LoginPage enterUserPassword(String password) { WebElement passwordBox = driver.findElement(userPasswordLoginInput); passwordBox.click(); passwordBox.sendKeys(password); return this; } public HomePage submitLoginCredentials() { WebElement submitBtn = driver.findElement(loginSubmitBtn); submitBtn.click(); return new HomePage(driver); } }: public class HomePage { private WebDriver driver; public HomePage(WebDriver driver) { this.driver = driver; } public boolean checkIfLoginSucceed() { return driver.getPageSource().contains("fbxWelcomeBoxName"); } } …and test looks as follows: @Test public void shouldNotLoginWithIncorrectCreds() { LoginPage loginPage = new LoginPage(driver); loginPage.enterUserLogin("[email protected]"); loginPage.enterUserPassword("wrongPassword"); HomePage homePage = loginPage.submitLoginCredentials(); assert (!homePage.checkIfLoginSucceed()); }: public class LoginPage { @FindBy(id = "email") private WebElement userEmailLoginInput; @FindBy(id = "pass") private WebElement userPasswordLoginInput; @FindBy(id = "u_0_n") private WebElement loginSubmitBtn; private WebDriver driver; public LoginPage(WebDriver driver) { this.driver = driver; driver.get(""); PageFactory.initElements(driver, this); } public LoginPage enterUserLogin(String login) { userEmailLoginInput.click(); userEmailLoginInput.sendKeys(login); return this; } public LoginPage enterUserPassword(String password) { userPasswordLoginInput.click(); userPasswordLoginInput.sendKeys(password); return this; } public HomePage submitLoginCredentials() { loginSubmitBtn.click(); return new HomePage(driver); } }! Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/selenium-design-patterns
CC-MAIN-2018-43
en
refinedweb
public class LineNumberReader extends BufferedReader A buffered character-input stream that keeps track of line numbers. This class defines methods public LineNumberReader(Reader in) Create a new line-numbering reader, using the default input-buffer size. in- A Reader object to provide the underlying stream public LineNumberReader(Reader in, int sz) Create a new line-numbering reader, reading characters into a buffer of the given size. in- A Reader object to provide the underlying stream sz- An int specifying the size of the buffer public void setLineNumber(int lineNumber) Set the current line number. lineNumber- An int specifying the line number getLineNumber() public int getLineNumber() Get the current line number. setLineNumber(int) public int read() throws IOException Read a single character. Line terminators are compressed into single newline ('\n') characters. Whenever a line terminator is read the current line number is incremented. readin class BufferedReader IOException- If an I/O error occurs public int read(char[] cbuf, int off, int len) throws IOException Read characters into a portion of an array. Whenever a line terminator is read the current line number is incremented. readin class BufferedReader cbuf- Destination buffer off- Offset at which to start storing characters len- Maximum number of characters to read IOException- If an I/O error occurs public String readLine() throws IOException Read a line of text. Whenever a line terminator is read the current line number is incremented. readLinein class BufferedReader nullif the end of the stream has been reached IOException- If an I/O error occurs Files.readAllLines(java.nio.file.Path, java.nio.charset.Charset) public long skip(long n) throws IOException Skip characters. skipin class BufferedReader n- The number of characters to skip IOException- If an I/O error occurs IllegalArgumentException- If nis negative public void mark(int readAheadLimit) throws IOException Mark the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point, and will also reset the line number appropriately. the stream to the most recent mark. resetin class BufferedReader IOException- If the stream has not been marked, or if the mark has been invalid.
http://docs.w3cub.com/openjdk~8/java/io/linenumberreader/
CC-MAIN-2018-43
en
refinedweb
Stars Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 54168 Accepted: 23299 Description Astronomers often examine star maps where stars are represented by points on a plane and each star has Cartesian coordinates. Let the level of a star be an amount of the stars that are not higher and not to the right of the given star. Astronomers want to know the distribution of the levels of the stars. For example, look at the map shown on the figure above. Level of the star number 5 is equal to 3 (it’s formed by three stars with a numbers 1, 2 and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map there are only one star of the level 0, two stars of the level 1, one star of the level 2, and one star of the level 3. You are to write a program that will count the amounts of the stars of each level on a given map. Input The first line of the input file contains a number of stars N (1<=N<=15000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0<=X,Y<=32000). There can be only one star at one point of the plane. Stars are listed in ascending order of Y coordinate. Stars with equal Y coordinates are listed in ascending order of X coordinate. Output The output should contain N lines, one number per line. The first line contains amount of stars of the level 0, the second does amount of stars of the level 1 and so on, the last line contains amount of stars of the level N-1. Sample Input 5 1 1 5 1 7 1 3 3 5 5 Sample Output 1 2 1 1 0 代码: #include <algorithm> #include <iostream> #include <stdlib.h> #include <string.h> #include <iomanip> #include <stdio.h> #include <string> #include <queue> #include <cmath> #include <stack> #include <map> #include <set> #define eps 1e-7 #define M 10001000 #define LL __int64 //#define LL long long #define INF 0x3f3f3f3f #define PI 3.1415926535898 const int maxn = 50000; using namespace std; int c[maxn]; int vis[maxn]; int lowbit(int x) { return x&(-x); } void add(int x) { while(x < maxn) { c[x]++; x += lowbit(x); } } int sum(int x) { int cnt = 0; while(x > 0) { cnt += c[x]; x -= lowbit(x); } return cnt; } int main() { int n; while(~scanf("%d",&n)) { int x, y; memset(vis, 0 , sizeof(vis)); for(int i = 0; i < n; i++) { scanf("%d %d",&x, &y); x++; y++; vis[sum(x)]++; add(x); } for(int i = 0; i < n; i++) cout<<vis[i]<<endl; } return 0; }
https://blog.csdn.net/qq_42825221/article/details/81592015
CC-MAIN-2018-43
en
refinedweb
libchrome: Uprev the library to r456626 from Chromium Pulled the latest and greatest version of libchrome from Chromium. The merge was done against r456626 which corresponds to git commit 08266b3fca707804065a2cfd60331722ade41969 of Mar 14, 2017 Notable changes are: - base::Bind now supports lambdas but prohibits capture. - FOR_EACH_OBSERVER macro removed (replaced by use of C++ 11 range-base for loop) - LazyInstance instance default initializer has been removed. Code must specify leaky or not behavior. - base::Values no more FundamentalValue - stl_util moved to base namespace - path() accessor renamed to GetPath() in ScopedTempDir (and other classes) - introduction of base::CallbackOnce Note that crypto/ has not been updated, has it now uses boring_ssl which cannot coexist with regular openssl. Test: All unit-tests should still pass. Change-Id: I5c2cb41ea4c037fe69fbb425e711b1399d55d591 Reviewed-on: Commit-Ready: Jay Civelli <[email protected]> Tested-by: Jay Civelli <[email protected]> Reviewed-by: Dan Erat <[email protected]>
https://chromium.googlesource.com/aosp/platform/external/libchrome/+/c3f34a3eed92e804017c0eaf9a9c69fd2f39d2ec
CC-MAIN-2018-43
en
refinedweb
IntroductionIn this post we will see how to fix the exceptions like this which hapens even after adding proper dll(s). Here in this post we will see how to fix exception, "The type or namespace name Data does not exist in the namespace Microsoft.Practices.EnterpriseLibrary (are you missing an assembly reference?)" BackgroundI was working on a project when I encountered one exception which was The type or namespace name 'Data' does not exist in the namespace 'Microsoft.Practices.EnterpriseLibrary' (are you missing an assembly reference?) I added the proper dll reference but still I was getting this compilation error. I was wondering what is going wrong. I tried to browse the class inside this dll using object browser. I was able to find classes inside this dll. I tried to create an object of the class which was inside the dll; I was able to create the object while I was writing the code. When i build it, it again failed. 1. Added Proper dll reference but compilation fails. 2. Exception the type or namespace name 'Data' does not exist in the namespace even after adding proper dll references. Using the code How did I fix this exceptionFinally when I check the project configuration, I was running .Net Framework 4.0 Client Profile. I made it to .Net Framework 4.0 and everything worked perfectly. The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 which is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile. If you are targeting the .NET Framework 4 Client Profile, you cannot reference an assembly that is not in the .NET Framework 4 Client Profile. Instead you must target the .NET Framework 4. This is what happening in my case. :) To change the Target Framework, Go to your project in the solution and right click on the project and select properties. In the window that comes up, select the Application tab. There you can see the Target Framework section. Select the .Net Framework 4 instead of .Net Framework Client Profile. :) Had the same problem, solved the same way :-D TY Thanks, Its solved my problem
http://gonetdotnet.blogspot.com/2015/06/solved-type-or-namespace-name-data-does.html
CC-MAIN-2018-43
en
refinedweb
This chapter focuses on the publish-and-subscribe (pub/sub) messaging model that was introduced in Chapter 2. The pub/sub messaging model allows a message producer (also called a publisher) to broadcast a message to one or more consumers (called subscribers). There are three important aspects of the pub/sub model: Messages are pushed to consumers, which means that consumers are delivered messages without having to request them. Messages are exchanged through a virtual channel called a topic. A topic is a destination where producers can publish, and subscribers can consume, messages. Messages delivered to a topic are automatically pushed to all qualified consumers. As in enterprise messaging in general, there is no coupling of the producers to the consumers. Subscribers and publishers can be added dynamically at runtime, which allows the system to grow or shrink in complexity over time. Every client that subscribes to a topic receives its own copy of messages published to that topic. A single message produced by one publisher may be copied and distributed to hundreds, or even thousands of subscribers. In Chapter 2 you learned the basics of the pub/sub model by developing a simple chat client. In this chapter we will build on those lessons and examine more advanced features of this model, including guaranteed messaging, topic-based addressing, durable subscriptions, request-reply, and temporary topics. In this chapter we abandon the simple chat example for a more complex and real-world Business-to-Business (B2B) scenario. In our new example, a wholesaler wants to distribute price information to retailers, and the retailers want to respond by generating orders. We'll implement this scenario using the publish-and-subscribe model: the wholesaler will publish messages containing new prices and hot deals, and the retailers will respond by creating their own messages to order stock. This scenario is typical of many Business-to-Business operations. We call the clients retailers and wholesalers, but these names are really only for convenience. There's little difference between our wholesaler/retailer scenario and a stock broker broadcasting stock prices to investors, or a manufacturer broadcasting bid requests to multiple suppliers. The fact that we use a retailer and a wholesaler to illustrate our example is much less important than the way we apply JMS. Our simple trading system is implemented by two classes, both of which are JMS clients: Wholesaler and Retailer . In the interest of keeping the code simple, we won't implement a fancy user interface; our application has a rudimentary command-line user interface. Before looking at the code, let's look at how the application works. As with the Chat application, the Wholesaler class includes a main( ) method so it can be run as a standalone Java application. It's executed from the command line as follows: java chap4.B2B.Wholesaler localhost username password username and password are the authentication information for the client. The Retailer class can be executed in the same manner: java chap4.B2B.Retailer localhost username password Start your JMS server, then run one instance of a Wholesaler client and a Retailer client in separate command windows. In the Wholesaler client you are prompted to enter an item description, an old price, and a new price. Enter the following as shown: Bowling Shoes, 100.00, 55.00 Upon hitting the Enter key, you should see the Retailer application display information on the screen indicating that it has received a price change notice. You should then see the Wholesaler indicating that it has received a "buy" order from the Retailer. Here's the complete interaction with the Wholesaler and the Retailer:[1] java chap4.B2B.Wholesaler localhost WHOLESALER passwd1Enter: Item, Old Price, New Price e.g., Bowling Shoes, 100.00, 55.00 Bowling Shoes, 100.00, 55.00Order received - 1000 Bowling Shoes from DurableRetailer ----------------------- java chap4.B2B.Retailer localhost RETAILER passwd2Retailer application started. Received Hot Buy: Bowling Shoes, 100.00, 55.00 Buying 1000 Bowling Shoes Here's what happened. The Wholesaler publishes a price quotation on a topic, "Hot Deals," which is intended for one or more Retailers. The Retailers subscribe to the "Hot Deals" topic in order to receive price quotes. The Retailer application has no interaction with a live user. Instead, it has an autoBuy( ) method that examines the old price and the new price. If the new price represents a reduction of greater than ten percent, the Retailer sends a message back to the Wholesaler on the "Buy Order" topic, telling it to purchase 1,000 items. In JMS terms, the Wholesaler is a producer of the "Hot Deals" topic and a consumer of the "Buy Order" topic. Conversely, the Retailer is a consumer of the "Hot Deals" topic and a producer of the "Buy Order" topic, as illustrated in Figure 4.1. The rest of this chapter examines the source code for the Wholesaler and Retailer classes, and covers several advanced subjects related to the pub/sub messaging model. After the listing, we will take a brief tour of the methods in this class, and discuss their responsibilities. We will go into detail about the implementation later in this chapter. Now, here is the complete definition of the Wholesaler class, which is responsible for publishing items to the "Hot Deals" topic and receiving "Buy Orders" on those deals from retailers: public class Wholesaler implements javax.jms.MessageListener{ private javax.jms.TopicConnection connect = null; private javax.jms.TopicSession pubSession = null; private javax.jms.TopicSession subSession = null; private javax.jms.TopicPublisher publisher = null; private javax.jms.TopicSubscriber subscriber = null; private javax.jms.Topic hotDealsTopic = null; private javax.jms.TemporaryTopic buyOrdersTopic = null; public Wholesaler); pubSession = connect.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); subSession = connect.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); hotDealsTopic = (Topic)jndi.lookup("Hot Deals"); publisher = pubSession.createPublisher(hotDealsTopic); buyOrdersTopic = subSession.createTemporaryTopic( ); subscriber = subSession.createSubscriber(buyOrdersTopic); subscriber.setMessageListener(this); connect.start( ); } catch (javax.jms.JMSException jmse){ jmse.printStackTrace( ); System.exit(1); } catch (javax.naming.NamingException jne){ jne.printStackTrace( ); System.exit(1); } } private void publishPriceQuotes(String dealDesc, String username, String itemDesc, float oldPrice, float newPrice){ try { javax.jms.StreamMessage message = pubSession.createStreamMessage( ); message.writeString(dealDesc); message.writeString(itemDesc); message.writeFloat(oldPrice); message.writeFloat(newPrice); message.setStringProperty("Username", username); message.setStringProperty("Itemdesc", itemDesc); message.setJMSReplyTo(buyOrdersTopic); publisher.publish( message, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, 1800000); } catch ( javax.jms.JMSException jmse ){ jmse.printStackTrace( ); } } public void onMessage( javax.jms.Message message){ try { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText( ); System.out.println("\nOrder received - "+text+ " from " + message.getJMSCorrelationID( )); } catch (java.lang.Exception rte){ rte.printStackTrace( ); } } public void exit( ){ try { Wholesaler broker username password"); return; } Wholesaler wholesaler = new Wholesaler(broker,username,password); try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader (new java.io.InputStreamReader( System.in ) ); System.out.println ("Enter: Item, Old Price, New Price"); System.out.println("\ne.g., Bowling Shoes, 100.00, 55.00"); while ( true ){ String dealDesc = stdin.readLine( ); if (dealDesc != null && dealDesc.length( ) > 0){ // Parse the deal description StringTokenizer tokenizer = new StringTokenizer(dealDesc,",") ; String itemDesc = tokenizer.nextToken( ); String temp = tokenizer.nextToken( ); float oldPrice = Float.valueOf(temp.trim()).floatValue( ); temp = tokenizer.nextToken( ); float newPrice = Float.valueOf(temp.trim()).floatValue( ); wholesaler.publishPriceQuotes(dealDesc,username, itemDesc,oldPrice,newPrice); } else { wholesaler.exit( ); } } } catch ( java.io.IOException ioe ){ ioe.printStackTrace( ); } } } The main( ) method creates an instance of the Wholesaler class, passing it the information it needs to set up its publishers and subscribers. In the Wholesaler class's constructor, JNDI is used to obtain the "Hot Deals" topic identifier, which is then used to create a publisher. Most of this should look familiar to you; it's similar in many ways to the Chat application, except for the creation of a temporary topic, which is discussed in more detail later in this section. Once the Wholesaler is instantiated, the main( ) method continues to monitor the command line for new "Hot Deals." When a "Hot Deal" is entered at the command prompt, the main( ) method parses the information and passes it to the Wholesaler instance via the publishPriceQuotes( ) method. The publishPriceQuotes( ) method is responsible for publishing messages containing information about price quotes to the "Hot Deals" topic. The onMessage( ) method receives messages from clients responding to deals published on the "Hot Deals" topic. The contents of these messages are simply printed to the command line. Here is the complete definition of the Retailer class, which subscribes to the "Hot Deals" topic and responds with "Buy Orders" on attractive deals: public class Retailer implements javax.jms.MessageListener{ private javax.jms.TopicConnection connect = null; private javax.jms.TopicSession session = null; private javax.jms.TopicPublisher publisher = null; private javax.jms.Topic hotDealsTopic = null; public Retailer(); connect.setClientID("DurableRetailer"); session = connect.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); hotDealsTopic = (Topic)jndi.lookup("Hot Deals"); javax.jms.TopicSubscriber subscriber = session.createDurableSubscriber(hotDealsTopic, "Hot Deals Subscription"); subscriber.setMessageListener(this); connect.start( ); } catch (javax.jms.JMSException jmse){ jmse.printStackTrace( ); System.exit(1); } catch (javax.naming.NamingException jne){ jne.printStackTrace( ); System.exit(1); } } public void onMessage(javax.jms.Message aMessage){ try { autoBuy(aMessage); } catch (java.lang.RuntimeException rte){ rte.printStackTrace( ); } } private void autoBuy (javax.jms.Message message){ int count = 1000; try { StreamMessage strmMsg = (StreamMessage)message; String dealDesc = strmMsg.readString( ); String itemDesc = strmMsg.readString( ); float oldPrice = strmMsg.readFloat( ); float newPrice = strmMsg.readFloat( ); System.out.println("Received Hot Buy :"+dealDesc); // If price reduction is greater than 10 percent, buy if (newPrice == 0 || oldPrice / newPrice > 1.1){ System.out.println("\nBuying " + count +" "+ itemDesc); TextMessage textMsg = session.createTextMessage( ); textMsg.setText(count + " " + itemDesc ); javax.jms.Topic buytopic = (javax.jms.Topic)message.getJMSReplyTo( ); publisher = session.createPublisher(buytopic); textMsg.setJMSCorrelationID("DurableRetailer"); publisher.publish( textMsg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, 1800000); } else { System.out.println ("\nBad Deal- Not buying."); } } catch (javax.jms.JMSException jmse){ jmse.printStackTrace( ); } } private void exit(String s){ try { if ( s != null && s.equalsIgnoreCase("unsubscribe")) { subscriber.close( ); session.unsubscribe("Hot Deals Subscription"); } Retailer broker username password"); return; } Retailer retailer = new Retailer(broker, username, password); try { System.out.println("\nRetailer application started.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader ( new java.io.InputStreamReader( System.in ) ); while ( true ){ String s = stdin.readLine( ); if ( s == null )retailer.exit(null); else if ( s.equalsIgnoreCase("unsubscribe") ) retailer.exit ( s ); } } catch ( java.io.IOException ioe ){ ioe.printStackTrace( ); } } } The main( ) method of Retailer is much like the main( ) method of Wholesaler. It creates an instance of the Retailer class and passes it the information it needs to set up its publishers and subscribers. The constructor of the Retailer class is also similar to that of the Wholesaler class, except that it creates a durable subscription using the "Hot Deals" topic. Durable subscriptions will be discussed in more detail later in this section. Once the Retailer is instantiated, the main( ) method uses the readLine( ) method as a way of blocking program execution in order to monitor for message input. The publishPriceQuotes( ) method is responsible for publishing messages containing information about price quotes to the "Hot Deals" topic. The onMessage( ) method receives messages from the Wholesaler client, then delegates its work to the autoBuy( ) method. The autoBuy( ) method examines the message, determines whether the price change is significant, and arbitrarily orders 1000 items. It orders the items by publishing a persistent message back to the Wholesaler client's temporary topic, using the JMSCorrelationID as a way of identifying itself. We will examine persistent publishing and temporary topics in the next section. [1] WHOLESALER and RETAILER are usernames you have set up when configuring your JMS server. passwd1 and passwd2 are the passwords you've assigned to those usernames. If you are using an evaluation version of a JMS provider, it may not be necessary to set up usernames and passwords; check your vendor's documentation for more information. No credit card required
https://www.oreilly.com/library/view/java-message-service/0596000685/ch04.html
CC-MAIN-2018-43
en
refinedweb
erupted 1.7.1 Auto-generated D bindings for Vulkan To use this package, put the following dependency into your project's dependencies section: This package provides sub packages which can be used individually: erupted:devices - Simple Vulkan example erupted:layers - Simple Vulkan example ErupteD Developement Information: Project ErupteD has been deprecated, it was upgraded with breaking changes into Project ErupteD-V2. If the old functionality is required use ErupteD-V1 instead. ErupteD-V1 represents the current state of ErupteD without deprecation information. Neither ErupteD nor ErupteD-V1 will be further developed, vulkan v1.0.69 is the last suported version. ErupteD-V2 comes with a new versioning system corresponding to Vulkan-Docs versioning. Eventually ErupteD will be destroyed and ErupteD-V2 renamed to ErupteD. Additional details can be found in ErupteD-V2 - Deprecation and Upgrade Process. Original Introduction: Automatically-generated D bindings for Vulkan based on D-Vulkan. Acquiring Vulkan functions is based on Intel API without Secrets Usage The bindings have several configurations. The easiest to use is the "with-derelict-loader" configuration. The DerelictUtil mechanism will be used to dynamically load vkGetInstanceProcAddr from vulkan-1.dll or libvulkan.so.1. Otherwise you need to load vkGetInstanceProcAddr with either platform specific means or through some mechanism like glfw3 as shown here. Additional configurations enable the usage of platform specific vulkan functionality (see Platform surface extensions). To use without configuration: - Import via import erupted;. - Get a pointer to the vkGetInstanceProcAddr, through platform-specific means (e.g. loading the Vulkan shared library manually, or glfwGetInstanceProcAddressif using GLFW3 >= v3.2 with DerelictGLFW3 >= v3.1.0). - Call loadGlobalLevel -. ) - Now three options are available to acquire a logical device and device resource related functions (functions with first param of VkDevice, VkQueueor VkCommandBuffer): - Call loadDeviceLevelFunctions(VkInstance);, the acquired functions call indirectly through the VkInstanceand will be internally dispatched by the implementation - Call loadDeviceLevelFunctions(VkDevice);, the acquired functions call directly the VkDeviceand related resources. This path is faster, skips one indirection, but (in theory, not tested yet!) is useful only in a single physical device environment. Calling the same function with another VkDeviceshould overwrite (this is the not tested theory) all the previously fetched __gshared function - Create a DispatchDevice with vulkan functions as members kind of namespaced, see DispatchDevice To use with the with-derelict-loader configuration, follow the above steps, but call EruptedDerelict.load() instead of performing steps two and three. Available configurations: with-derelict-loaderfetches derelictUtil, gets a pointer to vkGetInstanceProcAddrand loads few additional global functions (see above) dub-platform-xcb, dub-platform-xlib, dub-platform-waylandfetches corresponding dub packages xcb-d, xlib-d, wayland:client, see Platform surface extensions dub-platform-???-derelict-loadercombines the platforms above with the derelict loader The API is similar to the C Vulkan API, but with some differences:. Examples can be found in the examples directory, and run with dub run erupted:examplename DispatchDevice The DispatchDevice holds a VkDevice and the vulkan functions loaded from that device collision protected. Before usage the device must be initialize, either immediately: auto dd = DispatchDevice( device ); or delayed: DispatchDevice dd; dd.loadDeviceLevelFunctions( device ); The VkMember is private, it should never change as the functions can be used only with this device. It can be accessed with the getter vkDevice() e.g.: auto dd = DispatchDevice( device ); dd.vkDestroyDevice( dd.vkDevice, pAllocator ); The DispatchDevice has also convenience functions such that the device argument can be omitted. They forward to the corresponding vulkan function and the device argument is supplied by the private VkDevice member. The crux is that function pointers can't be overloaded with regular functions hence the vk prefix is ditched for the convenience variants: auto dd = DispatchDevice( device ); dd.DestroyDevice( pAllocator ); // instead of: dd.vkDestroyDevice( dd.vkDevice, surface extensions The usage of a third party library like glfw3 is highly recommended instead of vulkan platforms surfaces. Dlang has only one official platform binding in phobos which is for windows, found in module core.sys.windows.windows. Other bindings to XCB, XLIB and Wayland can be found in the dub registry and are supported experimentally. However, if you wish to create vulkan surface(s) yourself you have three choices: - The dub way, this is experimental, currently only three bindings are listed in the registry. Dub fetches them and adds them to erupted build dependency when you specify any of these sub configurations in your projects dub.json (add -derelict-loaderto the config name if you want to be able to laod vkGetInstanceProcAddrfrom derelict): XCBspecify "subConfigurations" : { "erupted" : "dub-platform-xcb" } XLIBspecify "subConfigurations" : { "erupted" : "dub-platform-xlib" } Waylandspecify "subConfigurations" : { "erupted" : "dub-platform-wayland" } - The symlink (or copy/move) way. If you like to play with bindings yourself this might be the way for you. Drawback is that you need to add the symlink into any erupted version you use and that your binding is not automatically tracked by dub. - Create a directory/module-path similar to those in erupted/types.d(I myself have these paths from the C header vk_platform.h) and symlink it under ErupeD/sourcesas sibling to ErupeD/sources/erupted. - You also need to specify the corresponding vulkan version in your projects dub.json versions block. E.g. to use XCByou need to specify "versions" : [ "VK_USE_PLATFORM_XCB_KHR" ]. - The source- and importPaths way. This is if you don't want to add stuff to the ErupteD project structure. Drawback here is that neither erupted nor the binding are automatically tracked by dub, you need to check yourself for any updates. In your project REMOVE the erupted dependency and add: "sourcePaths" : [ "path/to/ErupteD/source", "path/to/binding/source" ] "importPaths" : [ "path/to/ErupteD/source", "path/to/binding/source" ] Additional info: - there is no need for platform extensions if glfw3 (or similar technique) is used, as shown here. - for windows platform, in your project specify: "versions" : [ "VK_USE_PLATFORM_WIN32_KHR" ]. The phobos windows modules will be used in that case. - wayland-client.h cannot exist as module name. The maintainer of wayland:clientchoose wayland.clientas module name and the name is used in erupted/typesas well. - for android platform, I have not a single clue how this is supposed to work. If you are interested in android and have an idea how it should work feel free to open up an issue. Platform extensions First time non-surface platform (windows) specific extensions were released by NVidia in Vulkan-Docs-v1.0.25, VK_NV_external_memory_win32 and VK_NV_win32_keyed_mutex. To use these extensions specify "versions" : [ "VK_USE_PLATFORM_WIN32_KHR" ]) in your projects dub.json. This will also make VK_KHR_win32_surface available and vice versa, even if it is not required when using e.g. GLFW. A more flexible platform extension mechanism is WIP. Generating Bindings To erupt the vulkan-docs yourself (Requires Python 3 and lxml.etree) download the Vulkan-Docs repo and call erupt.py passing path/to/vulkan-docs as first argument and an output folder for the D files as second argument. Differences to D-Vulkan - Platform surface extensions - ErupteD follows API without Secrets in terms of function loading naming and stages (three stages contrary to d-vulkan two stages) Known Issues Dub error: Could not find a valid dependency tree configuration: Solution: Confirm that in YOUR projects dub.selections the xcb-d version is at least 2.1.0+1.11.1 or 2.1.0 Explanation: This is a dub issue with fetching dependencies, in particular with xcb-d and xlib-d. It happens on windows systems as well, even though these dependencies will never be used. Problem is that xlib-d depends on xcb-d ~>1.11.1 while erupted depends on the newer xcb-d ~>2.1.0+1.11.1. This should be O.K. as both xcb-d dependencies can coexist BUT dub.selections of YOUR project has only one entry for the xcb-d dependency. If these dependencies are fetched for the first time dub.selections is created in YOUR project and xcb-d version might have been set to version 1.11.1. - Registered by Peter Particle - 1.7.1 released 7 months ago - ParticlePeter/ErupteD - BSD 2-clause - Copyright 2015-2016 The Khronos Group Inc.; Copyright 2016 Alex Parrill Peter Particle - Authors: - - Sub packages: - erupted:devices, erupted:layers - Dependencies: - none - Versions: - Show all 64 versions - Download Stats: 3 downloads today 14 downloads this week 37 downloads this month 2750 downloads total - Score: - 2.1 - Short URL: - erupted.dub.pm
http://code.dlang.org/packages/erupted/1.7.1
CC-MAIN-2018-43
en
refinedweb
Today I'm working in Spyder just like any other day but when I try to import arcpy, I get this: import datetime import os import arcpy Traceback (most recent call last): File "<ipython-input-3-5467a3dc9fe3>", line 1, in <module>. I imported datetime & os just to see if they worked okay and they do; I get this error if I let the console window sit long enough. I'm curious what the connection is with arcpy, spyder, python and Portal/ArcGIS Online is and how I can avoid this in the future.... eta moments later.... Shut down spyder and reopened it: cured.... (?) Happened to me, once or twice... waiting and/or rebooting fixed the issue: You will have to follow the long and circuitous path in your installation path to arcpy C:\Your_path_to_arcgis_pro\Resources\ArcPy\arcpy which contains Bin, Resources and Support the __init__.py files starts the imports, which imports stuff... including _base.py amongst others. You can follow the trail which generally leads to a dead end (ie *.pyd files usually) and try to figure out why any connection would be needed. In short... you probably shouldn't know or want to know. I have explored some of this Import arcpy.... what happens to check namespace, load time and bloat issues when just importing arcpy
https://community.esri.com/thread/222141-arcpy-fails-to-import-in-spyder
CC-MAIN-2018-43
en
refinedweb
As of the September 2017 release of Qlik Nprinting we can now use the cycling feature, a gap feature from Nprinting 16, that has now been added to the product. You can read more about the feature here: Cycling your reports ‒ Qlik NPrinting . However, in this feature all the reports ends up in a .zip file, even though we apply a filter for a single user. Filters needs to be dynamic based on what the users can see elsewhere. Faced with this not-so-user-friendly we ended up with two questions How can we filter easily and friendly for a user? No users want a zip file. How can each user receive a report dynamically? So we came up with a solution for both of these. The solution includes a single Qlik Sense app which builds a logic on filters. The Qlik Sense app has 3 tables which is identical to how an import job would look like. Dynamically based on the data we used in other apps. So we use Nprinting to extract them out of QS to a xlsx file through a regular "Publishing task", and import them again through an "Importing task". As more and more filters add, we simply add them within the QS script - to have a single truth for all our reports. Step 1. Import Active Directory automatically to Nprinting The solution builds on the import of an .xls file, which can be handled manually, as explained here: Importing users with filters and groups ‒ Qlik NPrinting , and can be automated, as with my own solution, mentioned here: Import Nprinting Users from Active Directory automatically . Either way, the way columns are handled within the Excel file would likely be a similar requirement if there is an AD connection in a future release of the product. The trick here is to include every userfilter per user, all of them with a number. In the PowerShell script in the automated version, this is a very simple script suggesting 10 filters to start with, but allows us to connect a number (userfilter_001) to a specific filter. Step 2a. Structure user access hierarchy with Section Access (or similar) So in order to filter a particular region, product or country on a specific user, we need something to filter on. In our case we used Active Directory groups to slice data, with Section Access, e.g. SA_Region_Austria to filter out people who should look at Austria. All members only allowed to see Austria would then be a member of this group. In our case we actually use a more complex script, as we have several fields to limit data on. You can read more about this here: A Primer on Section Access Basics for complex authorization Data Reduction Using Multiple Fields We include the Section Access in our apps through a must_include statement, but also allows it to be disabled through a script. This allows us to read the SA tables but not apply them, using these very filters to filter out e.g. regions, products or countries. By using the very same script, we ensure we do not have different versions of the SA script. In the attached sample .qvf file userfilter_001 and userfilter_002 is using such SA groups. set vL_ImportOnly_SA = 1; $(must_include=[lib://Shared\SectionAccess.qvs] ); //0 = production mode, SA in place //1 = no SA //2 = SA on, but in this specific document we do not drop the authentication bridge if vL_ImportOnly_SA = '1' then set vL_ImportOnly_SA = 1; elseif vL_ImportOnly_SA = '2' then set vL_ImportOnly_SA = 2; else set vL_ImportOnly_SA = 0; end if; Step 2b. Row-level access instead of SA Assuming that e.g. Salespeople do not have access to the Qlik Sense environment, but should receive a report, we can connect their username to filtering out data instead. This assumes that on each row in the data model there is a connection to their username, and thus we can connect them. In the attached sample .qvf file userfilter_003 and userfilter_004 shows how this can be done. (Step 3. - Add a distribution list for a group of people to receive reports - Optional) As we control access largely through AD Groups, we decided to add all users that should receive a report in a specific group, called NP_Austria. By using this group we control in the AD, not in the script, who should receive a report. The members of the group will be added to a "virtual group" within the below QS script, as we apply filters, send it into Nprinting and similar. Of course, the group can be added directly in Nprinting as well. We can also manually hardcode within the QS script who should receive reports, by logic. Step 4. Produce filter tables for Nprinting within Qlik Sense. We use a Qlik Sense script to generate tables, practically identical to how an Excel import file would look. In the attached sample file "Generic Nprinting filters" you'll see 4 samples. - userfilter_001 - a group receiving reports about Austrian products, filtered on different categories. Within QS we use Section Access to filter out specific product categories, which we apply here too. - userfilter_002 - same as 001, but management - which usually includes a summary and no data constraints. Thus we apply no filter. No filter = all values. - userfilter_003 - Sales people in France, which has not access within QS, e.g. a license constraint. The users have AD accounts, and are members of a receiving AD group. - userfilter_004 - same as 003, but management - which usually includes a summary and no data constraints. Thus we apply no filter. No filter = all values. When we export users, filters and groups - we bundle together 001+002, 003+004. 001 and 002 are receiving different reports (standard vs summary), but same standard Nprinting filters apply (e.g. Region Europe) and they use the same Nprinting app and Nprinting connection. As you may notice, when selecting in the QS app whichfilter_filter = 001 and whichfilter_user = 001, we still see userfilter_002 under the sheet Users, and on the sheet Groups. It is missing from "Filters" as no filter = all values. The attached sample file can help you get started, which includes the above 4 examples. Modify the script accordingly to suit your needs. Suggestions is - when you are done - to publish it to a stream and reload it daily. Reload it daily _after_ you import the users from the xlsx file, to ensure that you have the newest information. You can also for instance import .qvd's from other Qlik Sense apps that filters out data, builds tables etc. Regarding Nprinting filters: Use one connection per report, even though they go to the same app. The reason for this is that otherwise the filters, applied on users can cause conflicts. The Products for report A will be applied to both report A and B, for user01. Yes, this means that on a general static filter, e.g. Country: Austria, it needs to be added several times, one for each app. Step 5. Filter report within Nprinting Go into the admin interface of your Nprinting server. First, you need to create a new Nprinting app. Apps > Create app. Name, e.g. "Nprinting filters" Then we need a connection Connections > Create connection Name, e.g. "Nprinting filter connection" Source: Qlik Sense Fill out the proxy address and the Sense app ID accordingly. Step 5a. Userfilter 001 and 002 For filters and reports, you may use the attached sample file - "Nprinting filters - create userfilter_001 report.zip". We also need filters. These filters will filter on which report we want to use from the QS app. Filters > Create filter Name: Nprinting filters - userfilter_001 Use the following filters: whichfilter_filters: userfilter_001 whichfilter_users: userfilter_001 VirtualGroup: 1 We also need to create a report: Reports: Create report Name: Nprinting filters - create userfilter_001 You may use the attached xlsx file as a template - filter_output_template.xlsx. It needs to look exactly like Nprintings import format, meaning one sheet for Filters, one for Users and one for Groups. Add the filter: Nprinting filters - userfilter_001 Before we can create the output job, we need to add a folder as a destination Destination > Folders > Create folder. Let's call the connection "Output Nprinting filters". Select "Custom path" and e.g. "D:\Shared\Import-filters_auto" We then need to create a "Publish task" Publish tasks > Create task Name: Nprinting filters - create userfilter_001 App: Nprinting filters Reports: Nprinting filters - create userfilter_001 Friendly name: userfilter_001 Output format: XLSX Add yourself (rootadmin) as User/Groups, but under Destinations only add the folder connection "Output Nprinting filters". Suggestion is to schedule this daily, _after_ the QS app. That's it! When the task is run, it will output a file on disk, which we will use in a later step. Step 5b. Userfilter 003 and 004 Repeat the above steps, you may use the same App but as it is a different report, using probably different filters, you may want to use a new connection. This means that you need to set up new filters, reports and tasks. Destination folder can be the same. Step 6. Import the filter tables though an Import job in Nprinting. Now that we have a file ready on disk with a bunch of users, we can import it. Most of these users already exist through an earlier import of the full AD, so this import job will: Create new filters on each user, e.g. - userfilter_001_USER, userfilter_002_USER etc - Create virtual groups, that we will use for distribution. These are called "USERFILTERGROUP_001", "USERFILTERGROUP_002" and so on. - Add these virtual groups on each user. You will notice this that under each user he/she will be part of the filters, and the virtual groups. Attached is a sample file showing what it could look like. Go to Tasks > Import filters and recipients task > Create import task Name: userfilter_001 Import file path: D:\Shared\Import-filters_auto\userfilter_001.xlsx You may check all the checkboxes in the configuration. We want this job to import accordingly. Please note that if a user is removed from a distribution group, he will disappear from Nprinting temporarily. As you might have schedule a full AD import every day, a day later he will return (or upon the next import). Schedule this daily, _after_ the output job is done. Step 7. Add the virtual user group to your reports. Now that we have set up filters on each user, and a virtual distribution group, we can add these to our regular Nprinting reports. Filters on each user, will be applied first. Each user will receive a sliced version of the report, with his or her products/regions. As they are a member of the virtual distribution group called USERFILTERGROUP_001, they will all get the report on their Newsstand/email inbox. Add this virtual group under the Publishing task > Task name > Users/groups. Filters added directly on a report, will be applied afterwards. If you are receiving warnings in the publishing task, it is due to a user-filter have filtered out some data, and the report-filters are filtering out "the rest" on a specific user. Thus there is nothing left to send to the user. You might want to reconsider how the report structure is set up. You may read more about filter order here: Static and dynamic filters ‒ Qlik NPrinting . Good luck! Changelog: v 1.0 - 2017-12-22 Initial version. Tested with Qlik Sense September 2017 and Nprinting September 2017.
https://community.qlik.com/docs/DOC-19424
CC-MAIN-2018-43
en
refinedweb
Hi @mythz, I am currently trying to deploy a netcore 2.1 app to Azure with ServiceStack Razor pages.v5.1.1 Everything works locally but when I publish to Azure, the default page loads ok but when I hit a page requiring a service dto response, I'm getting the metadata html view back instead of the view I expect. My config is basically the same as Is there anything you might know of that is causing the compiled views to not be found and return the native html response instead? [EDIT] Actually happening locally too using dotnet .\myapp.dll in the folder generated after running dotnet publish dotnet .\myapp.dll dotnet publish ServiceStack Razor in .NET Core uses MVC's APIs to access and render views so it's essentially all handled by MVC libraries and build tools. You should instead use for a reference impl. I don't see why this would affect Azure as they should be running the published .NET Core App, can you publish the App and run the published release build, e.g. $ dotnet publish -c Release Then run it with: $ cd bin\Release\netcoreapp2.1\publish $ dotnet MyApp.dll Use whatever your Host project name is. I've just done this for a new Razor project and it's running as expected. This has also been deployed to: Found the culprit. I was using an array response type [Authenticate, RequiredRole(Roles.Member)] [DefaultView("products")] public class ProductService : Service { public object Any(ProductsRequest request) { return new ProductsResponse { Products = new [] { new Product { .. } } }; } } [Route("/products")] public class ProductsRequest : IGet, IReturn<ProductsResponse> { } public class ProductsResponse { // was just returning Product[] with a view products.cshtml with same model type - Product[] specified // changed to use ProductsResponse type (and updated view vm) and it worked. // if I remove DefaultView attribute from service again it doesn't find view which I thought by convention it would public Product[] Products { get; set; } } public class Product { public int Id { get; set; } } hmm spoke too soon. Whilst the views now resolve running from a publish directory, they are still not resolving when published to Azure. Could this be something to do with a path (root/virtual)? Kinda stumped at the moment why it's happening! Sounds like a deployment issue, I've only known .NET Core App deployments to deploy the published .NET Core App. When creating a release build of your App your compiled views are in MyApp.Views.dll so there shouldn't be any path issues as they're resolved from compiled classes inside a .NET .dll so they should not be impacted by any static files or path issues. MyApp.Views.dll So finally got to the bottom of why the pages were not rendering. Solution below in case anyone else encounters this. I had the views in Views/Pages. When I moved them to the Views folder, they were picked up correctly on Azure. No idea why as this worked fine locally when testing and publishing. Views/Pages Views
https://forums.servicestack.net/t/razor-pages-on-azure/6182
CC-MAIN-2018-43
en
refinedweb
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <RTL.h> #include <rl_usb.h> BOOL usbh_hw_ep_add ( U8 dev_adr, U8 ep_spd, USB_ENDPOINT_DESCRIPTOR *ptr_epd ); The usbh_hw_ep_add function adds endpoint to the system. The argument dev_adr is the address of device to which endpoint will communicate. The argument ep_spd is the speed of device to which endpoint will communicate. The argument ptr_epd is a pointer to endpoint parameters. The usbh_hw_ep_add function is part of the RL-USB Host software stack. A handle to the added endpoint. usbh_hw_delay_ms, usbh_hw_ep_config, usbh_hw_ep_remove, usbh_hw_get_capabilities, usbh_hw_get_connect, usbh_hw_get_speed,.
https://www.keil.com/support/man/docs/rlarm/rlarm_usbh_hw_ep_add.htm
CC-MAIN-2020-34
en
refinedweb
In this tutorial we will learn how to tile an image so it repeats itself both vertically and horizontally the number of times we specify. We will do this using Python, OpenCV and numpy. Introduction In this tutorial we will learn how to tile an image so it repeats itself both vertically and horizontally the number of times we specify. We will do this using Python, OpenCV and numpy. This tutorial was tested on Windows 8.1, using Python version 3.7.2 and OpenCV version 4.1.2. Tiling a colored image As usual, we will start by importing the modules we need. We will need numpy and cv2. import numpy import cv2 After that we will read the image with the imread function from the cv2 module. This image will be returned as a ndarray, like we have seen in previous tutorials. img = cv2.imread('C:/Users/N/Desktop/Test.jpg') Once we have our image as a ndarray, we can use the tile function from the numpy module to do a tiling of our image horizontally and vertically. In short, the tile function allows to construct a new ndarray by repeating the original array across its axes [1]. The function allows us to specify the number of repetitions along each axis [1]. In our case, we have read an image in the BGR format, which means that it has 3 dimensions: the height, the width and the three color channels of the image. In our case, we want only the repetition to occur in the first and second axes (height and width) and that the third axis remains unchanged. Note that concatenating an image only vertically or horizontally is a particular case where there is no repetition over one of these axis. So, the tile function receives as first input the ndarray (our original image) and as second input a tuple where each element corresponds to the number of repetitions along that axis. Looking into more detail to this second parameter, we have the following tuple format: (nº of repetitions vertically, nº of repetitions horizontally, 1) Take in consideration that the value 1 means no repetition, just the original values across that axis. So, if we want the image to be repeated 2 times vertically and 3 times horizontally, we have the following tuple: (2,3,1) Putting all together with the tile function invocation, we have: tile = numpy.tile(img,(2,3,1)); Note: The tile function can be generically used to work with ndarrays, which means it is not an image processing dedicated function and it can be used outside of this scope. To finalize, we will display the tiled image in a window. cv2.imshow('Tile', tile) cv2.waitKey(0) cv2.destroyAllWindows() The final code can be seen below. import numpy import cv2 img = cv2.imread('C:/Users/N/Desktop/Test.jpg') tile = numpy.tile(img,(2,3,1)); cv2.imshow('Tile', tile) cv2.waitKey(0) cv2.destroyAllWindows() To test the code, simply run it in an environment of your choice. In my case I’m running it on IDLE, a Python IDE. Upon running the code, you should obtain a result similar to figure 1. As can be seen, the original image was tilled both vertically and horizontally, as expected. Just as a note, if you wanted to tile the image 3 times only horizontally or only vertically, you could use the following: tileHorizontally = numpy.tile(img,(1,3,1)) tileVertically = numpy.tile(img,(3,1,1)) Tilling a grey scale image As mentioned in the previous section, since we were working with a BGR image, then we had to specify the repetition over the three axis, even if there was no need to repeat anything in the third dimension. In case we are working with an image in grey scale, the the corresponding ndarray only has two dimensions. Consequently, when calling the tile function, the second argument (the repetitions tuple) should only have two entries: (nº of repetitions vertically, nº of repetitions horizontally) If mistakenly we add the third parameter with the value 1 to the tuple, then a new axis will be prepended to the resulting ndarray [1], which will give wrong results when we try to display it as an image. Below you can see the full code to do the tiling procedure to a gray scale image: import numpy import cv2 img = cv2.imread('C:/Users/N/Desktop/Test.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) tile = numpy.tile(gray,(2,2)) cv2.imshow('Tile', tile) cv2.waitKey(0) cv2.destroyAllWindows() If you run the previous code, you should get an output similar to figure 2. References [1]
https://techtutorialsx.com/2020/02/23/python-opencv-image-tiling/?shared=email&msg=fail
CC-MAIN-2020-34
en
refinedweb
anford University Press Stanford California 2005ON TOUCH I NG-J EAN-LUC NANCY Jacques Derrida Stanford University Press Stanford, California On Touching-jean-Luc Nancy was originally published in French in 2000 under the title Le toucher, jean-Luc Nancy © 2000, Editions Galilee. Derrida, Jacques. [Toucher, Jean-Luc Nancy. English] On touching-Jean-Luc Nancy I Jacques Derrida ; translated by Christine Irizarry. p. cm.-(Meridian, crossing aesthetics) Includes bibliographical references and index. ISBN 0-8047-4243-X (cloth: alk. paper ISBN 0-8047-4244-8 (pbk. : alk. paper) I. Nancy, Jean-Luc-Criticism and interpretation. 2. Touch. 3. Sense (Philosophy) I. T itle. II. Meridian (Stanford, Calif) B2430.N364D4713 2005 I94-dc22 2005008743 Original Printing 2005 Foreword IX Translator's Preface Xl § I Psyche II " "PART II: EXEMPLARY STORIES OF THE FLESH § 7 Tangent I 135 Hand ofMan, Hand of God § 8 Tangent II 159 ''For example, my hand''- "The hand itself''-''For example, thefinger''- ''For example, 'Jfeel my heart'" § 9 Tangent III The Exorbitant, 2 , "Crystallization ofthe impossible':' ''Flesh, " and, again, ''For example, my hand" § 10 Tangent IV 216 Tangency and Contingency, I: The "question oftechnics" and the "aporias" ofFlesh, "(contact, at bottom) " § II Tangent V 244 Tangency and Contingency, 2: "The 'mercifol hand ofthe , Father, with which he thus touches us, is the Son . . . . the Word that is 'the touch that touches the Soul' (toque de la Divinidad . . . el toque que toea al alma) " "PART III: PUNCTUATIONS: AND YOU. Salve 3 00 Untimely Postscript, for i%nt ofa Final Retouch XaipE Notes Index ofNames 375 Foreword The first version of this essay was written in 1992. Peggy Kamuf translated it into English, and her translation was published the following yearin Paragraph, which had dedicated a special issue to Jean-Luc Nancy at thetime. ! This international tribute clearly showed once again that the measure of an idea is often taken, first and last, "abroad," in "foreign" countries. What I wrote then stands as a modest, partial, and provisional introduction to Nancy's work. It was my intention to develop it or pursue itelsewhere when the right time came. I have certainly not given up on that;many new developments are the mark of this. But I must admit that Ihave had to follow the motifs, at least, of my first attempts, as far as thetopical heart of the matter is concerned. While the choice of the guiding thread, and especially of the original title-Ie toucher-seemed to impose itself, it never ceased to worry me. Inthe grammatical form of the French phrase and its indecision-betweenthe noun toucher and verb toucher, the definite article Ie and personal pronoun Ie-it is easy to recognize two indissociable gestures: if one analyzedthe way in which a great philosopher treated touch, how he handled thisprofound question of the sense that is apparently the most superficial, thequestion of the very surface itself, touching, was it not necessary also totouch him, and thus touch someone, address oneself to him singularly, touchsomeone in him, a stranger perhaps? Never to this degree have I felt howenigmatic, how troubling idioms are in their necessity, in expressions suchas "touch to the heart," "touch the heart," whether their value is properlyliteral or figurative, or sometimes both, beyond all decidability. However, by thus privileging one perspective, let us even say one sense, lXx Foreword Two days after Jacques Derrida died, while this book was in production,Jean-Luc Nancy published an article in the newspaper Liberation titled"Salut a toi, salut aux aveugles que nous devenons." I thank Jean-LucNancy for allowing it to be translated and published in this book. I thank Peggy Kamuf, Jean-Luc Nancy (again and again) , Helen Tartar,Norris Pope, Werner Hamacher, Avital Ronell, Kim Lewis Brown, AmyJamgochian, Angie Michaelis, Mariana Raykov, Marc Froment-Meurice,Kalliopi Nikolopoulou, Edward Batchelder, Lee Moore, Ludwig Reichhold, Brigitte Vanvincq (in memory) , Sophie Bissonnette, Stephan Reichhold, Mila Reichhold, Alice Irizarry Froment-Meurice Reichhold, EddyIrizarry, Gil Mendez, Pascal Massie, Beate Schuh, Ronald Bruzina, DieterLohmar, Alan Bostick, and David Dwiggins. Peter Dreyer deserves my extensive gratitude for his editorial work onthis translation. His superb editing skills have contributed very significantly to the final result. I thank the staffs of the Hong Kong Public Library, the San FranciscoPublic Library, the Nashville Public Library, and the Vanderbilt University libraries. By permission of the Edinburgh University Press and Peggy Kamuf, thistranslation incorporates Jacques Derrida, "Le toucher: Touch / To TouchHim," translated by Peggy Kamuf, in On the Work ofJean-Luc Nancy, editedby Peggy Kamuf, Paragraph 16, 2 (July 199 3) : 122-57. Copyright: EdinburghUniversity Press () Christine Irizarry XlON TOUCHING-)EAN-LUC NANCY "Wh en our e yes toue h . . . " One day, yes, one day, once upon a time, a terrific time, a time terrificallyaddressed, with as much violence as tact at its fingertips, a certain questiontook hold of me-as if it, or "she" [la question] , came of me, to me. To tell the truth, "she" didn't come to me-putting it that way is inaccurate. "She" didn't come to pay me a visit. In other words, "she" didn'talight to see me, as if I had invited "her. " No, as I said, "she" took hold ofme, "she" invaded me even before I had seen "her" coming: "she" touchedme before letting "herself" be seen. In this sense, yes, although there wasn'tany visit paid to me, it really was-before any invitation-a visitation. Agenuine test of hospitality: to receive the other's visitation just where therehas been no prior invitation, preceding "her," the one arriving. Now as soon as I have nicknamed "her"-"her," let's say, this questionI may lose the right to say "one day" ("One day . . . a certain question tookhold of me," or took me by surprise, or grabbed me) and thus to tell a story. For the question just nicknamed was precisely one about the day, an enquiry on the subject of the day-the question of the day, if you will. Byright, "she" thus came to light before the light of day. "She" saw the light of the day, one might say, a priori: "she" came theevening before. A younger, earlier riser than the day, "she" henceforth hasto keep watch over it-and therefore over the phenomenon. "She" remainsprephenomenological, "she" does, unless we can say that "she" is transphenomenal as well. And I would have even lost the right to say, sensu stricto, that "she"came to or from me-as if I assumed that a question come to me thuscame from me. This question could not happen to me except by being I2 "When our eyes touch. . . " -These eyes or these gazes? You're going from one to the other. Fortwo gazes, more than two eyes are often needed. And then there are eyesthat no longer see, and eyes that have never seen. Aren't you also forgetting those living without any eyes? All the same, they don't always livewithout any light. time? To the time of the earth? To time tallied by this turning around theearth known as the finite course of a sun? Is it a day? Is it night? Wouldone have to make it night, make the night appear in order to see oneselflooking at the other or see oneself beheld by the other? In order to see theother seeing us, that is, provided we'd no longer see the other's eyes' visibility, then, but only their clairvoyance? Is that what night is, our firstnight-in the first sense, the strong sense of the word "night"? The firstfor which we'd need a taste to hear it, before seeing or touching? -Let's repeat this question; however, let's displace it while taking noteof its straying deportment: ''At this instant, then, is it daytime? Is it night?" If one answered "night," wouldn't it then seem that the eyes blindlytouch, in the constancy of this contact and the consent of the interruptionholding them together? But "she"-the one I nicknamed the question-obj ected to me, or Imyself objected to myself: "Unless this is precisely how they begin to hearand understand each other. " -But precisely, when my gaze meets yours, I see both your gaze andyour eyes, love in fascination-and your eyes are not only seeing but alsovisible. And since they are visible (things or objects in the world) as muchas seeing (at the origin of the world), I could precisely touch them, withmy finger, lips or even eyes, lashes and lids, by approaching you-if I daredcome near to you in this way, if lone day dared. reconciliation with death, I mean to say my own, from the good fortunethus promised of no longer seeing those whom I have loved-like myself,more than myself-die. I barely dared sign such a question, not to mention its gloss (it comesdown to tact, tactility, the caress, the sublime, when what is most discreetborders on the most indecent, unless it touches it) , and for a moment Ithought of inventing a history or, in fact, since we have said goodbye tohistory, of pretending to invent a true story. This one: unlikely though it may seem, I thought I deciphered thisanonymous inscription on a wall in Paris, as if it had journeyed there fromthe shores of another language: "Quand nos yeux se touchent, fait-il jourou fait-il nuit?" ("When our eyes touch, is it day or is it night?") . It inspired me with the desire, pure and simple, to trot it out, to make it anepigraph to what I had long wanted to write for Jean-Luc Nancy, thegreatest thinker about touching of all time, I tell myself. unity of sense of the tangible; third, the unity of sense, between the two, ofwhat refers touch to the tangible; fourth, the credit that we philosophersmay here bring to common opinion, to doxa, with regard to this sensibleunity of a sense. Let's start over as clearly as possible, then, and quote the texts that leadonto the pathless path of these four obscure aporias: 3 . " [Since] that through which the different movements [causing thesensations for the senses other than touch-J. D.] are transmitted is notnaturally attached to our bodies, the difference of the various sense-organsis too plain to miss. But in the case of touch [epi de tes haphes] the obscurity [adelon] remains . . . . no living body could be constructed of air or water; it must be something solid . . . . That they are manifold is clear whenwe consider touching with the tongue [epi tes glottes haphe]" (ibid., 423 a) . does the perception of all objects of sense take place in the same way, ordoes it not, e.g., taste and touch requiring contact (as they are commonlythought to do [kathaper nun dokei] ) , while all other senses perceive over adistance? . . . we fancy [dokoumen] we can touch objects, nothing comingin between us and them" (ibid., 423 a-b) . first, the "organ" of touch is "inward" or internal; second, flesh is but the"medium" of touch; third, "touch has for its object both what is tangibleand what is intangible [tou haptou kai anaptou]" (ibid. , 424a) , one keepsasking oneself what "internal" signifies, as well as "medium" or "intermediary, " and above all what an "intangible" accessible to touch is-a stilltouchable un-touchable. How to touch upon the untouchable? Distributed among an indefinitenumber of forms and figures, this question is precisely the obsessionhaunting a thinking of touch-or thinking as the haunting of touch. Wecan only touch on a surface, which is to say the skin or thin peel of a limit(and the expressions "to touch at the limit," "to touch the limit" irresistibly come back as leitmotivs in many of Nancy's texts that we shallhave to interpret) . But by definition, limit, limit itself, seems deprived of abody. Limit is not to be touched and does not touch itself ; it does not letitself be touched, and steals away at a touch, which either never attains itor trespasses on it forever. Let's recall a few definitions, at least, without reconstituting the wholeapparatus of distinctions holding sway in Aristotle's Peri psuches. Let's first recall that sense, the faculty of sensation-the tactile faculty,for example-is only potential and not actual (ibid., 417a) , with the ineluctable consequence that of itself, it does not sense itself; it does notauto-affect itself without the motion of an exterior object. This is a farreaching thesis, and we shall keep taking its measure with regard to touching and "self-touching." Let's also recall that feeling or sensing in general, even before its tactilespecification, already lends itself to being taken in two senses, potentiallyand actually, and always to different degrees (ibid., 41 7 a) . Let's mostly recall that touch was already an exception in the definitionof sensible objects [especes du sensible] (each being "in itself" or "accidentally"; "proper" or "common"). Whereas each sense has its proper sensibleobject [idion] (color for vision, sound for the sense of hearing, flavor forthe sense of taste), "Touch, indeed, discriminates more than one set of different qualities": its object comprises several different qualities (ibid., 418a) .Let's b e content with this initial set of signposts by way o f an epigraph.Down to this day, these aporetic elements have not stopped spelling trouble, if one can put it like that, in the history of this endless aporia; this will be borne out at every step we take. For, with this history of touch, we grope along no longer knowing how "When our eyes touch . . . " 7 to set out or what to set forth, and above all no longer able to see throughany of it clearly. An epigraph out of breath from the word go, then, towhat I renounced trying to write, for a thousand reasons that will soonbecome apparent. For, to admit the inadmissible, I shall have to contentmyself with storytelling, admitting to failure and renunciation. Hypothesis: it's going to be a lengthy tale with mythological overtones-"One day, once upon a time . . . " Pruning, omitting, retelling, lengthening, with little stories, with a succession of touches touched up again,off on one tangent and then another, that's how I'm going to sketch therecollections of a short treatise dedicated to Jean-Luc Nancy that I havelong been dreaming of writing peri Peri psuches, which is to say, around, onthe periphery, and on the subject of Peri psuches-De anima-a murky,baroque essay, overloaded with telltale stories (wanting to spell trouble) ,an unimaginable scene that to a friend would resemble what has alwaysbeen my relation to incredible words like "soul," "mind," "spirit," "body,""sense," "world," and other similar things. How can one have spent one's life with words as defining, indispensable, heavy and light, yet inexact, as those? With words of which one hasto admit that one has never understood anything? And to admit this whiledischarging oneself of any true guilt in the matter? Is it my fault if thesewords have never made any sense, I mean to say any exact sense-assuredor reassuring for me-and have never had any reliable value, no morethan the drawings deep in a prehistoric cave of which it would be insaneto claim one knows what they mean without knowing who signed them,at some point, to whom they were dedicated, and so forth? The difference is that I have never been able or dared to touch on thesedrawings, even be it j ust to speak of them a little; whereas for the big badwords I have j ust named (spirit, mind, soul, body, sense, sense as meaning, the senses, the senses of the word "sense," the world, etc.),2 I dreamthat one day some statistics will reveal to me how often I made use ofthem publicly and failed to confess that I was not only unsure of theirexact meaning (and "being"! I was forgetting the name of being! Yet alongwith touch, it is everywhere a question of "being," of course, of beings, ofthe present, of its presence and its presentation, its self-presentation) , butwas fairly sure that this was the case with everybody-and increasinglywith those who read me or listen to me. Now, we never give in to j ust "anything whatever": rigor is de rigueur;and, to speak like Nancy, so is exactitude. "Exactitude" (we'll come to it)8 "When our eyes touch . . . " is his word and his thing. He has reinvented, reawoken, and resuscitatedthem. That in a way is perhaps my thesis. It is thus necessary to explainand that may be this book's sole ambition-how Nancy understands theword "exact" and what he intends by it. I believe this to be rather newlike a resurrection. "Exact" is the probity of his signature. PA R T I II12 This Is- o/the Other August 22, 19 3 8, one year before his death. Nancy thus tirelessly quotesthe last sentence of a sick man's penultimate note, which almost looks likethat of a dying man. Later on we shall read it in extenso. Freud's very lastnote, the one that follows, comprising fewer than two lines, was writtenon the same day. It terms "mystic," or perhaps it defines in this way anything "mystical," the obscure self-perception of the realm outside the ego,the id, unless it is, as the Standard Edition translates it, the realm outsidethe I and the id: "Mysticism is the obscure self-perception of the realmoutside the ego, of the id" (Mystik die dunkle Selbstwahrnehmung desReiches ausserhalb des Ichs, des Es) . ') Would these aphorisms interest us as much as they do if they were notelliptical, and more than ever testamentary, as aphorisms almost alwaysappear to be? And above all, if like the Psyche of whom they speak andwhose extension they couch in words, they did not also keep silence, intheir very words, on a bed? On the extension of a deathbed? On an extension extended [une etendue etendue] on its deathbed? In the three cases, in Nancy's three texts, it all begins with what is extended, and more precisely with Psyche's being extended. Psyche is extended, stretched out (ausgedehnt, etendue) . In her essence, she is someextension [de l'etendue] (extensio) . She is made extended, made of extension. She is the extension/extended-noun and attribute. To express in hislanguage something that would probably make Descartes spin in his grave,extension is the essence, the substance or essential attribute, of the soulthat answers to the proper name Psyche. Let us quote in extenso the first occurrence, the p rinceps-the first edition, as it were-in Premiere livraison. Psyche "Psyche ist ausgedehnt, weiss nichts davon," reads a late [posthume] note of Freud's. The psyche is extended, knows nothing about it. Everything thus ends with this brief tune: Psyche ist ausgedehnt, weiss nichts davon. Psyche [Psyche] is extended, partes extra partes; she is nothing but a disper sion of indefinitely parceled-out locations in places that divide themselves and never interpenetrate. No fitting inside anything, no overlap; everything is out side another outside-anyone can calculate their order and report on their re lations. Only Psyche knows nothing of this; for her, there are no relations be tween these places, these locations, these pieces of a plane. Psyche is extended in the shade of a walnut tree, as the daylight fades. She Psyche 13 lies at rest; the slight movements of sleep have half exposed her bosom. Flus tered and mischievous, all at once, Eros contemplates her. Psyche knows noth ing of this. Her sleep is so deep that it has even robbed her of any abandon in her pose. Psyche is extended in her coffin. Soon it is going to be shut. Among those present, some are hiding their faces, others are keeping their eyes desperately fixed on Psyche's body. She knows nothing of this-and that is what everyone knows around her, with such exact and cruel knowledge.6 knows nothing of this: "The psyche is extended, knows nothing about it.Everything thus ends with this brief tune: ' Psyche ist ausgedehnt, weissnichts davon.' . . . Only Psyche knows nothing of this . . . . Psyche knowsnothing of this . . . . She knows nothing of this-and that is what every-one knows around her, with such exact and cruel knowledge. " I f Psyche remains alone, i t is first because she is alone i n knowing nothing of this. There again the meaning of the sentence bursts. Into bits, Imean. Psyche is the only one who knows nothing (nothing of herself, ofher extension, of her recumbent being-extended); but further, by beingalone in knowing nothing of this, she is also alone for not knowing anything of this. She finds herself alone without knowing it; her solitude isradical because she knows nothing, nothing of herself, of her extension, ofthat which others know; she doesn't know what they know and that theyknow, that is, the content and the fact of their knowledge. On the subjectofherself. Indeed, she is the submissive subject (extended object) , the support or subjectile of their knowledge but not of hers because on her ownshe knows nothing of herself-on the subject of herself. In other words, those around her, peripheral to her, who are not touching her while gazing at her all the same-they know something about her.They know it and their knowledge is exact (one of Nancy's master words,which we'll come back to frequently: exactitude is this thinker's thing, hisbig deal-he thinks exactly something other than what one thinks in general or ponders too easily under the word "exactitude," and yet . . . ). Theyknow this with exact and cruel knowledge. "Exact" is not the last word,just one of the last. What do they know? Is this "they" masculine or neuter? Is Psyche only a feminine figure surrounded by men, and first exposedto Eros? Perhaps "they," "those present" know the very selfsame thing thatshe doesn't know, but know above all that she doesn't know, the very factthat everything taking place is unknown to her: indeed, everything is taking place, that is to say, extends, "in places that divide themselves," "between these places, these locations . . . . " And thus "they" know that shedoesn't know about herself that very thing which is to be known withouther knowing it, namely, that she is extended. They know her unconscious,her being-unconscious, Psyche's unconscious. They see her not seeing herself, that is to say, not seeing herself extended; they know her where sheneither knows herself nor knows herself to be seen. But the vision of this extended body becomes almost intolerable to them.She-she has no self-relation: she doesn't see, hear, taste, or touch herself;16 This Is-o/the Other in a word, she doesn't feel herself. She lacks the sense of herself, whichamounts to saying that the sense is what she lacks. And no doubt sense. Andthe insensate (as much as insensible) support of this subjectile that knowsnothing and sees nothing of itself becomes almost insupportable to them. Can we imagine an extension that is untouchable? Imagining is neitherthinking nor knowing, to be sure, but it is in no way a complete absence ofthought or knowledge . Can one figure for oneself an untouchable extension,if you will? It is difficult, except (as Descartes, Kant, and a few others wouldhave it) if an intelligible extension without a body is at issue, precisely therewhere the understanding passes imagination and sensibility; and exceptfor some insensible sensible (Hegel, Marx, and so on) . But inversely, is anytouching imaginable that might touch something not extended? And further, to announce questions that will come back to us like boomerangs,what is the way to organize together the following four concepts or philosophemes: extension, partes extra partes, to touch, and to touch oneself?Soon enough, in a combinatory play closing up around a vacant center,their association and dissociation will compel us into a dizzying ambulation.If commonsensically I can only touch some extended thing (what is termed"body" and "material body") , it does not follow that every extension istouchable (as I said a moment ago about intelligible extension) ; nor thatany extension is structured following the intrinsic exteriority, which is essential, ofpartes extra partes. Certainly, the living body, for example, comprises some partes extra partes, but it also has a relation to itself that is oftenthought no longer to be divisible in this way. Should I touch a living body,should a living body touch itself, then there is no assurance that extensionis transcended-but there is even less assurance that the touching or selftouching touches in the way of partes extra partes. Soon, blows or caresseswill force us to leave suspended any hasty conclusion on the subject at hand. Among those present, some are hiding their faces, others are keeping their eyes desperately fixed on Psyche's body. Psyche the untouchable, Psyche the intact: wholly corporeal, she has abody, she is a body, but an intangible one . Yet she is not only untouchablefor others. She doesn't touch herself, since she is wholly extended partes extra partes. Those who are "present" to her refuse to see her or behold herdesperately, and if their "knowledge" is so "exact and cruel," then it's notonly because they know that she knows, sees, or touches nothing, noteven her own body or anything properly her own. It's because this scene Psyche 17 appears while a song of mourning resounds. Twice the "brief tune" resonates in German, for Psyche's name is written in German, without an accent, and moreover this is a "late [posthume] note of Freud's": "Psyche istausgedehnt, weiss nichts davon." This is about a passage, it is after Psyche'sdeath, and the scene rather looks like an entombment. Psyche is extended in her coffin. It remains that she, Psyche, is the subject. She remains the subject inasmuch as it is rest ("rests, " "lies"-reposing, lying, resting itself)J As forr8 This Is-o/the Other them, they are holding on, standing by her subject, not by her bedside [ason chevet] , as we might say, but at the edge of her being-extended, of hercot, or her coffi n . Knowing but one thing about her, which is that sheknows nothing of it, they watch her and seek, j ust as we do, to give thoughtto the subject of the subject, and think about and around psyche (peripsuches), and think about "touching" and what it means to say. But touching is what they are not doing, since they are thinking; and they are thinking-that is their postulate-that in order to think touching, this thinkingabout touch must not touch. They are also asking themselves what this(that is, touching) might see in seeing and have to do with it, a seeing thatsome accept resolutely whereas others are "hiding their faces. " They areasking themselves what touching might have to do with seeing and theother senses. But they already know that this thinking of touch, this thought of what"touching" means, must touch on the untouchable. Aristotle's Peri psucheshad already insisted on this: both the tangible and the intangible are theobjects of touch (he haphe tou haptou kai anaptou) (Peri psuches 424a) .Once this incredible "truth" has been uttered, it will resonate down to thetwentieth century, even within discourses apparently utterly foreign to anyAristotelianism, as we shall see . How can this be? To ponder touching while touching on, or tamperingwith, the untouchable-would this be the absolute injunction? Doesn'tthis inj unction dictate the impossible? Does it pertain to a posthumoushistory of Psyche or Peri psuches? And does posthumous here signify thatAristotle's legacy, no matter how undeniable, is really dead? Or does itmean that it is time to inherit it differently? What could this history oftouch have to do with inheritance? In any case , it was time to start with a tableau of mourning, not mourning for someone, male or female, some determined living being, some singularity or other, but mourning life itself, and what in life is the very livingthing, the living spring, the breath of life . Psyche is also a common propername, designating the principle of life, breath, the soul, the animation ofthe animal. That is why everything begins and must begin there. And it isindeed there that Peri psuches-so often translated in our tradition in Latinas De anima-begins. This treatise begins by explaining to us, at the very outset, what one is to begin with. For, if knowledge is among the mostbeautiful and most dignified things, if knowing one thing is worth morethan knowing another by reason of its accuracy or by reason of the ad- Psyche 19 mirable quality of its objects, then knowledge of the soul must properly beentitled to the highest rank-this can be read at the beginning of Peripsuches. Knowledge of the soul greatly serves the knowledge of all truth.First, it serves the knowledge of nature because the soul is the principleproper to living beings (esti gar hoion arche ton zoion) (Peri psuches 402a) .Aristotle thus proposes to study, on the one hand, the traits "proper" to thesoul, the ones that define the essence or the substance (ousia) of the psyche,and on the other hand, those traits pertaining to entire living beings. Thisbeginning of Peri psuches assumes that the soul (psuche)-at least the soulof the living being named man-can have self-knowledge. When one thencomes to the part of the soul that "thinks" and "knows," one will deal withthe intellect that is separable and is "able to think itself" in its eternity orimmortality (ibid., 429b) . Certainly, Aristotle's psyche, like Nancy's, is impassive (apathes), insensitive, and indifferent to suffering, within its noeticand active principle, there where it thinks, thinks itself, and knows. But itis also separable, and when it is severed-which is also the moment ofdeath, but here a death that doesn't happen-it re-becomes "immortal andeternal" (ibid., 43 0a) . It is appropriate, at this point, to recall what is evident: Aristotle's Peripsuches is a treatise on the pure life of the living. Now, Nancy's Psyche sees herself treated as a dead woman. This will have some consequences, both close and distant ones, forpsycho-logy, psycho-analysis-that goes without saying-but also for anumber of "modern" languages and our current discourses on the "livingbody" (Leib) , whether the ear grasps it as "body proper" or the "flesh. " Theprinciple or drive to expropriation introduced there forthwith by death, theother or time, is certainly hard to tolerate, bur, as we shall see, it's less resistant to thought than what complicates an incarnation even more, whichis to say, the prosthesis, the metonymic substitute, the autoimmune process, and technical survival. The techne of bodies, ecotechnics, and the intrusion of L'intrus are, forexample, among the names that Nancy bestows on these. 8 § 2 Spacings May I, even before starting out again, be permitted the space and thefreedom of a long parenthesis here to announce, at some remove, a possible destination? It is justified precisely by the attention accorded to space,or rather to spacing, the absolute condition of any extension and any partesextra partes, as well as the condition of this strange Psyche. A further justification for the parenthesis is the link between the spacing motif and anunusual thinking offreedom. One of Nancy's rare references to Aristotle is an even rarer one to Peripsuches, in which he reminds us, without alluding to touch himself, that''Aristotle's psuche-a substance [in the sense of form] of a living bodywas united with the body like 'wax and the shape given to it. "' ! And it isalso in these last pages of his Ego sum that Nancy first revisits (so to speak)his own reference to Freud's note.2 Indeed, this point is quite significant, and accordingly, no doubt, we shallhave to give sustained attention to it later on. Naturally, although the word"touch" does not appear there, the stakes of his demonstration do touch onwhat "touching" may mean. It deals with a subtle but firm distinction between orality and buccality, between os and bucca, the latter being more"primitive" than the former. The mouth speaks but it does so among otherthings. It can also breathe, eat, spit. It has "not always been speaking," notalways been an oral agency: "the instant speaking begins, an unstable andmobile opening forms. For a few instants, nothing is discernible; ego willnot say anything. All that ego does is open up this cavity" (Nancy, "Unumquid," p. 162) . The mouth that can scream, the closed mouth at the breast,thus opens up before the "oral stage." The mouth attaches itself to the 20 Spacings 21 gift as such is kept [garde] , that is, offered . . . . The offering is the inestimable price of the gift. The generosity of being offers nothing other than existence, 22 This Is-ofthe Other and the offering, as such, is kept [gardte] in freedom. All this means: a space is offered whose spacing, each time, only takes place by way of a decision. But there is no "the" Decision. There is, each time, my own (a singular mine) yours [fa tienne] , his or hers, ours. And this is the generosity of being. (Nancy, Experience ofFreedom, pp. 146-47; slightly modified-Trans.)? I have emphasized the four occurrences of the verb garder [keep, guard, keep guard, ward off-Trans.] that are essential in my eyes. They point at the same time toward truth's verity [veritas) Wahrheit] , which is a guard, as I the word indicates, and to economy. Must a gift be kept? In truth? Must'I one keep or guard, as the text says? And is this keeping compatible with the "withdrawal," "retreat," "holding back," and "retaining," which are also in question? Questions. And yet, when I reread this fundamental chapter, "Decision, Desert, Offering," followed by "Fragments," with admiration (some will say, an other Cartesian word!) ; when I follow through, step by step, with grateful recognition at every instant, I wonder. Doesn't my timid, reticent concern about the word "generosity" (it is the word I worry about and not neces sarily the concept at work in it) pertain to the very reserve that the conge nial motif and the good movement of "fraternity" always inspire in me? I mean to say fraternity in the greatest tradition, certainly, and all its res torations, but still, in spite of the differences, in Levinas, Blanchot, and others.s In this conclusion of The Experience ofFreedom, incidentally, the reference to fraternity is as insistent as it is cautious and awkward. While Nancy is very conscious of what may appear to be "ridiculous" or suspect in the French republican motto, and of what makes one "smile" in the word "fraternity, " he nevertheless makes the suggestion that "thought" should be given to fraternity in another way, to "fraternity in abandon ment, of abandonment" (Nancy, Experience of Freedom, p. I68) . Briefly, what embarrasses me in the word "generosity," as in the word "fraternity," finally amounts to the same thing. In both cases, one acknowledges and nods to some genealogy, some filiation, a principle having to do with "birth," whether or not it is "natural," as it is often thought to be. Above all, the word privileges some "virility. " Even if he is an orphan, a brother is a son and therefore a man. In order to include the sister or woman or daughter, one has to change words-generously-and then change the word "generosity" itself while one is at it. Indeed, if one gives or offers be cause one is naturally, genially, congenitally, or ontologically generous, at Spacings 23 birth; if it's because one has to give or has something to give, because onecan give, thanks to a power, a force, or a capacity related to giving, to having what it takes to give, with sovereign power; once giving is possible, orthere is a "generosity of being"; then does one offer, does one still give?Here, like the gift, like spacing, "freedom" or "decision" perhaps presupposes the interruption of generosity as well as fraternity. To give, out ofgenerosity or because one can give (what one has) is no longer to give. Giving is possible only where it remains im-possible, and not even im-possibleas such.9 It here comes down to the impossibility of the "as such," to thefate of phenomenology as much as ontology. Besides the insistence on keeping guard, a suspension of the constativeutterance as the enunciation of a thesis gives way to an address in the familiar form [tutoiement] ("yours [la tienne] , his or hers [fa sienne] , ours,"and so on) at the heart of Nancy's demonstration will have been noted.The indicative mood of the thesis is suspended, not abandoned; the address is embedded in the analysis. But in the allocution, there is a certainchallenge, which will have some importance for us later on. This movement does not proceed rhetorically. It often carries with it (and already recalls, with a change of scenes) an essential displacement in the gesture ofthe thinking. To bring this point home, it helps (though it does not suffice) to underscore to what degree philosophical discourse has excluded(one might even say prohibited) this strophic turn of the apostrophe, aswell as "thou" and "you," from Aristotle to Kant, from Descartes to Hegeland to Heidegger. Even today, this prohibition extends to many others.Exceptions-if any-are rare; we would learn much from their inventory. "The free" [das Freie] is the motif (the "semantic root") that Heideggerkeeps until the end, whereas he has left by the wayside the theme, at least,of the essence of freedom. This leaves a gap, into which Nancy proceedswith his original meditation on a freedom that is no longer a subject's orsomeone's freedom (he says daringly: "In this sense, the stone is free"[Nancy, Experience ofFreedom, p. 1 59 ] ) . In many places, but more particularly in the chapter titled "The Space Left Free by Heidegger" (ibid. , pp.39 ££), Nancy directly or indirectly questions the paradox of this "free space"that Heidegger maintains as a motif after he has let go of the motif of"freedom." Is it the space, or the place, in which it would be appropriateto engage thought? End of this long parenthesis. This Is-o/the Other While Peri psuches is thus a treatise on the pure life of the living, it recurrently accords to touch a status that sets it apart. Touch may well existapart from the other senses, but Aristotle stresses that without it, no othersense would exist. As has been noted, all animals possess this sense, whichis also the sense of nutrition. Why is it that, unlike ten years later, Nancy does not seem to have beenpreoccupied with touch-at least not as a theme and by this name-at thetime when he wrote Psyche (1978) and Ego sum (1979), or even in briefly alluding specifically to the problem of life in Aristotle's Peri psuches? The major question, at the end of Ego sum as well as in Psyche, seems tocome together under the heading of one noun, namely, extension, and it isan incredible extension, that of the soul or thought. Underscoring whatis paradoxical and unique, that is, incommensurable, in such an extension is at issue then. It seems that one can only touch an extended bodyor some part of it, but not every extension is necessarily touchable. Thereis an intelligible or pure, sensible extension, a nonempirical extension. Psyche's extension-that is, that of Psyche the character in Psyche-hasno measure in common with anything, and above all not with any otherextension. And yet, as the term indicates and demands, must "Psyche" notshare at least some trait with what one commonly terms "extension," withthe everyday sense of extension? The conceptual passage, if one may say so,in this argumentation between the extension of the body (which is easy forcommon sense to apprehend, which is an essential attribute of the corporeal substance for Descartes and the eidetic component of any materialthing and any transcendent and tangible res for Husserl) and the extensionof the psyche or thinking (which is a paradoxical extension resisting intuition, perception, and consciousness) is what exceeds any measure in themboth-and therefore exceeds common measure. That is their common incommensurability. This incommensurability-as incommensurability ofextension, as incommensurability between two ways of being extended,two spaces or two spacings-goes through a thinking of place [lieu] , as aplace or locus that is reduced neither to objective extension nor to objective space. This place must be spacing before it is space; it must open anopening, as it were, an interval, which is to say an apparently incorporeal,though not intelligible, extension-thus neither sensible nor intelligible. The mouth would here be this place, this unique place: cavity, gapingplace, chasm, abyss, opening (these words are part of Nancy's lexicon inthese pages); hole [trou] ' orifice (these additional words that do not appear, Spacings 25 it seems, at least not here, might point toward other resources) . As a uniqueplace, even before one distinguishes between bucca and os, the mouth wouldthus be the common place of the incommensurables in question, that is,body and soul (spirit or mind or thought) , and so forth. "The incommensurable extension of thinking is the opening of the mouth" (Nancy, "Unumquid," p. 161) . 1 0 Let u s not forget the final demonstration that orients Ego sum ( a workthat can be read both as a new meditation on fiction, fictitiousness, or fictionality at work within the cogito [i.e., of Descartes] I I and as an experience, an experiment, and an abyssal "provocation" of what is called themouth) : without the mouth, one cannot conceive of the union of the souland the body-of the "comme un seul tout" in the due de Luynes's translation (that is, "seemingly a single whole," "a quasi-single whole," or [in theHaldane and Ross translation] "seem [ing] to compose with it one whole") ,o f the "conjunctum e t quasi permixtum," o r o f the "quasi permixtio. " 1 2Nancy will make this the obsessive motif of his book-in truth, of the veryego sum itself-while to the "quasi," to the fable of this quasi-fiction, hewill accord a decisive authority or a daunting pertinence. Since I am playing at tracking down all the tropological uses of touch, allthe times Nancy resorts to it-this tactile metaphor or metonymy, whichsome may find hackneyed and weakly invested-it may be appropriatehere to point out that, just as he lends all the requisite attention to the duede Luynes's translation of the famous passage in Descartes's Sixth Meditation, notably when it transfers-and effaces-the quasi from "quasi permixtum" to "unum quid," yielding "comme un seul tout," 1 3 here Nancyquasi-touches, if I can put it that way, the figure or trope (metaphor ormetonymy) of touch as if with a distracted, barely grazing hand: As for the Latin text, it says: I am quasi-intermixed with my body, so that along with it, I make up a certain unity-something like a "unum quid." The dis placement [of quasi] does not touch on anything important, and it is in depen dence on quasi that the Latin unum quid is thought, if not [grammatically] con structed. Indeed, Descartes wrote this unum quid, and we shall, so to speak, keep our eyes fixed on it. (Nancy, "Unum quid," p. 133) the metaphor of sight may not be more strictly appropriate here than themetaphor of touch, yet it is only with respect to the "eyes fixed" thatNancy considers that he can decently make a concession: " . . . we shall, soto speak, keep our eyes fixed on it. " We are not through with this question, which is to say, with knowingwhether the "quasi" of the "quasi permixtio" of the soul and the body isseen, or whether it is rather touched or lets itself be touched. As a closegame will play itself out between these orifices, that is, the mouth and theeyes, these quasi-placeless places, these bordered openings, these girdledspacings, that's one of the reasons why we began with the scene of the kisson the mouth-or on the eyes, between single eyes only, making eyes, eyeto eye, eye on eye. self conditions the "sense of the world"-and with the thinking of "excess"that "inexorably" pushes outwardly, until it is throwing or jettisoning (ejecting, dejecting, objecting, abjecting) the ego's subjectivity into exteriority. 1 4The outline of this discourse adjoins certain propositions by Paul Valery, in"Bouche" [Mouth] , 1 5 as well as Heidegger's thinking on Geworfenheit, onan "opening in and through which 1 is indeed properly thrown " (Nancy,"Unum quid," pp. 162-63 ) . Here Nancy underscores the trait, or more exactly the traced outline or tracings, of this exteriorization of exteriority. Already, the movement in ex- is scored as a sort of writing, and the conceptof the ex-scribed in rehearsal, although it will only appear under this namelater on, to unsettle every phenomenology of touch: The subject gives way in this abyssal chasm. But ego utters itself in it: ego ex teriorizes itself there, which does not signify that it carries to the outside the visible face of an invisible interior. This literally signifies that ego makes or makes itself exteriority, spacing of places, distancing and strangeness that make up place, and thus space itself, first spatiality of the tracings of a veritable out line in which-as in no other-ego may come forth, trace itself out, and think itself. (Nancy, "Unum quid," p. 163) come to Freud only because he was thinking against the Cartesian subject. But this thought also "came" to Descartes, and in Descartes as in Freud, it inex orably tips over, falling outside, exceeding any psychoana(ysis. (Nancy, "Unum quid," p. 161) 1 6 Henceforth there are two questions, two beats in time at least, for thesame question. First, how do two incommensurabilities-of psychical thinking and ofthe body-unite in an extension that is itself incommensurable? At thisstage of the question, Nancy's answer is original yet clear and developed,and even insistent. It is contained in a single word (itself obscure and gaping) : mouth-embouchure of the mouth, originary spacing of a mouthopening (itself) between the lips and at the other's breasts. It may be necessary here to distinguish between extension and spacing. But secondly, as the question is generated a second time (that is, whatabout touch in all this? How does this double extension touch or self-touch?Is it opened by being touched /touching itself?), its answer still appears elliptical, virtual, and prethematic in Ego sum. That's my hypothesis, and Iwould like to support it with a few quotations. First again, therefore: the mouth's answer to the first question is heldbetween a nonspeaking mouth (bucca, without the orality of os) and amouth that starts detaching itself from the breast and is ajar even beforethe "oral stage." Beating time, the opening of the mouth responds to thelips moving-the other's lips, the mother's lips at birth, then mine, if Imay say so-always nearest to birth into the world, and from a mother, anoun and name Nancy never pronounces. Isn't birth into the world thefirst ex-pulsion? The word "mother" does not appear, despite Nancy's obvious, explicit reference to her (at the time of birth and nursing) , despitehis reference to the edges of the orifice, to the lips parting and opening thepassage for the newborn (the labia between the mother's legs as well as theinfant's lips in their first cry) , despite his reference to the breasts partingthe nursling's mouth. (Note the earlier reference to a silent photograph ofthe stretched-out, extended mother [in "When Our Eyes Touch," n. 2] .) Why? If it is the mother, in any case, who opens the bordering edges aswell as the lips of a mouth first described as an opening, then this happensbefore any figure-not before any identification, but before any "identification with a face," as a later remark specifies. It is the opening that incommensurabilizes-there where it [raJ spacesitself out. The mouth is at the same time place and nonplace, it is the locus Spacings 29 I don't believe that the said opening o/self ("opens [itself] and distends[itself] ") signifies autonomy or auto-affection. The nonplace-noncase ofthis place is also opened by the other. All at once auto-affected and heteroaffected, uniting both affections like two lips, it lets itself be openedhence "thought without measure," hence the incommensurable, hence thatwhich seemingly comes to pass, here, between Aristotle and Descartes.Nancy goes on, making his only reference to Aristotle's Peri psuches: The psuche of the ancients was localized-whichever its bodily organ might be. Aristotle's psuche-a substance [in the sense of form] of a living body was united with the body like "wax and the shape given to it." The Cartesian soul (whose detailed study would furthermore show several traits carried over from those traditions) , as the soul of the one whose being it is to utter, takes up this place-nonplace-noncase of the mouth opening and closing upon "ego sum," then opening and closing a second time at once, repeating, not re peating, "ego existo. " This double beat utters the subject; it utters itself as subject. But a mouth is neither a substance nor a figure. Bucca-a later, more triv ial term-is not os. (Nancy, "Unum quid," pp. 161-62) Here Nancy works on several figures, among several figures of the figure,which is to say of a kind of fictionality and a kind of facticity of fingere.Four figures of the figure, at least, belong to this semantic configuration:30 This Is- o/the Other Figure as the form of extension: Nancy has just said: "figure (that is, 1.extension, measure) and figurelessness (that is, thought without measure) "; 3 . Figure as trope; These figures are inscribed within one another, as when the face becomes a metonymy for the mouth, for example: "But a mouth is neithera substance nor a figure. Bucca-a later, more trivial term-is not os. Os,oris, the mouth of orality, is the face itself taken as metonymy for thismouth it surrounds, carries, and makes visible, the place through whichall kinds of substances pass, and first of all the airy substance of discourse"(ibid., p. 162) . Similarly, the self-relation of a mouth that "opens (itself) " or "spaces itself out" draws the figure of the mouth before any figure as visage (orality)and before any identification with a (maternal) face: The Freudian child (I won't say the subject) is not initiated in an "oral stage." First of all he or she opens into a mouth, the open mouth of a scream, but also the closed mouth at the breast, with which it is attached in an identification more ancient than any identification with a face-as well as the mouth slightly open, detaching itself from the breast, in a first smile, a first funny face, the fu ture of which is thinking. The mouth is the opening of ego; ego is the opening of the mouth. And there, what comes to pass is that it spaces itself out [ce qui sy passe c'est qu'il sy espaceJ . (ibid. , p. 162) Secondly. Nowhere in the analysis that we have just followed (in the lastpages of Ego sum and the reference to Freud's "The psyche is extended,knows nothing about it") , do we encounter any allusion to touch, at leastunder this name, since all that the mouth does before orality, all that isabundantly evoked here (eating, sucking, spitting, and so forth) is hardlyforeign to tactility. But the word "touching" is not mentioned and "selftouching" even less. It further seems to me that this is the case throughoutthis book, from beginning to end, despite its preoccupation with theproblem of sentir, "feeling," "sensing," and not j ust in the Cartesian sense Spacings 31 of the word (see, e.g. , ibid. , p. 1 3 6 ) . This is a decisive point, since Nancydaringly (isn't it risky?) inscribes Descartes's sentir and his "properly speaking it is what is in me called feeling" under the heading of fiction: . . . et [sic] certe videre videor-''properly speaking it is what is in me called feel ing": 17 proof that this feeling mostproper, most properly speaking (evidence itself, as opposed to any syllogism), resting on feint or consisting entirely of it, also im plies nothing but the fiction that lets it be established. More especially, it thus implies nothing as to the real nature of the subject of this feeling; it thus implies neither the "spirituality" nor the "corporeality" of this subject. (ibid., p. 136.) So it may be. But, from Descartes's point of view, can one say the sameof this "feeling oneself feel" [se sentir sentir] , the target here, no doubt, ofthe "properly" and the "most proper," which I felt I had to emphasize?Isn't this the place where it all plays itself out? Isn't it in this place of reappropriation that the simple, phenomenological dimension of "sensing," of"feeling that one feels," of "feeling oneself feel," spiritualizes or decorporealizes experience? It follows that-at least for Descartes-pure feeling,"feeling oneself feel," would indeed be spiritual and not at all corporeal.Mutatis mutandis, this would be the same for the analogous moment inHusserl's phenomenology. And Nancy is thus not naming touch here. And yet-can it be insignificant that once in this book (only once, if I am not mistaken) , as ifdistractedly or rhetorically, he seems to let escape a "touches itself" thatlooks like one of those dead or hackneyed metaphors whose appearance Ihave vowed, in a way, never to neglect here? It all leads one to think thatNancy-here at least-does not attribute any decisive thematic or problematic importance to this. The expression appears only once; Nancy neither underscores nor analyzes it; he neither interrogates nor relaunches itin any way. And yet-is it fortuitous that this "touches itself" should appear here regarding the "mouth," whose "place," spacing, locus withoutlocus, place without place, we have j ust considered? Is it fortuitous thatthe subject of this "touches itself" is precisely the very subject itself, 1, buta faceless 1, even a bodyless 1, except for what is mouthlike in it? Before we ask ourselves what happens then, let me quote an excerpt, atleast, from these pages and their ample, tight webbing, which one shouldreconstitute each time (once and for all, let us here recall this duty, whichis as imperative as it is unworkable) . Around a certain "I" that "touches itself" (or himself or herself) or "is touched" [Je se touche . . ] , here is a . 32 This Is-ofthe Other "faceless mouth," but also the words: "But that is still saying too much," which, with the next stroke [trait] , seem ready to retract each word-re tracting it either by effacing it or in order to neutralize its literality by dint of tropes. And here again, it is the predicate open/closed that is decisive overall (the "mouth" thus becomes that which, by opening, has "the look or the shape of a mouth") : Unum quid, a something that is neither-soul-nor-body, opens its mouth and pronounces or conceives "ego sum." But that is still saying too much. Unum quid has no mouth that it could manipulate and open, any more than an in telligence that it could exercise to reflect upon itself. Yet something-unum quid-opens (it thus has the look or the shape of a mouth) and this opening is articulated (it thus has the look of a discourse, hence of thought) , and this articulated opening forms l, in an extreme contraction. At one blow, it forms itself as I in a convulsion; it experiences I; it thinks it self I. I touches itself, is touched; it fixes itself, going-saying-I [faisant disant-je) . (ibid. , p. 157) Before carrying on with the reading of this passage and seeing the mo ment of auto-affection, the tactile figure of pure auto-affection, the "1 self touches," come forth, one must take note of three things at least: where: "The question o f the joint makes up the last question i n Descartes:it concerns the soul and the body adjoining" (ibid., p. 131) . Then, in thisself-commotion resembling a (diastolic/systolic) heartbeat as much as asyncope, a rhythmical violence concentrates. It is a gathering in an interruption, the cut that opens and shuts the mouth. Three years earlier, in1976, Nancy had published Ie discours de fa syncope: I. Iogodaedafus. 18 Unless one mobilizes this entire earlier work, one might find it somewhat difficult, it seems to me, to read what Nancy says here about the convulsivecontracture of the mouth that touches itself when it "forms itself as I " The syncopated convulsion, this contraction o f the inside and the outside, is also this (still and spoken [tu et ditJ) discourse, a difference at theheart of the 1, the articulation that can be disarticulated of an ego, an egocapable of touching it to the heart in touching its heart. Isn't the heartmemory? Isn't it thinking of memory? Thinking as memory? We shall safeguard the recollection, the cardiogram of this cardio-Iogy from one end ofthis book to the other-as it also writes itself or is written on the heartand on the hand, if not with a wholehearted hand or a freehanded heart-especially when we lend an ear to a certain heart sensation in Husser! 'his Herzgefohl, in the haptological moment of Ideas 1121 In the meantime,here is a first diaphragm: . . . and this articulated opening forms 1, in an extreme contraction. At one blow, it forms itself as 1 in a convulsion; it experiences 1; it thinks it self 1. 1 touches itself, is touched; it fixes itself, going-saying-l [faisant disant-jeJ . Imagine a faceless mouth (which is to say the structure of a mask once again: open holes, and the mouth opening in the middle of the eye; locus of vision and theory, diaphragmatically traversed-open and shut simultane ously-by a proffered utterance) a faceless mouth, then, mouthing the ring of ' its contracture around the noise "I." "You" [tuJ experience this daily, each time you are pronouncing or conceiving ego in your mind, each time (and this hap pens to you daily) you are forming the 0 of the first person (indeed the first: there is nothing before it) : "ego cogito existo. " An 0 forms the immediate loop of your experience. Truly, it is of that which it is and that it undergoes the ex perience it makes-that it makes or forms because it cannot be it. (ibid. , p. 157) This difference between making or forming, on the one hand, and being,on the other; the excess offashioning over essence, with one making up forthe other; one coming in lieu of the lack or impossibility of the other; allthat, no doubt, is the law offiction, at the origin offeeling oneself as touching oneself: there where it is not, one will have had to make, to fashion, tofeature, to figure. Where the taking-place of the event doesn't find its place-a gaping locus, indeed, a mouth-except in replacement; where it doesn'tfind room except in replacement-isn't that the trace of metonymy or thetechnical prosthesis, and the place for the phantasm as well, that is to say,the ghostly revenant (phantasma), at the heart of (self-)feeling? The revenant, between life and death, dictates an impossible mourning, an endlessmourning-life itself. Barely visible scene of this mourning: it pertains toa spacing that is irreducible or even heterogeneous in relation to an "extensio" from which, however, one should not dissociate it.22 § 3 This Is My Body How is one to take up again the "proper" of "unum quid"?l The debatenecessarily unfolds around an "inextension of the mind," or a "nonextension of the mind," thus around Psyche, inasmuch as she can be "united tothe whole body, " extended, stretched out, subjected-and she lies downon her couch in the course of this union, or even with a view to thisunion, which will always look like a fiction, "quasi permixtio." An animated debate around the animation of inanimate Psyche: it iswith Descartes that Nancy thus organizes this Auseinandersetzung-withhim, wholly alongside and against him, repeating against him, but throughthis mouthpiece and about the mouth, what the inventor of the modern"subject" and its "truth" thought, without thinking, in the very utteranceof the cogito. There are several voices, therefore, in this serene and subtle altercationwith Descartes thus ventriloquized. Although Psyche is in mourning andthe mourning barely acknowledged, she collects herself, making a pronouncement. The pronouncing of a final judgment goes through the opening [embouchure] of the mouth, to be sure, but we could say that, besidesthe places thus identified, it goes through a singular point, and the pointnamed point. For the soul is united to the whole body, and it could not becircumscribed in one part of the body, be it a point. Accordingly, Nancyanalyzes the double contradiction jeopardizing the hypothesis of a punctualspatialization of the mind such as the theory of the pineal gland and theanimal spirits inhabiting it. It is contradictory to think of the mind as anextension, but it is also contradictory to think of extension as a point.Hence the voluminous figure of a gland whose soul does not inhabit the This Is My Body 37 inside, steering i t like a pilot. Hence, also, the "incredible theoretical contortions Descartes engages in so as to subtilize the body in the gland andthe 'animal spirits,' in order to permix body and mind." If "the gland is thisimprobable somewhere, also an 'unum quid,'" and if '''unum quid' pronounces 'ego'" (Nancy, "Unum quid, " pp. I44-4 5 , I 5 6), then the altercation with Descartes finds its space here (at least here in this book, Ego sum),that is, not in the question of the heart or of the body, but on a strange trajectory between an improbable pineal gland and a mouth from beforespeech [parole] , an opening still anoral and already touching. Digression. Why this altercation with Descartes (rather than with Aristotle or Kant?) It could be explained by the needs of a strategy, with reference to the subject, this concept of modern tradition, if one can put it likethat, and more precisely to the truth ofthis subject, which one often associates with Descartes (though the word "subject, " sensu stricto, is notCartesian but rather Kantian) , notably in discourses marked by Heideggerianism or Lacanism. Nancy's strategy seems dear: "The nonextensionof the mind appears, therefore, as what the union demands as much aswhat the distinction guarantees. What is demanded and guaranteed in thisway is the unity of the subject as its truth" (ibid., p. I4 5 ). Altercation with Descartes-as we were saying-rather than with Kant,or Aristotle. Why not with Kant, who paid more attention, no doubt, to any subjectivity of the subject than Descartes did, and to what we call touching[Ie toucher] ? Is it because Kant is fundamentally mute, taken aback, when confrontedwith the body, confronted with the union of the soul and the body? This,at least, is what Nancy proffered three years earlier in Le discours de fa syncope: Logodaedalus,2 a luminous, inventive book, so cheerful it leaves onebreathless; it bursts with the laughter of thought-at the very place whereit leads us to think the thinking of laughter and of syncopes and syncopation, the contretemps, and also the counterpoint that gathers and upholds, in order to keep it all together, dissociation itself. Thus, " Kant the philosopher" has nothing to say about the flesh, aboutthe philosopher's flesh, about his "union of the soul and the body": in a sequence that we shall have to reconstitute, Nancy names "a connection between the body and thought about which Kant the philosopher, in truth,has nothing to say" (Nancy, Logodaedalus, p. I4 5) .:1 nothing to say ("For i f we admit that with all our thoughts i s harmonically combined a movement in the organs of the body . . . " ) . 6 The union of the soul and the body (this union giving itself sexual airs here) , this union which is also the sublime union of thought and the un thought (the nonrepresented)-this union which isn't one, and isn't the re union of two orders or two substances, but is, if it is something, the philoso pher's jlesh-, this union of the heterogeneous is not the object of some knowledge: "What is your opinion about the union [Gemeinschaft] of soul and body, about the nature of mind, about creation in time? I have no opin ion whatsoever about that . . . . Whence this question is necessary and, in re gard to the object, can only be answered subjectively-this I knoW."7 ones? To the extent that touch is the only sense of immediate external perception and thus the one bringing us the greatest certainty, it is the mostimportant or the most serious one (wichtigste), although it is the clumsiest (grobste) among the external senses. In a way it is the foundation of theother two objective senses, sight and hearing. These must "originally bereferred" (urspriinglich bezogen werden miissen) to touch in order to "produce empirical knowledge" (um Erfohrungserkenntniss [sic] zu verschaffen)(Kant, Anthropology, p. 42) . Such a hierarchical arrangement is without any doubt part of the greattradition that accords an absolute privilege to touch and does not let itselfbe encroached upon by the possibility (briefly and poorly evoked by Kant)of any vicariousness of the senses (Vicariat der Sinne) . This "tactilist" or"haptocentric" tradition extends at least until Husserl and includes himhis original part will be discussed later. The tradition becomes complicated,with the risk of being interrupted, in Merleau-Ponty, as we shall also see,when the latter seems to reinstate a symmetry that Husserl challenges between the touching-touchable and the seeing-visible. Now, in the Kantian period of this tradition, it is indeed suitable for apragmatic anthropology to know the fundamental, founding, and originarysignification of touch, for the only organ to which Kant ascribes this organic sense is the hand, the human hand-the fingers and the fingertips,in truth. The sense of touch has its appropriate place in the fingertips andthe nerve endings, the papillae. These nerve endings inform us, human beings, about the form of a solid body. Indeed, one could ask oneself whichway the difference between the physiological and pragmatic points of viewgoes here. This way, no doubt: if it is nature that has provided the hand, soto speak, it has given it to human beings only; and by thus making humanbeings, it has then allowed them freely to make themselves, particularlythrough objective knowledge, the guiding thread of this analysis. And whatKant analyzes is not the structure of the papillae and the nervous system,or the link with thought, and so forth; rather, it is what human beingsmake with their hands. It comes down to their phenomenal experience ofthe hand, as it were. And one is tempted to suggest that Kant outlines orprefigures, within the limits of an anthropology, a phenomenological orprephenomenological reduction that requires a comparison with Husserl'sgesture in Ideas 11, to be discussed later. The hand's finality; what natureputs within reach of the human hand, and only the human hand; what itallows human beings to make by hand, with the hand, thanks to the hand:42 This Is-ofthe Other all that is the proper object of a pragmatic anthropology. For Kant, as Heidegger and so many others will repeat later, animals possess nothing thatcan be compared to a hand: "Nature seems to have endowed man alonewith this organ, so that he is enabled to form a concept of a body by touching it on all sides. The antennae of insects seem merely to show the presence of an object; they are not designed to explore its form" (Kant, An thropology, p. 41). 1 3 Kant insists precisely o n "form." Since the privileged position o f touch isdefined here from the point of view of objective knowledge, it is advisableto set apart from it all that has to do with "vital" impressions (Vitalempfindung, sensus vagus), that which is not specific to an organ (Organempfindung, sensus fixus) and that, through touch, leads us to sense somethingother than forms: coldness and heat, softness and roughness. Let us note in passing that although Nancy does not make any allusionto this anthropology of touch in Kant in Logodaedalus, it seems to me,here he already underscores a trope of touch. As a mere rhetorical figure, itis a mark that the problematic or thematics of touch have not yet beenbroached, as such, at this date; but their point already appears, and it ispointedly there, above all, like the pointy tip of an antenna, a scout at theforefront, in this very acute place where it always comes forth subsequently: still very close to a point, and upon a limit. For Nancy, it is alwaysa matter of touching what is well-nigh at the limit not to be touchednamely, the limit itself, and the point's extreme, pointed tip. Thus, the sentence quoted j ust below is all the more remarkable because, in evokingKant's Anthropology (but at the same time ignoring its theory of touch) , ithas to do precisely with the figure and with sensible figuration in Dichtung [poetry] . Let us read these lines, which describe a coupling and what then"touches" with its "pointed tip." They also follow a remarkable, abyssal development about the "fraternal" ( Kant dixit) or even an "incest" (Nancydixit) , between the understanding and sensibility, locus of schematism,place of "art concealed" in the depths of the soul, of Dichtung, sensiblepower or sensible figuration of this power, and so forth. "But for the timebeing this operation is more narrowly interesting for us: here, in the An thropology, it couples understanding with sensible imagination. Now, whilethe power of Dichtung remains, to the letter of the text, limited to sensibility, it nonetheless touches on understanding, with its pointed tip" (Nancy, Logodaedalus, p. 108) . 1 4 Here ends the digression, or anticipation.r This Is My Body 43 o f space? Doesn't Freud confirm that pure intuition [here o f space] "mustbe found in us prior to any perception of an object" and that consequently,it must be a "pure, not empirical, intuition"?18 Therefore, wouldn't it be akind of pure sensibility, the insensible sensibility reappearing as a motif inHegel and Marx? And here, following our thread, a kind of sensibility touching nothing? Or a kind of touch without empirical contact, a self-touchingor being touched without touching anything? For it is known that therecognition or attribution of extension to something or someone (for example, to Psyche, which and who is both) does not suffice to make a body, atangible body. The pure form of sensibility, pure intuition, "even withoutany actual object of the senses or of sensation, exists in the mind (im Gemuthe) a priori as a mere form of sensibility. " 19 Kant insists on it: in therepresentation of a body, when one has detached what comes from the understanding (substance, force, divisibility) and what comes from sensation(impenetrability, hardness, color) , there still remains something of empirical intuition: extension (Ausdehnung) and figure (Gestalt) . It will not have escaped the attention of anyone interested in touch, aswe are here, that among properties accessible to sensation are the properties that are tangible par excellence, that is to say impenetrability (Undurchdringlichkeit) and hardness (Harte) , tangible properties that Kant'sAnthropology from a Pragmatic Point of View excludes from organic sensibility in order to lock them into a vital receptivity (Vitalempfindung, sensusvagus), without organs, without objective knowledge. These sensible givensof sensation do not fall within pure sensibility, as figure and extension do.Here, even if there is no touchable body that does not also appear extended, extension is not touchable through the senses-no more than inDescartes, though for radically different reasons. It is well known that thismotif of transcendental ideality is joined to an empirical realism interrupting the reduction of appearances-that is, phenomena-to mere illusion. Certainly it allows one to understand the movement of the "goodBerkeley" who foresaw the absurdities to which a realism of space and timeas properties of things in themselves leads. But it also allows one to avoidBerkeley's absolute idealism. I am recalling these well-known yet always enigmatic matters for a number of contextual reasons. On the one hand, it is in order to try to understand Freud's brief allusion to Kant, its ambiguity, and how diffi c ult itmight be to inflect it toward any materialization, or incorporation, or evenincarnation of Psyche (the word "extended" in itself means neither accessi- This Is-ofthe Other Aristotle has not left us for a moment, even though Nancy does not invite him to speak. Let us stress again the singular place that touch has inAristotle's discourse on the living-in such a zoology. Touch is the onlysense that the existence of the living as such cannot dispense with. Thepurpose of the other senses is not to ensure the being of the animal or ofthe living, but only its well-being (Aristotle Peri psuches 43 5b2o-25) . Butwithout touch animals would be unable to exist; the sense of touch aloneis necessarily the one whose loss brings about the animal's death: "It is evident, therefore, that the loss of this one sense alone must bring about thedeath of an animal. For as on the one hand nothing which is not an animal can have this sense, so on the other it is the only one which is indispensably necessary to what is an animal" (ibid., 435b4- 7) . Aristotle measures this essential coextensivity of animal life and touch; he also explainsit by putting it to the test of death. When an animal is deprived of sight,hearing, or taste, it does not necessarily die. Should it come to a lack oftouch, however, it will die without delay. (This follows the set of distinctions recalled earlier.24 Among the senses, touch is an exception, becauseit has as its object more than one quality-in truth, it potentially has allsensible qualities.) Conversely (but it is the other side of the same phenomenon) , animals also die when an excessive intensity of touch touchesthem. Tangible excess, "hyperbole, " comes to destroy the organ of thistouching, "which is the essential mark of life" (ibid., 43 5b) .25 Couldn't onesay that this measure, this moderation of touch, remains at the service oflife to the sole extent, precisely, that some kind of reserve holds it on thebrink of exaggeration? A certain tact, a "thou shalt not touch too much,""thou shalt not let yourself be touched too much," or even "thou shalt nottouch yourself too much," would thus be inscribed a priori, like a firstcommandment, the law of originary prohibition, in the destiny of tactileexperience. Ritual prohibitions would then come to be determined, afterward, and only on the background of an untouchability as initial as it isvital, on the background of this "thou shalt not touch, not too much,"which wouldn't have awaited any religion, ritual cult, or neurosis of touch.In the beginning, there is abstinence. And without delay, unforgivingly,touching commits perjury. Touching, then, is a question of life and death. One cannot say as much,and it is not true, of the sense of the senses in general. Now, whether or notNancy aimed at the opening of Peri psuches, whether he did it deliberately,explicitly, or elliptically, or even maliciously (like Eros who "contemplates" This Is-ofthe Other Psyche, "flustered and mischievous, all at once") , it turns out that, in the brief, discreet page, the quasi-mute tableau, the powerful, reserved allegory that Nancy, the author of "Psyche," affects to dedicate to a kind of deplo ration (Psyche's deathly sleep and her imminent interment) , we can deci pher a stubborn, ironic, discreet, and overdetermined challenge to Aristo tle, to the one who, at the beginning of Peri psuches, lays down or implies this double possibility, that is, knowledge and self-knowledge of the soul. Hypothesis: would Nancy have chosen the words "around her" for his last sentence if at this point he had not had Aristotle's Peri psuches in view, even though he virtually never mentions it? He insists on this, with cruel exactitude, and I emphasize: "She knows nothing of this-and that is what everyone knows around her, with such exact and cruel knowledge." For according to Nancy, the knowledge of "those present" with Psyche, around her (let's say, peri psuches) , is the knowledge so "exact and cruel" of which (and that) Psyche, for her part, knows nothing, nothing herself, of herself-of (and from) her extension, in any case. We have noted it-it is repeated, in more than one language, four or five times within a few lines. The scene goes on-it certainly places itself, if one may put it this way under Freud's authority, or at least it goes with the guarantee, or the secu rity, of his "posthumous" note (for there is also another, more Aristotelian Freud: psychoanalysis intends to be knowledge that is peri psuches and ac cessible to a psyche knowing itself, in a certain way) . Let us be attentive to this writing, which is so exact, and above all to the unfolding in time, to the rhythm, to the four beats in time of this tableau vivant. Any picture, tableau, or portrait is called a zographia, or tableau vi vant-in short, a "living painting" or "painting of the living"-in Greek. But for this once, here is the tableau vivant of a death-of an imminence, of a coming death, of a dying woman who will be dead before the end of the sentence. But a corpse that has not been buried yet. And even if this were her entombment, she has not yet been conveyed into the ground. Later in the year during which I wrote the first version of this text (1992) , Nancy gave an extraordinary conference about Caravaggio's paint ing The Death ofthe Virgin at the Louvre. The text, "Sur Ie seuil" ("On the Threshold") , was reissued first in Po&sie,26 and then in The Muses,27 a book that comes back forcefully to the question of touch and the "primacy of touch" (Nancy, Muses, p. uf£)o From then on-since Nancy refers then to the first version of my text, among other things-in our gestures we keep :�,.,rI This Is My Body 49 meeting, even touching each other, at all points where there is a question of our touching. And from this point of view, I no longer dare, I hardly dare approach Nancy's numerous writings published after 199 3 . It remains that one should no longer dissociate two "apparitions," two "visions," however singular: "Psyche" (19 7 8) and "On the Threshold" (199 3 -94) . What I venture to term a vision or an apparition, the one in spiring this last reading of The Death of the Virgin, so beautiful it leaves one breathless, here looks like "Psyche" in a troubling fashion-but with out authorizing the slightest analogy. I may try to make them co-appear some day, word by word, in their ineffaceable difference, but also in their reciprocal convocation or annunciation-a little like the two Marys, the Virgin and the Sinner or the Penitent, of whom the last text speaks: "Mary is the model of Mary, but no figure is common to them both. Doubtless they together refer to a third, who, however, is not or is barely a figure . . . . In the Entombment by the same painter, the two Marys are side by side" (Nancy, Muses, p. 65) . I shall not quote here every sentence that would have suited "Psyche" fourteen years earlier. I let myself go and imagine that this scene, this woman in truth, never leaves him: she remains for him, in front of him, forever immobile, impassive, intangible. Christianity's indeconstfuctible? What a scene! What scene? What woman? Why she, when he thinks-so far and so powerfully-that thought is extended, when on this subject he quotes an enigmatic sentence by Freud? Why this hallucination of one who would be extended, a woman, and a beautiful one, so beautiful, beautiful for being neither dead nor alive, eternal yet perpetually dying, and surviv ing, belying death itself, death's ever being there? Psyche as Mary, Psyche as Mary and Mary, as two or three Marys: the virgin, the sinner, the penitent. Just one example, but it is not an answer. And it is not in "Psyche, " but in The Muses. As always, exactitude keeps its appointment (I am empha sizing: " . . . she is not exactly dead") : She did not die here. They have carried her to this makeshift bed where they deposited her body, slackened in a posture not yet arranged, to wash it before the funeral. . . . And yet, this body is firm, whole, intact in its abandon. It is not here that this woman died, but here she is not exactly dead. One might also say that she is resting, as if she were still on this side of death, or else already beyond it . . . . And is it not for this reason that there is not, there is never "death itself"? (Nancy, Muses, pp. 58-59) This Is- ofthe Other 2.about the fact that, of her dispersion partes extra partes, everyone saveher-safe she-can calculate the order and report on the relations; 3 . about the fact that in her sleep and the abandon of her pose, "flustered and mischievous, all at once, Eros contemplates her"; 4. about the fact that later (but is it not already "later," or "later" soon?) ,in her coffin, which is soon going to be shut ("Soon it is going to beshut"; she is dead but, like disappearance, inhumation seems imminent;she is dead but remains visible; she is dead but not yet a departed [une disparue] ; she is on the verge of disappearing but is still visible, though shedoes not know herself to be seen)-well, the others, in their presence peripsuches, see her or avert their eyes-but in any case they know her [la savent] .28 Exactly. If psuche is Life itself, then mourning Psyche is not j ust any mourningamong others. It is mourning itself. It is absolute mourning, mourning oflife itself, but mourning that can neither be worn and borne (no life canput on such mourning any longer) nor go through the "work" of mourning. Mourning without work of mourning, mourning without mourning.Mourning on the threshold of mourning. Our life itself-isn't it? To represent Psyche as a dead woman, "extended in her coffin," is to representLife as a Departed woman [comme une Morte]-dead in her sleep already.What is dying in one's sleep? A transition of which we are told nothing, asif on purpose, but of which the temporality interrupts itself. Within theblank that marks the passage from one paragraph to the next,r This Is My Body 51 Her sleep i s s o deep that i t has even robbed her of any abandon i n her pose. Psyche is extended in her coffin. Soon it is going to be shut . . . . the passage is from one rest to the other. One has gone from the sleep ing woman to the corpse-or the recumbent figure. From the transient repose of sleep ("She lies at rest; the slight movements of sleep have half exposed her bosom"), a pose seeming to seduce Eros as much as Psyche's nonknowledge, one has insensibly become engaged in the endless repose of death. From the repose of the pose, one has slid toward the extended extension in the coffin. But across the interruption, across the blank on the page, one has moved from one imminence to the other. No sooner asleep (asleep almost all at once), no sooner dead (dead almost all at once) , all at once, "soon" locked into her coffin . Precipitated time of imminence, a "soon" announcing the end rather than the future, this is the announcing of an apocalypse, which is to say an unveiling or revelation. Now, what this apocalypse reveals is not so much a truth as the night of nonknowledge in which every desire gathers momentum. Eros's flustered, mischievous contemplation seems to have to do with this nonknowledge and Psyche's own unknown. Eros seems seduced by that which, in her, no longer affects itself. And by that which, in her, can no longer say "I touch myself." 1 seduces there where 1 does not self-touch. It is she. She, Psyche, is desirable, infinitely, as death, as a dead woman coming, and only a Psyche lets herself be desired, where she knows nothing, feels nothing of herself, where she partakes of the discontinuous duration, the precipitation of a dying [mourance] in which she finds herself without finding herself al ready, in her rest as a sleeping and a dying one, soon in her deadly rest, and soon invisible and inaccessible still: ex-posed to the other and surrendered [/ivree] , but already inaccessible and just before becoming invisible. Ex posed, surrendered but all too soon denied to the other's eyes after having been prey to the other's hands. Maybe as a dead woman, as only the dead may be. Between the hands of the other, surrendered into the other's hands. The other's hands: this could have yielded a title for all the scenes that are henceforth going to engage us. This tableau condenses the narrative ellipsis of an allegory. Psyche is ex posed, surrendered to the word of the other around her-and about her. For Psyche, for a psyche altogether exposed to the outside and the other, I ' I52 This Is-o/the Other there is no autobiography, there has never been any "I touch myself." Nopoint in a signed autobiography for the one who, untouchable to herself,feels or knows nothing of herself. Mourning autobiography is not just anymourning among others, any more than Psyche's mourning lets itself bepreceded or properly figured by any other. One might as well say that, being unimaginable, it can only give rise to images, phantasms, and specters,that is, figures, tropes, allegories, or metonymies opening a path to technics. Being undeniable, it can only leave room for denial. And so thismourning without mourning will never be overcome by any-failing orsuccessful-"work of mourning. " At the time when he attempts to rethink the question of "sense" between the name of death and the verb for being born [naitre] , Nancydraws the line, exactly, between "work of mourning" and death, betweenthe work of mourning and absolute mourning. In doing this, he showsthe direction for a representation of the unrepresentable-and this couldwell be a way of inviting us to read, of telling us how to read, in otherwords and beyond any representation, of seeing without seeing his allegorical painting named Psyche. Death is the absolute signified, the sealing off [bouclage] of sense. The noun is what it is (and even this proper name, "Death"), but the verb is "bear," to be born [naftre] . It is certainly neither false nor excessive to say that all production of sense-of a sense making sense in this sense-is a deathwork. The same goes for all "ideals" and "works," and the same goes, remarkably, for all philoso phies. Philosophy distinguishes itself by the unique way it profits from death [jouir de La m ort] -which is also a way of assuring its own perdurability. Phi losophy is ignorant of true mourning. True mourning has nothing to do with the "work of mourning": the "work of mourning," an elaboration concerned with keeping at a distance the incorporation of the dead, is very much the work of philosophy; it is the very work of representation. In the end, the dead will be represented, thus held at bay. But mourning is without limits and without representation. It is tears and ashes. It is: to recuperate nothing, to represent nothing. And thus it is also: to be born to this nonrepresented of the dead, of death. To come forth and be born: to find ourselves exposed, to ex-ist. Existence is an imminence of existence. 29 This sets off a dream: what if Psyche also described the picture of an imminent "being born" ? Of a coming into the world? What if the work ofr This Is My Body 53 a thing and this "in itself" is no longer an interiority. Let us rather quote, and emphasize: "If only our world were to understand that it is no longer time to want to be Cosmos, no more than Spirit oversizing Nature, it seems that it could do nothing except touch in itself the abjection of fes tering immundity [/'abjection de l'immonde] ."30 (A parenthesis for a matter to be developed later, elsewhere, unless it has long been done already: at this time in the "history" of the "world," with a discourse-rather, the world's doxa -spreading so powerfully, easily, irre sistibly, as well as violently, on the subject of the said globalization (mondia lisation in French; Globalisierung in German); at the time when Christian discourse confusedly but surely informs this doxa and all that it carries with it, beginning with the world and the names for its "mundiality," and its vague equivalents globe, universe, earth, or cosmos (in its Pauline usage) , Nancy's propositions may be intersecting with a strand of Heidegger's proj ect (though his trajectory is quite different), which is to dechristianize the thinking of the world, of the "globalization of the world" [mondialisation du monde] , of the world insofar as it mundifies or mundanizes, worldifies or worldizes (weltet) itself. What Nancy announces today under the title "The Deconstruction of Christianity"3] will no doubt be the test of a de christianizing of the world-no doubt as necessary and fatal as it is impos sible. Almost by definition, one can only acknowledge this. Only Chris tianity can do this work, that is, undo it while doing it. Heidegger, too -Heidegger already-has only succeeded in failing at this. Dechristianiza tion will be a Christian victory.) What "our world" touches in itself, then, is nothing else but this rejec tion. Self-expulsion is precisely what it produces. This thinking of "touch," of the world's "self-touching," of "our world" inasmuch as it is rej ected and rejects itself as foul and festering "immundity," is going to develop amply at the point when Nancy writes Ie sens du monde (The Sense of the World) ,32 published one year later. Indeed, it comprises a chapter on "Touch"-to which we shall return-and another, "Painting," that prof fers essential, powerful things about "the threshold between intactness and touching" (Sense of the World, p. 81) . But above all, within its very axio matics ("The End of the world"; "There is no longer any world: no longer a mundus, a cosmos. . . . In other words, there is no longer any sense of the world" [ibid., p. 4]) , it corresponds, in a way, with the discourse orienting Corpus, about rejection, abjection, expulsion. What happens in it? And why does it fall to a work titled Corpus to putrI This Is My Body 55 of ecotechnics," such as one sees it appear and reappear here, will later introduce us to what, it seems to me, singles out Nancy's thinking among allother modern ideas about the body proper, the flesh, touch, or the untouchable, which is to say, the taking into account of technics and technical exappropriation on the very "phenomenological" threshold of the bodyproper. And there, this thinking of touch, of the world and of rejection, ofthe possibility of the world as possibility of "its own rejection," seems bothnecessary and impossible, in equal measures-mad, fittingly; fittingly andj ustly mad; j ust to be mad; j ust like a certain kind of madness.) This exudation and this intimate agitation of the world's corpus are Psyche's extension. . . . This is not only the ambivalent effect of all narcissisms. In fact, as soon as the world is world it produces itself (it expels itself) also as foul im mundity. The world must reject and be rejected (as) a festering im-mundity, because its creation without a creator cannot contain itself Creators contain, they retain their creation and bring it to bear on themselves. But the creation of the world of bodies comes to nothing, and falls to no one. World means to say without principle and end: and that is what spacing ofbodies means to say, which in its turn means nothing except the in-finite impossibility of homogenizing the world with itself, and the sap of sense with the sap of blood. Openings of the sanguine are identically those of sense- hoc est enim . -and this iden . . tity is made only of the absolute self-rejection that the world of bodies is. The subject of its creation is this rejection. The figure of ecotechnics, which prop agates, in every sense and way, global swarming and the foul contagion of im mundity, is the figure of this identity-and in the end, no doubt, it is this identity itself. A body expels itself, that is, as corpus, distended spastic space, rejection-of the-subject-"immundity," if the word is to be retained. But that is how the world takes place. In a sense, the creation of the world of bodies is the impossible itself. And in a sense, in a repeated stroke of sense and sanguinity [de sens et de sang] , the impossible is what takes place. That the sensical and the sanguine have no common schema (notwithstanding the sound and scent of their sans and the infinite of " roo " [cent] ) ; that creation is an uncontainable distancing, a fractal and architectonic catastrophe; and that coming into the world is an irrepress ible rejection-all that is what body means, and what sense means, henceforth. The sense of the world of bodies is the sans-without-limit, without-reserve; it is the assured extreme of extra partes. In a sense, that is what sense is, in one sense-always renewed, always spaced out, in one sense and an other, in a cor pus of sense and thus in all senses, but without possible totalization. The ab- This Is My Body 57 solute sense of the world of bodies, its very [memes] mundiality [mondialite] and corporeality: the excretion of sense, sense exscribed. Thinking this makes one mad . . . . the world is its own rejection, the rejec tion of the world is the world. (Nancy, Corpus, pp. 93-95)36 The insistence and playfulness are remarkable here, and first, amongother things, the insistent, mechanical, machinelike, and quasi-mechanisticreturn (understood as an introduction to ecotechnics) to the structure ofpartes extra partes,37 the "assured extreme of extra partes," which had ensured or even organized Psyche's very body; and then, the playful gamebased on the word "sense." The plurality of the senses of the word "sense"affects each of its two principal senses: on the side of signification, ofcourse, when one speaks of the sense of a word or the sense of the world,and so forth, but also on the side of the said sensible faculties and sensitivity, each side remaining essentially multiple, resisting community, resistingit precisely by virtue ofpartes extra partes, a contiguity without contact, ora contact as artificial, and thus technical, as superficial. By definition, this spaced-out multiplicity can only "renew" itselfwhence this concept of creation ("creation of the world of bodies," for example) , which Nancy will never give up, at the very place where this creation is said to be "without a creator" and even "impossible," the impossibleof an impossibility that is in truth what takes place: "the impossible is whattakes place." Madness. I am tempted to say of this utterance, itself impossible, that it touches on the very condition of thinking the event. Therewhere the possible is all that happens, nothing happens, nothing that is notthe impoverished unfurling or the predictable predicate of what finds itselfalready there, potentially, and thus produces nothing new, not even accidents worthy of the name "event." The spaced-out multiplicity of senses,and of the senses of sense, and of the sense of the senses-the condition ofcreation as well as of the event-is also (if one may further say so) whatsanctions this just madness of thinking or language, the madness arousedby phrases such as "in a corpus of sense and thus in all senses, but withoutpossible totalization." All the concepts of Nancy's new corpus, all the concepts that he "created, " in this new sense of the word create (creating the world, the sense ofthe world, mundiality, the ex-scribed or ex-creted, sense, "the excretion ofsense, sense exscribed," and so forth) are born of this j ust madness, andthey call for a different thinking of the j ust. This Is- ofthe Other We said that they are "born," for these catastrophic theses ("creation . . .is a fractal . . . catastrophe") are also thoughts of birth. They make us givethought to the birth of the body, of the corpus, a birth to distinguish herefrom plain origin. They let us think of a delivery into the world as a rejection, but also of the possibility of rejection in general, the rejection ofthe body at birth as well as the rejection of one of its essential parts-atransplanted heart, for example-by the body itself In itself ejectable, disposable, rejectable. Immune disorder is also in order.38 All that Nancy willlater say about the "exscribed" essentially springs from this, it seems to me.And since it is also a matter of self-rejection, this source does remain essentially autobiographical. But this is true only at the point where, as wehave noted, Psyche's pure autobiography is impossible, and the possibilityof transplantation puts its instituting signature there. The return of "Hocest enim . . . " in this book is more than just a mise-en-scene setting thetable for transubstantiation, which is sarcastic, that is, mordant-a fiercetransubstantiation tirelessly biting, morsel by morsel, and biting again,mortally setting upon the flesh, putting it to death; a transubstantiation ofthe Eucharist itself, agitating the whole Corpus, shaking it sometimes until it bursts out laughing. The one who speaks here presently has an experience of death, and therefore of the living body, that cannot be invokedby any of those who are like me and never stop thinking about deathwithout having yet had a change of hearts-and without knowing, without knowing within their bodies, within their "my body," that a heart canbe thrown off or rejected. Of course, they do know it, but isn't theirknowledge so very poor, abstract, shameful, protected, and shamefullycozy, compared to his knowledge-that of the one who is able to put hissignature to Corpus, who happened to be able to sign that Corpus? To each his or her own "Hoc est enim . . . " to sign. We have recalled one, and here is the other, on the facing page, with another accent; it is the continuation of the interrupted quotation: Thinking this makes one mad. This thinking, if it is a thought, or the thought that it behooves one to think that-and nothing else. This thought: "Hoc est enim," here it is, the world is its own rejection, the rejection of the world is the world. Such is the world of bodies: it has in it this disarticulation, this inar ticulation of corpus-enunciating the whole, wide-ranging extension ofsense. In-articulating utterance [enonciation]-that is to say, signification no longer, but instead, a "speaking"-body that makes no 'sense, " a body- 'speak" that is notr This Is My Body 59 organized A t last, material sense, that i s t o say, madness indeed, the immi nence of an intolerable convulsion in thought. One cannot think of less: it's that or nothing. But thinking that, it's still nothing. (It may be laughter. Above all, no ironizing, no mockery-but laughter, and a body shaken by thinking that can't possibly be.) (Nancy, Corpus, p. 9 5) From the opening pages onward, things are clear: the title, Corpus, first of all rings out like such laughter, like a sort of thinking burst of laughter, fierce and implacable before Jesus, in truth within the very evangelical word and the Christic body. The whole book preys and sets upon "Hoc est enim corpus meum," thereby announcing his work in progress, whose an nounced title is "The Deconstruction of Christianity." But Nancy believes he can identifY the power or reach of "Hoc est enim corpus meum" well beyond Christian culture strictly speaking and hear in Buddhism, Islam, and Judaism an "obstinate, or sublimated paganism." Unless-whispers the spoilsport that I have remained, at the point of lighting votive candles, still, in all the Catholic churches in the world, in the role of incorrigible choirboy, and Jewish, no less-unless there is no true beyond, beyond what I just imprudently termed "Christian culture strictly speaking"; unless Christianity carries in itself-and all but consti tutively consists in carrying in itself-the resource, and the law, of this de stricturation, of its passage beyond itself, of this ability to part without parting, of universal abandon while remaining with oneself, in a word of death without dying, without this "death itself" ever coming about. Then, the deconstruction of Christianity would have its infi n ite task cut out for it as its daily bread. "Hoc est enim corpus meum." Bread for the ( Last Supper) stage would safeguard the very memory of all deconstruction. Evangelical and apocalyptic. Luke and John. Saint Augustine recalls this clearly in The City of God, which also quotes Peter and John. And know ing how to read would be enough, if one can put it like that. It would be enough to hear, but hear well, the injunctions about reading at the end of John's Apocalypse, the terrible threats Rung at those who will not hear or do not know how to read, and at anyone tempted to add or subtract some thing in the witnessing text, in the "martyrdom" describing the punish ment reserved for those who, instead of reading and receiving, would like to enrich the text further, or deplete it, and then write otherwise, some thing else-in a word, deconstruct or sign. Nancy does not want to believe in this-nor be a believer-and neither do I. But all the same. If there is60 This Is-ofthe Other I shall not even attempt to comment, paraphrase, or gloss the first chapters of this Corpus. They are too rich, and their stitches too tightly woven.My sole ambition is to invite reading, inevitably, directly, and without interposition. I am content to track the metamorphic displacement oftouch, there where the trail is in danger of disappearing. Indeed, "touching, " the lexicon of touch, strikes a grammatical poseand heads off on quite diverse rhetorical side paths. It carries a semantictenor whose specter seems to obey a subtle and ironic play, both discreetand virtuoso. As if a master of language airily made believe he wasn'ttouching any of it. And by the way, is he doing it on purpose? Or is he letting a treacherous symptom show an obsession too strong to be dominated or formalized? A dread that is within language before it haunts anindividual subject? And within a language that changes sense, that touchessense, one could say, reaching the presumed core of sense, passing fromthe verb "to touch" to the noun "touch," or from the noun to the adjective and the participle "touching"? ONE . Thus, for example, j ust within the limits of the first three pages of the book, here is toucher at first, a verb, "touching" as a verb. From the firstpage, and despite a certain Thomas, there is a suggestion that this "Hoc This Is My Body 61 est enim . . . " ends up forbidding us to touch, or in any case seeks to keepits body away from anything that could touch it: " [1] £ is our obsession toshow a this [ceciL and to be convincing (ourselves) that this this [ceciLherewith [ici] , is that which one can neither see nor touch, neither herenor elsewhere-and that this is that [cela] , not in whichever way, but as itsbody. The body of that [ fa] (God, the absolute, whatever one wishes) , thathaving a body, or that being a body (and thus, one may think, 'that' beingthe body-absolutely) : that is what haunts us" (Nancy, Corpus, p. 8). TWO . But j ust after that, here comes a noun. In order to describe the idealization that keeps the body from touching, in order to see to the sublimating subterfuge or the magical sleight of hand that makes the tangibledisappear, Nancy resorts to the pictorial figure of the touch [La touche] . 4 1The magician's finger, which makes the tangible untouchable-this is apainter's paintbrush. He must know how to put the finishing "touch" tohis simulacrum so as to make the body vanish in producing it, and so asto reduce it in affecting its production: '''Hoc est enim . . . ' defies, appeases all our doubts about mere illusions, giving to the real the true finishing touch of its pure Idea, that is, its reality, its existence. One wouldnever be done with modulating the variants of these words (randomlylisted: ego sum [the title of that other great book by Nancy, thus dealingwith egological fiction] , nudes in painting, Rousseau's Social Contract, Nietzsche's madness, Montaigne's Essais, Antonin Artaud's 'nerve-meter' [Pesenerfi])" (ibid., p. 8) . If one reads what follows, it goes the way of thewhole culture, "the whole texture interweaving us": "Body: that is how weinvented it. Who else in the world knows it?" (ibid.) . THREE. Now, just after the verb and the noun, here comes the attribute suffer the wounds of the said "sense certainty. " In order to describe the point at which the latter is all at once attained and wounded ("attained" in the sense of "reached," become accessible, but also reaching out toward an "attaint," and the sense of a harm that is "sustained") , Nancy says of it that it is "touched": no sooner has one attained it, no sooner has one touched it, no sooner does one believe one is touching it, than one wounds it, find ing it harmed already, attainted, cut into, vulnerable at once, and even sick. It is not what it used to be, nor what one believed it to be. Waking from this anesthesia, sense certainty becomes mad. It mixes up everything. What makes sense, Rimbaud says, are the senses in disarray. Adjective, attribute, past participle: ''As soon as it is touched, sense certainty turns to chaos, to tempest, and every sense to disarray. [,] Body is certainty startled and shat tered. Nothing is more properly of our old world, nothing more foreign to it" (ibid. , p. 9). FOUR. Retouching the verb. What in fact happens just after that-after the verb, the noun, the past participle, or adjective have had their turn? We turn to the verb toucher, "to touch," again. Paradox: we shall now be shown that if one has sought (as in ONE ) not to "touch," to keep the body from touching; if one has longed for the untouchable; if one has had to add a "finishing touch" (as in TWO ) to the idealization and the conjuring away of touch; if sense certainty is thus "touched" by this (as in THREE ) until the senses are in disarray, it is because of a desire or a hyperbolic hunger to "touch," to be what one wants to touch by eating it. "Touch" turns around, and everything seems to be decided. All of Nancy's new conceptuality (BegrijJlichkeit) , a seizing put-upon or at grips with one's grasp,42 receives the mark of this, beginning with another thought of the body, of the mundane and "immund" world, and of freedom, and first and foremost, of what from now on excribes itself as the ex-scribed (as ex pulsion, originary abjection, and so forth) . At this turning point (though one could find other metonymies) , one seizes again the resource or springlock of Nancy's thinking-his weighing, as we shall say later-and in it, let's say, that which might make a beam of the scales-or a "flail," or even "scourge," the "flail" proper, which is to say every sense of the French word fUau: an instrument for threshing or flagellating; evil; calamity; cataclysm or disaster; baneful wound; some times, precisely, the scales or scourge or flail 0/ God; or as God; but espe cially an implement of justice with scales that weigh exactly, necessarily, the unthinkable and unweighable [l'impe(n)sable] , the impossible, the unbear- This Is My Body able, and give the immense its exact measure. A question of hearts, and offoreign bodies, a question of exappropriation of the ownmost and mostproper, as autoimmune desire of the proper, I would say. An implacabledeconstruction of modern philosophies of the body proper and the "flesh."So it should surprise no one that this turning around of touch should produce the concept of ex-tirpation, expulsion of the desirable, of the exscribedand the body far-flung or lost, during the course of a sequence with theLast Supper busy eating the body-in truth, eating God's heart out, theSacred Heart: But instantly, always, it is a foreign body that shows itself-monstrance of a monster impossible to swallow. There's no getting away, one is caught up in a vast waste of images stretching from a Christ who daydreams over his unleav ened bread to a Christ who extirpates from himself a throbbing, bloody Sa cred Heart. This, this . . . this is always too much, or not enough, to be that. And all the ways of thinking the "body proper," the laborious efforts to reappropriate what was believed to be unfortunately "objectified," or "reified"; all the ways of thinking about the body proper are contortions of comparable scope: they end up with nothing but the expulsion of what one wished for. Being in anguish, wishing to see, touch and eat the body of God, to be this body and to be nothing but that, all that makes up the principle of (un) reason of the West. At a stroke, the body, any body, any of the body, never takes place there, and especially not when one names or summons it there. For us, the body is always sacrificed-holy host. If "Hoc est enim corpus meum" says anything, it is outside and beyond any words [hors de parole] , it isn't said, it is exscribed-the body lost in a mindless thrust [a corps perdu] . (Nancy, Corpus, p. 9)43 One is never done with an analysis of the variations, and keys touchedupon, in playing this hymn to touch, to tactful fingering, which is to sayto con-tact as interrupted contact. After the passage I have just quoted,over ten short pages: "the body must touch down" (p. II) ; "Writing: totouch on extremity" ( p. 12) ; "Nothing else happens to writing, then, ifsomething should happen to it, except touching. More precisely: touchingthe body. . . . Writing touches the body, by essence . . . that's where it'stouching" (p. 13) ; "points of tangency, touches . . . " (p. 14) . 44 Shall one join him when he says that this history of the world and thebody is merely Christian, or even Abrahamic, and limited to the West("principle of (un) reason of the West") ? And to the body "for us," implying "we," the Jewish, Christian, or Muslim heirs of "Hoc enim corpus This Is-o/the Other devoid of any empirical sensation. It is also to recall what Freud had saidabout this, precisely, in this "posthumous" note, the "brief tune" quotedfirst: "Psyche ist ausgedehnt, weiss nichts davon." She knows nothing of this, at the point when one speaks of it; she isbound to a secret; she knows nothing of herself-in particular, of herselfextended, and therefore always far off, self-distanced, no matter how closeshe is. Tangible, to be sure, yet untouchable. For Eros, at least. At leastwhen Eros is tactful. And experienced-or even an expert-in caresses. What is still needed from here on? An explanation as to why the Peripsuches of our time is now called Corpus, by Jean-Luc Nancy. § 4 The Untouchable, or Wern gefiele nicht eine Philosophie, deren Keirn ein erster Kuss ist? Who would not like a philosophy whose kernel is a first kiss? -Novalis , I I What to give him, and how? Would it have to be? Does it have to be? I did not know what to present as an offering to Jean-Luc Nancy in or der to tell him of my gratitude and admiration, whose limits I cannot even measure, which I have felt for him for too long-and have seen revived or rejuvenated too often-even to attempt to tell myself their story. There is no declaration for these things, they shouldn't be declared, either publicly or privately. Perhaps the law is always a law oftact. This law's law finds itself there, before anything. There is this law, and it is the law itself, the law of the law. One cannot imagine what a law would be in general without some thing like tact: one must touch without touching. In touching, touching is forbidden: do not touch or tamper with the thing itself, do not touch on what there is to touch. Do not touch what remains to be touched, and first of all law itself-which is the untouchable, before all the ritual prohi bitions that this or that religion or culture may impose on touching, as! ; suggested earlier. And this enjoins us to respect, and above all to respect in I the Kantian sense, so to speak, where it is first of all respect for the law, re spect for which is precisely the cause of respect, that is to say, in the first place, to respect the law rather than the person. This only gives an exam ple of it. Respect commands us to keep our distance, to touch and tamper neither with the law, which is respectable, nor-therefore-with the un- 66 The Untouchable, or the Vow ofAbstinence as ordered (do touch but do not touch, in no way, do touch without touch ing, do touch but do watch out and avoid any contact)-it in effect installs a kinship that is at the same time conjunctive and disjunctive. Worse than that, it brings into contact both contradictory orders (do do and do not do), thus exposing them to contamination or contagion. But what it thus brings into contact, or rather into contiguity, partes extra partes, is first of all con tact and noncontact. And this contact without contact, this barely touching touch is unlike any other, in the very place where all it touches is the other. There is no facile thinking or formulation whatsoever in this-rather, it is madness. It is certainly always possible painlessly to produce and re produce these paradoxical formulas. It is certainly always possible to speak as a somnambulist, to handle symbols stripped of any intuition,3 to pro nounce apparently paradoxical syntagmas such as, to define "tact" or "fin gering" [doigte] , for example, "touch without touching," "contact without contact," or "contact without contact between contact and noncontact." But one certainly feels (as will be verified, and verified precisely by test ing the very senses of the word "sense," of the French sens or sentir, which tend to come down, though not reductively, to the word "touch") that from Aristotle to Nancy, aporias (originally Aristotle's word) , as aporias of touch, lead us to think the essence of touch only through language that paradoxi cal, more than contradictory and hyperdialectical (x without x, x non-x,= the "who" or the "what," the touching or touched, which we shall not toohastily call the subject or object of an act. There is not in the first place thesense of touch, followed by secondary modifications that allow the verb tobe completed by a subject or a complement (that is, what touches whomor what, who touches whom or what) . There is little doubt that Aristotle took into account a differential transformation of touch depending on the diversity of tangible things, and perhaps on what this grammatical distribution may specify. However, for lackof sufficient indications on this subject, 4 one wonders whether in Aristotle'sPeri psuches, his treatise on touch, there was room for blows (for strikingblows in all their multiplicity, a multiplicity that may not be reducible toany general blow) or caresses (all stroking caresses, which may not be accessible either by way of any subsumption under one concept of the caress ingeneral) . A blow is perhaps not a kind of destructive touching, indeed, ofthe excessive tangibility that, as Aristotle already noted, can have devastatingeffects. Likewise, stroking is not only a species of soothing, beneficial, andpleasant touch, pleasure enjoyed by contact. Striking and stroking addressa "who" rather than a "what," "the other" rather than some other in general. Such a living "who" is no more necessarily human, moreover, than itis a subject or an "I." And above all it is not a man any more than a woman. What, then, is a treatise of touch that says nothing about this: "Whotouches whom? And how?"; "Who strikes whom? Who strokes whom?And why? And how?" Let us insist again that various causes or qualities donot come and modify or modalize one single, selfsame, presupposed generality of what we conveniently term the "caress" and the "blow. " Thereagain, they constitute a multiplicity without the horizon of a totalizableunity. For, let us not hide this from ourselves, by this stroke, and with a caress-a caress may be a blow and vice versa-it comes down to the conceptual condition of concepts. And let us not exclude either that certain experiences of touching (of "who touches whom") do not simply pertain toblows and caresses. What about a kiss? Is it one caress among many? Whatabout a kiss on the mouth? What about a biting kiss, as well as everythingthat can then be exchanged between lips, tongues, and teeth?5 Are blowswanting there? Are they absent in coitus, in all the penetrations or acts ofhomosexual or heterosexual sodomy? Is a "caress," more so than a "blow,"enough of a concept to say something of this experience of "touching" ofwhich Aristotle, followed by all those who came after him in the great traditional philosophy of touch, hardly breathed a word? This Is-ofthe Other As for Nancy, he does not fail to name the caress and the blow, or moreprecisely-for verbs and gestures are what counts-stroking and striking,among a nonfi n ite number of other experiences, in what he terms the"tactile corpus," under the heading "Weighing" [''Pesee''] . Of course, I amunderscoring the words striking and stroking, as well as a point that will beimportant for us later on, in that there is no sexual difference marked hereas a dual or dissymmetric opposition, which does not mean that sexualdifference is not taken into account-on the contrary: "Tactile corpus:skimming, grazing, pressing, pushing in, squeezing, smoothing, scratching,rubbing, stroking, palpating, groping, kneading, massaging, embracing,hugging, striking, pinching, biting, sucking, wetting, holding, letting go,licking, jerking, looking, listening, smelling, tasting, avoiding, kissing,cradling, swinging, carrying, weighing."6 Why does he end his list here? What right has he to do so? Are there operations that are completely independent of any tactile semantics andrhetoric? And that would rightfully be excluded from this series? Thisquestion will remain with us, under this form or another; it concerns whatthis corpus has left out. But the opposite question also looms: it concernsinclusion no less than exclusion. And so, by classifying "looking" and "listening" in a tactile corpus, does one follow this traditional or even classical gesture (a gesture we shall keep recognizing later on) , which consists inincluding sight and hearing, as well as all the senses, in the general or fundamental sense of touch? This hypothesis is confirmed j ust afterward bythe inclusion of "smelling" and "tasting, " the sense of smell and the senseof taste. Or, on the contrary, is it a matter of challenging in that traditionthat which would pertain to retaining only the most proper and most literal in what is called touching? What could make one lean toward the second hypothesis in this list would rather be the inclusion of verbal expressions such as "letting go" [/acher] or "avoiding" [eviter] , which rather thantouching seem, on the contrary, literally to signify noncontact, interruption, spacing, a hiatus at the core of contact-tact, precisely! And the heartbeat, with its syncopal interruptions, which gives its rhythm to pulse, pulsion, or even haptical compulsion, the cum of con-tact, coming to link orconjoin only where disconnection remains at work, as well as a possibledisj unction. Not to mention, in this reckoning, that the French grammarof this corpus and the series of transitive verbs referring to an object ofsense lead to the discovery of more undecidable ones, undecidably transitive and/or intransitive ones, "wetting," for example, but especially "weighing," which we have yet to examine. The Untouchable, or the Vow ofAbstinence 71 Now, this changes something as far as tact and touching are concerned.Extension can remain intelligible (with Descartes) or sensible-insensible(with Kant and a few others) , and thus intangible. The extension of a body,a body inasmuch as it is extended, can thus remain untouchable. Can onesay as much about a body or thought that weighs? While these texts have often been translated, they remain untranslatable, no doubt. They speak to us of this untranslatability, of this "trace deposited in language." How is one to translate into English or German the affinity in French between penser and peser? One might wish more often to have at one's disposal a set of analyses as sobering as these, as vigilant and fair with regard to etymologistic desire or metaphoric power, to undecidable and nondialecticizable contradictions, when such an affinity inscribed in an other family of languages is at issue-for example, concerning thought, the affinity between denken and danken and "thinking" and "thanking. " Even in French, we often refer to it, at the precise moment when, in Heidegger's wake, we seek the specificity of a thinking that can be reduced neither to poetry nor to philosophy nor to science. And some are often content with an admiring, trusting, even incantatory reference to the miracle of lan guage: German or English, in which the same gift may be recognized in "thought" and "thanks," and here, in the first place, a gift oflanguages, the good luck, as Hegel put it, of an idiom that is originally speculative. If one gave in to the same wonder, one would point out that the verb peser ("to weigh") is conjugated in French simultaneously as both transitive and intransitive, precisely like the verb penser ("to think") . This "simulta neously" at a stroke bestows its genius, its stroke of genius, upon this sen tence of Nancy's: "La pensee pese exactement Ie poids du sens" (literally, "Thinking [or thought] weighs exactly the weight of sense") . The event of this sentence takes place once only. It signals an invention, signed but re assigned to the account of language, the language one speaks, appropriates, yet never possesses. Thus, one can well see that his sentence, "Thought weighs exactly the weight of sense" plays out, while respecting it exactly, an unstable grammar, a syntax that is untranslatable in its duplicity: . i What, then, is the hypothesis worth that Nancy on his own does not jux tapose modalities of tactility? And the hypothesis that the theme, in his tac tile corpus, is corpus as much as it is tact? I believe it to be confirmed by an-, I The Untouchable, or the Vow ofAbstinence 75 -Weren't you asking, even before the beginning, whether we could caress or stroke each other with our eyes? And touch the look that touchesyou? so? Do you mean to say, 'I'm giving myself' or 'I'm giving myself to myself'?" etc.) . The caress finds itself no less affected by this and divided in truth by thissalvo of contradictory inj unctions. The order, the command is no longeraltogether that of tact: to touch without touching; to press without pressing, always more, always too much, never enough; to give without holding back or retaining, but with restraint; to give to hold without holdingon; to give without imposition: "Tiens!" [There! Hold on to this! Take it!Have it!-Trans.] . What is one saying, what is one giving to understand,when one says "Tiens! " [?] Is what is wanting here the virtual shadow, atleast, of a hand gesture ("Tiens!": "Take this!") , a touching hand or a handing one, a hand given to touch the other, an extended hand held out or extending something to the other? "Tiens!" Take this! But tact's command isneither to tender nor to grasp ourselves and each other without trembling,without some relinquishment at the heart of the seizing. Tact enjoins notto touch, not to take what one takes, or rather not to be taken in by whatone takes. Tact beyond contact. Which does not necessarily mean to say aneutralization of touching. One of our concerns incidentally bears on this enigmatic hypothesis ofneutrality. Could there be a touch or tactile experience that is neutral?And this can be understood in multiple ways-three at least: 1. The way of a theoretical touch, that is to say objective, knowing, exploratory in the epistemic sense of this word: touching in order to know,in view of the knowledge of an object: that which is before oneself but canthus also present itself to sight (the theorem) or that which resists and seemsmore appropriate for haptical objectivity; the privilege of the theoreticaltouch has always been central in every philosophy of touch. 2 . The way of a touch preceding any drive, invested or committed; before caresses or blows, and even before this prehensile and comprehensivegrasping that one can detect in the most "theoretical" of touches. 3. The way of a phenomenological neutralization, a "phenomenologicalreduction," which would leave intact-in order to analyze them or describe their constitution-all the intentional modalities that we have j ustmentioned. Contradictory inj unctions, thus, at the heart of touch. Can they stillgive rise to a phenomenology, or to what Emmanuel Levinas termed a "phenomenology of voluptuousness" as early as in the years 1946-47 , in the first edition of Time and the Other? 1 4 One day, together and separately, The Untouchable, or the Vow ofAbstinence 77 one will indeed have to reread these two thinking approaches to the caress, Levinas's and Nancy's, and from the outset follow this theme withineach of their trajectories, more particularly in order to pinpoint their respective differences in relation to phenomenology, beyond the discrepancies that keep them apart. In Levinas's work, long before Totality and Infinity (1961) 15 and its "Phenomenology of Eros," Time and the Other includes a chapter, "Eros," whichtells of the caress as contact beyond contact: "The caress is a mode of thesubject's being, where the subject who is in contact with another goes beyond this contact. Contact as sensation is part of the world of light" (Timeand the Other, p. 89) . Which is another way of saying that the caress carriesbeyond phenomenality, indeed beyond any contact sensation, or any contact as sensation, and does not share with sight this being enclosed withina totality, this belonging to the immanence of the world. Voluptuousness isnot a "pleasure like others," it is not "solitary. " Somewhat recklessly, Levinas then states that eating and drinking, on the other hand, are solitarypleasures, whereas the caress takes away erotic experience from any "fusion"and recalls "the exceptional place of the feminine." Let us not linger here over this aspect, which I have touched on elsewhere;16 let us j ust keep it company for a step beyond the stop, the onecarrying this analysis of caressing further than touching, though still in accordance with the hand, the hand only: "Contact as sensation is part of theworld of light. But what is caressed is not touched, properly speaking. Itis not the softness or warmth of the hand given in contact that the caressseeks. The seeking of the caress constitutes its essence by the fact that thecaress does not know what it seeks. This 'not knowing,' this fundamentaldisorder, is the essential" (Levinas, Time and the Other, p. 89) . The limit seems unequivocal, but it is subtle. Levinas, Levinas's hand, isproposing it. From the outset, we are clearly told that the caress does notfall under the sense called touch, not even under contact or the sensationone relates to contact: "what is caressed is not touched," "not touched,properly speaking. " Is this clear enough? One could be tempted to putthis proposition side by side with Maurice Merleau-Ponty's when the latter, without however naming the caress, speaks of a certain untouchabilityof the other, or rather of the other inasmuch as the other comprises someuntouchable and thus gives me access to this thinking of the untouchableas such. I ? But this same language immediately acknowledges that it is hostage to This Is-ofthe Other which is a production of being" (ibid. , pp. 256-5 7) .21 What becomes exorbitant does not only exceed or disturb the onto-logic that Levinas callsin question on a regular basis. It threatens the very ethics to which Levinasappeals so powerfully. Threat: the word is not too strong, for all this also describes the threatening par excellence, as a good number of Levinas's formulas let it comeacross. We have to insist on this for three reasons at least, each being of quitea different order. On the one hand, it comes down to the limits of the ethics and axiomatics of the face that are in command of Levinas's discourse on this subject. On the other hand, where promise carries beyond the possible or the future while remaining a promise, an aim, an expectation of a "not yet moreremote than a future"; where promise comprises a threat, it is the conceptitself of the promise, in its classical definition, that fi n ds itself automatically deconstructed. At last, where Levinas courageously takes it into account, sexual difference can be analyzed here within an expressly dissymmetric space. Its analysis is signed by a masculine signature. There is a resolutely virile point ofview there, or a point ofcontact (contact that touches without touching theuntouchable) , and this discursive privilege in its turn seems untouchable.As a discursive, philosophic, and phenomenological privilege, it is all themore untouchable, unchangeable in that the feminine threatens even theorder of discourse and language: "The feminine is the Other refractory tosociety, member of a dual society, an intimate society, a society withoutlanguage" (Levinas, Totality and Infinity, p. 265) . Indeed, the touchingtouch of the caress is touching (without touching) on the untouchable asinviolable, and the one stroking is always masculine and the stroked one(the untouchable) feminine. Let us be quite specific about these three points and for clarity's sakeproceed as if we could distinguish them, although they are truly indissociable, as the quotations will show. 1 . First, that which seems to extend past the limits of ethics and the face,therefore threatening them, from the side of the feminine. On this side,the voluptuous caress indeed runs the risk of locking things up in secrecy,clandestinity, the asocial, but also in animality. The question of the secretand secrecy is at the center of these analyses, a secret at once, simultane ously, good and bad, untouchable and touched, inviolable and violated, sacred and profane. As we will see, this at once, simultaneously defines profa- The Untouchable, or the Vow ofAbstinence 8I nation itself and equivocation, "the simultaneity o f the clandestine and theexposed" [decouvert] . This equivocation of negation without negativity,which is marked in the analysis by the recurrence of "as if" and "without"(x without x, "essence of this non-essence, " "appears without appearing,"and so forth) , will therefore have been the accepted ambiguity of this discourse with regard to what is called truth, phenomenon, appearing, ontology, and phenomenology. Nothing less. That is what is touched upon, onemight say, without, on the face of it, any semblance of a touch.22 Strokingthought. "Exorbitant ultramateriality," of which we spoke earlier . . . designates the exhibitionist nudity of an exorbitant presence coming as though from farther than the frankness of the face, already profaning and wholly profaned, as if it had forced the interdiction of a secret. The essentially hidden throws itself toward the light, without becoming sign ification. Not noth ingness-but what is not yet. Without this unreality at the threshold of the real offering itself as a possible to be grasped, without the clandestinity de scribing a gnoseological accident that occurs to a being [slightly modified Trans.] . " Being not yet" is not a this or a that; clandestinity exhausts the essence of this non-essence. In the effrontery of its production this clandes tinity avows a nocturnal life not equivalent to a diurnal life simply deprived of light; it is not equivalent to the simple inwardness of a solitary and inward life which would seek expression in order to overcome its repression. It refers to the modesty it has profaned without overcoming. The secret appears without appearing, not because it would appear half-way, or with reservations, or in confusion. The simultaneity of the clandestine and the exposed precisely de fi n es profanation. It appears in equivocation. (Levinas, Totality and Infinity, pp. 256 - 57V'l 2. What announces itself in this way, beyond the future and the possi ble, is also what introduces the threat into the promise. Equivocation, profanation, indecency, indiscretion are not good. And if "To be for the Other is to be good," as Levinas says a little further on, it is indeed evil or wickedness, as the face's beyond, that winds itself into the face itself and the promise of erotic movement, its good movement of love. This does not forbid the promise but makes us call into question again, once more, all the analyses of the promise and its performative virtue. According to these classic analyses and common sense itself, the promise, the perfor mative of the promise, does make the assumption that one will promise only what is good, the good things-and that a promise, in its essence, in its pure signification as promise, be pure and free of any threat. One prom ises to save, or give, to give life first and foremost; one threatens to kill or take away, to take away life first and foremost. According to the good sense of common sense, one should never promise to give and deal out death. I recall this here again,24 in its principle and sketchily, solely to show that, insofar as they are convincing, these analyses comprise a logic that is itself threatening: both for sense and onto-phenomenology, as well as the theory of speech acts (which incidentally takes for granted a whole im plicit or explicit onto-phenomenological axiomatics, and often a philoso phy of intentionality) . wants to avoid doing) , should one favor a dissymmetry, as well as the presumed sexual identity of the signatory? Still another reason for warding off this incredible scene without delay:among so many additional complications, it is necessary to take into account Orphic theology, which makes Eros coming out of the primeval egginto a bisexual being (Phanes-Eros) , a close relative of Aristophanes' androgynous being-which Levinas, let it be noted, incidentally interpretsin his own fashion, in "The Ambiguity of Love," before his "Phenomenology of Eros," when it all begins. He interprets Aristophanes' myth pre- The Untouchable, or the Vow ofAbstinence Aimee, the feminine Beloved (Levinas never, I think, speaks of the Aime, the masculine Beloved) . One can indeed violate her but only to run aground before her inviolability. For this Eros (though some could say that Levinas here only describes the point of view, the desire or fantasy of Eros, his phenomenological fantasy, experience, what appears for him), femininity is only violable, that is, like the secret that it is, inviolable. "Feminine" signifies the locus of this "contradiction" of "formal logic" : vi olable inviolable, touchable untouchable. It is epekeina tes ousias-"be yond being"-but this time, it is not good, it is not the Good: The Beloved, at once graspable but intact in her nudity, beyond object and face and thus beyond the existent, abides in virginity. The feminine essentially·. 1 violable and inviolable, the "Eternal Feminine," is the virgin or an incessant recommencement of virginity, the untouchable in the very contact or volup tuosity, future in the present . . . . The virgin remains unseizable, dying with out murder, swooning, withdrawing into her future, beyond every possible promise to anticipation [slightly modified here-Trans.] . Alongside of the. i night as anonymous rustling of the there is extends the night of the erotic, be hind the night of insomnia the night of the hidden, the clandestine, the mys terious, land of the virgin, simultaneously uncovered by Eros and refusing Eros -another way of saying: profanation. (ibid., pp. 258-59) mit murder. " Indeed, such are the traits of what Levinas tells us "we shallterm femininity." The latter, at least inasmuch as she is the one stroked bythe caress, is neither a thing nor a person, but animality, childhood, ayoung animal, barely a human life, barely even a life, almost the death ofa life ignorant of its death: The caress aims at neither a person nor a thing. It loses itself in a being that dissipates as though into an impersonal dream without will and even without resistance, a passivity, an already animal or infantile anonymity, already en tirely at death. The will of the tender is produced in its evanescence as though rooted in an animality ignorant of its death, immersed in the false security of the elemental, in the infantile not knowing what is happening to it . . . . The tender designates a manner, the manner of standing in the no man's land be tween being and not-yet-being. A manner that does not even signal itself as a signification, that in no way shines forth, that is extinguished and swoons, es sential frailty of the [feminine] Beloved produced as vulnerable and as mortal [slightly modified here-Trans.] . (ibid., p. 259)27 epiphany of the face, a dead woman, desirable still, perhaps, dead andstretched out before Eros: [W]e have sought to expose the epiphany of the face as the origin of exterior ity. . . . exteriority is signifyingness itself. And only the face in its morality is ex terior.. (ibid. , pp. 261-62) The nudity of the principle is the nudity of the face. It can only bethreatened with death by this other nudity, the "mystery" of the "exhibitionist nudity" that "exhibits itself in immodesty" . . . "that is, is profaned."Two nudities: absolutely heterogeneous, and one being the reverse of theother, yet both and each announcing the one through the other and theone beyond the other. Is one straining the point by restricting the traits of this truly hierarchizing discourse to this "masculine civilization," which is precisely inquestion here, which is naturally in question in this analysis of caressing,equivocation, and the "epiphany of the feminine" ? Equivocation constitutes the epiphany of the feminine-at the same time in terlocutor, collaborator and master superiorly intelligent, so often dominating men in the masculine civilization it has entered, and woman having to be treated as a woman, in accordance with rules imprescriptible by civil society. The face, all straightforwardness and frankness, in its feminine epiphany dis simulates allusions, innuendoes. It laughs under the cloak of its own expres sion, without leading to any specific meaning, hinting in the empty air, sig naling the less than nothing. (ibid., p. 264) We are not going far from our "subject," the touching of the untouchable, the caress, the [feminine] Beloved, and the epiphany of the feminine.The social and sexual hierarchy that we have j ust recognized is even toofamiliar for us, but it builds up around the vacuum or solitary vertigo of aradical asociality, and this asociality has its paradoxical place in a "community of feeling," in this "community of sentient and sensed" which isalso a "non-sociality of voluptuosity." The feminine attracts toward separation, far from the social, the universal, far from language. While attracting by starting from voluptuousness as the community of sentient �ndsensed, the feminine does this also in the community of the touching and90 This Is-o/the Other the touched. One will also notice how abruptly one is changing over froma sentence concerning the asociality of lovers (a man and a woman, supposedly) to "the feminine," suddenly, on her own, becoming "the Other" : The relationship established between lovers in voluptuosity, fundamentally re fractory to universalization, is the very contrary of the social relation. It ex cludes the third party, it remains intimacy, dual solitude, closed society, the supremely non-public. The feminine is the Other refractory to society, mem ber of a dual society, an intimate society, a society without language. . . . This solitude does not only deny, does not only forget the world; the common action ofthe sentient and the sensed which voluptuosity accomplishes closes, encloses, seals the society of the couple. The non-sociality of voluptuosity is, positively, the community of sentient and sensed: the other is not only a sensed, but in the sensed is affirmed as sentient, as though one same sentiment were sub stantially common to me and to the other. . . . In voluptuosity the Other is I , and separated from m e [slightly modified here-Trans.] . The separation o f the Other in the midst of this community of feeling constitutes the acuity of vo luptuosity. (ibid. , pp. 264-65)30 which Levinas so often recalls that it already presupposes the face) alreadypertained to the ethical, at the point where one "beyond the possible"stays at a tangent to the other, one in contact with the other, in what remains, as an impossibility, the same impossible? And the same "desire" ? In what describes the caress, for example, in the lines quoted below,how can we not recognize the very structure of ethics? Our hypothesis,then, does not orient us less toward an "already-ethical" of the caress orprofanation than toward a remainder of shame, profanation, treachery,and perjury in the respect of the ethical. In both cases, isn't it tragically thesame caressing experience of two nearly indiscernible "impossibles" or two"unpowers" [impouvoirsJ ? Here again, unsurprisingly-this is the equivocalness of equivocation-everything pivots upon a "without," around itssyntax without negativity. Tenderheartedness of the caress: he gives, extends, and takes pleasure, in one and the same movement-but it is alsoa "suffering without suffering," and first and foremost an "evanescence."Death is still promised there. There is a death threatening the promise,giving to see the mortuary mask in the face beyond the face: [I]n the evanescence and swoon of the tender, the subject does not project itself toward the future of the possible. The not-yet-being is not to be ranked in the same future in which everything I can realize already crowds, scintillating in the light, offering itself to my anticipations and soliciting my powers. The not yet-being is precisely not a possible that would only be more remote than other possibles. The caress does not act, does not grasp possibles . . . . Wholly passion, it is compassion for the passivity [toute passion, elle compatit a fa passivite] , the suffering, the evanescence of the tender. It dies with this death and suffers with this suffering. Tenderheartedness, suffering without suffering, it is consoled al ready, complacent in its suffering [slightly modified here-Trans.] . . . . Volup tuosity does not come to gratify desire; it is this desire itself . . . To discover here means to violate, rather than to disclose a secret. A violation that does not recover from its own audacity-the shame of the profanation lowers the eyes that should have scrutinized the uncovered. The erotic nudity says the inex pressible, but the inexpressible is not separable from this saying . . . . The "say ing," and not only the said, is equivocal. (ibid., pp. 259-60) not; I don't really believe this, not simply, not i n a n instant, not with a lossof memory-but all the same. I therefore return-I turn around, toward Jean-Luc Nancy. Is what hesays about the caress, in his "tactile corpus," compatible with what wehave j ust read? A change of climates or landscapes would not be enoughto prove it. Moreover, what is a climate in philosophy, and what is a landscape? What about the pathos-declared or not-of a discourse? Whatabout the scene of the signature that gives rise to it, in this place I j usttermed "landscape" ? Does this resist analysis? Is there anything else to analyze, finally-and what could be more interesting? Furthermore, theremay be a religious fund that the two thinkers share in more ways thanwould at first seem. Levinas sometimes plays a game (he did it right beforeme) : he plays at confessing a Catholicism that Nancy, for his part, seriously disclaims. "Tenderheartedness," says Levinas, and the tender: extending privilegesto tenderheartedness and speaking of the "tender" as an original categoryimplies putting the accent in love2 and the erotic (in "The Ambiguity ofLove" and the "Phenomenology of Eros") on a movement toward appeasement, a moment of peace, and a disarming, which insistently reaches intothe violence of a violation-moreover impossible, the [feminine] Beloved'svirginity remaining "inviolable" -or the violence of unfailing profanation.Levinas almost always says "tender" and "tenderheartedness," rarely (infact, never, it seems to me) "tenderness." This may be because what he describes is less a shared state or feeling (such as the "ambiguity of love," forexample) than an eidos (the invariant of the tender or the becomingtender) , the essential and ideal quality of an intentional experience, readable right on the other, or in me as other. One seeks this disarming andthis peace (peace is the ethical itself for Levinas) more in the tender of thecaress, where the caress would renounce possession, than in any erotic violence pushing tooth and naif to achieve pleasure [acharnee a jouir] . Thecaress does not set upon anything tooth and nail. It is tender in that it doesnot push to take anything. It won't even let itself be pushed by the flesh.Rather, it tends to give, extend, tender forth the tender: "Tiens," hold,take what I do not possess, nor you, what we do not and shall never possess. This will not be properly our own; of this, we shall never be the masters and owners. Gift or offering? Let us not play with words-ever. Let us not place any bets on thehomonymy, in French, between tendre and tendre, on the relations be-94 This Is-o/the Other tween, on the one hand, the immense semantic network and all the properly intentional senses of the verb tendre: in the dominant tradition inFrench, it connotes rather oriented activities, perhaps even virility (Latin,tendere, French, tendre: to tend, to hold out, to tender, to extend, to stretch,to lay out, to set up [dresser] , to hold out one's hand or to set up a trap andattend to it, to give or to ensnare, to orient oneself toward, to intend to, intentionally to seek, and so forth) ; and on the other hand, the instance ofthe attribute tendre: the latter often connotes fragility, delicacy, a rather passive vulnerability that is nonintentional, exposed, and rather childlike orfeminine in the same dominant tradition of its privileged figures. Thus, inextending privileges to the caress, Levinas no doubt put the accent uponthe tender of the [feminine] Beloved. But in opening it up onto peace (animpossible peace, at any rate-beyond the possible) , he also implied thegift or offering of that which tends or extends, or tends to hold out to theother. With the chance of quasi-homonymy, the haunting of the tendercomes back, in an essential, irreducible, and necessary fashion, to visit theother. The other, the tender-extend her, extend him. The proof of thetender is only in tending.3 or get a grip on him- or herself, but also, in receiving and accepting it,that the other keep what one extends to him or her. Saying "Tiens!," signifying "Tiens!" means holding out or extending, and giving to "touch."One is suggesting that the other take the gift of an offering for example,and receive and accept it, and thus touch it by taking it on, by taking it inhim- or herself, by keeping it in or near oneself-as nearly as possible, inoneself or within reach of the hand. Touch, more than sight or hearing,gives nearness, proximity-it gives nearby. And if the two other senses,tasting and smelling, do this also, it is no doubt because of their affinitywith touching, because they partake in it or lie near it, precisely, near thesense of nearness, proximity. In this regard, is it ever possible to dissociatethe "near," the "proximate" [proche] from the "proper," the "propriate"[propre] ? The proximate, the proper, and the present-the presence of thepresent? We can imagine all the consequences if this were impossible. Thisquestion will no longer leave us, even if it is in silence that we leave it todo its work. In it, the shares and dividing lines are announced, even if theycannot always be decided . . . . If one begs the other to take in the gift of an offering, and therefore totouch it by taking it on, by keeping it in or near oneself, in the closest possible proximity, in oneself or within reach of one's hand, it is because, as always (irresistible tendency) one thinks first of all, and too much, abouthands, that is, about the manual, the manner, maneuver, or manipulation:seizure, comprehension, prehension, captation, acceptation, reception-aplea [priere] that something be received that begins to seem like an order:"Tiens!" do take it, do touch. Hence, this "tender extending" may sometimes become violence itself-not even to mention the striking twist [coup]in the language that displaces the "Tiens!" (Take this!) of a gift to the"Tiens!" (Take that!) of a blow [coup] : "Tiens!" "Take that!" one sometimessays when dealing a blow-for, in French, a blow is also dealt, that is,given: one gives the blows one strikes. But this gift is not a present, then; itshouldn't be-so one thinks, at least-and an offering even less. Nancy distinguishes between offering and gift, or rather the offering inthe gift. A gift is an offering when at the heart of the donation of the giftthere is a "withdrawal of the gift," the "withdrawal of its being-present."4 "Tiens!" Fittingly, it is on the subject of "The Sublime Offering" thatNancy enjoins the incredible. He lets himself be enjoined-but he seemsto hold to this-to "change sense," no less! This gesture looks like him: I know Jean-Luc Nancy to be always ready This Is-ofthe Other for everything, resolved to change everything, even sense, and more than anyone else, he still, always, even should he be the last one still doing it, talks sense, of sense in all the senses of the word sense, which does not pre vent his corpus from remaining consistent and powerfully faithful to itself. And he is working on a book to be tided Ie sens du monde (The Sense ofthe World), no less!5 Now, in the aftermath, and after a few earlier allusions to this, isn't this the place to risk proffering the "periodization" hypothesis that is guiding us? It is worth whatever it is worth, it is nothing but a hypothesis, it is worth whatever such periodizations are worth. Certainly, there is no cutting, in divisible limit; there is no simple instant or agency between a before and an after wherever, with the nonlinear duration of a process, thinking-weighing pondering, language and the "body," and the exscribed, come about. All af tereffects discreetly refer back to a few premises, a past from before the markable beginning; to find them announced, it suffices to sharpen one's reading. However, I wonder whether it may not be toward the end of the,I 1980s that touch touched down in Nancy's thinking and writing, let's say in an increasingly phenomenal way, increasingly less evitable-until the early 1990S, when touch invaded his lexicon by way of eva), rhetorical or logical mode. Let me repeat that none of this can have started just out of the blue, one fine-or bad-day. To be sure, some precursory signs were already there very early on. But it was between 1985 and 1991 (approximately pending a more fine-grained statistical analysis) that the corpus was more than touched upon: it was summoned, almost violated, penetrated, domi nated, by the operation that came to inscribe some "touching" at the heart of all writing. The operation in question did not take place in one single day, to be sure, at a particular hour, and if it did take place one day, it had a whole history preceding and following it, a history that is older than the body and thinking ofJean-Luc Nancy, as he said himself I have purposely just used the general term "operation." The operation of which I am speaking is contemporaneous with what is called a surg ical - one [surgery: Greek cheirourgia, from cheir (hand) and ergon (work)] , done by hand, the hand of the other, and thus by touching, even if, as always, machines and technology are indispensable in this. (And in the following chapters, it is the thinking of a techne of bodies as thinking of the pros thetic supplement that will mark the greatest difference, it seems to me, Tender 97 "I I") when it speaks [senonce] : "I am suffering" implies that there are two = ''1's,'' each one foreign to the other (yet touching) . So it is with "I am in ec stasy" [jejouis] . . in "I am suffering," one ''1'' rejects the other "I," while in "I . am in ecstasy" one ''1'' exceeds the other. The two resemble each other, doubt less like birds of a feather [comme deux gouttes deau] , neither more nor less.8 A. First, let us note that, mutatis mutandis-if this may still be said atsuch a gaping distance-this passing from sight to tact here again recallsBerkeley. In truth I never stop thinking of him while writing about touch,even if I cannot possibly here do justice to the fine complexity of his problematic. But out of its context a sentence such as "one must . . . pass fromsight to tact" could belong to the Berkeleyan axiomatics that began with therejection of any identity between a seen object and a touched object. Oneneeds to leap from one to the other blindly, like someone born blind, acrossan infinite abyss. Even if it is the "same thing," what we see is one thing,what we touch is another, says Berkeley in An Essay Towards a New Theoryof Vision (section 127) (in a prephenomenological style: an already phenomenological style, already with a certain reduction, and still at the threshold ofthis reduction) : "The extension, figures, and motions perceived by sight areI Tender 99 specifically distinct from the ideas of touch called by the same names, nor is there any such thing as one idea or kind of idea common to both senses. " 12 Later on, these different objects will go by the same names, and thus, what Berkeley mobilizes to account for this is the whole question of lan guage, its use and destination, and the question of theology ("the proper objects of vision constitute an universal language of the Author of Na ture") . 13 And that is the ultimate recourse grounding his philosophy. What this interpretation of the senses presupposes-and first of all of touch, of the haptical, that is, the least reducible among them, common to all living beings in the world, which is not the case with vision-lastly is a theology, and more precisely an ontotheology. But beyond so many obvious differences, a common gesture of thought takes into account the heterogeneity between the two senses, the two "phenomenologies of per ception" that are dedicated to them, as well as a certain primacy granted to touch. If the ideas of space, distance, and therefore movement could not come from vision, as Berkeley tirelessly repeats and Nancy also seems to imply, then the figure of the limit, the approach of and to a limit, the "presentation of a limit" must push us, as Nancy says, indeed, to "pass from sight to tact. " In addition, Berkeley often argues that the physical mechanisms of vision, "retina, crystalline, pupil, rays" traveling through it, and so forth, "are things altogether of a tangible nature." 1 4 The remaining task (is it a task for today?) is to try to account for the "same names," common, for example, to both the visible and the tangible; almost, here, at the limit visible and tangible. The remaining endeavor is to follow their genealogy starting from another discourse altogether, an other "knowledge" altogether, a knowledge less confi d ent in its thinking of "common sense," or the fivefold root of the senses-in a body with five senses, no more, no less-without at once calling on God for help. A "de construction of Christianity," we can bet, will have to do battle between the visible and the tangible-and seek something else. 1 5 I . Jesus the savior is "touching," he is the One who touches, and mostoften with his hand, and most often in order to purify, heal, or resuscitate-save, in a word. He heals or purifies the leper by touching him: "And he stretched outhis hand and touched him, saying [et extendens Iesus manum, tetigit eum,dicens . . I kai ekteinas ten cheira epsato autou legon] , 'I wish it; be clean.' . they brought t o him a man who was deaf and had a n impediment i n hisspeech; and they besought him to lay his hand upon him. And taking himaside from the multitude privately, he put his fi n gers into his ears, and hespat and touched his tongue [tetigit linguam eius I epsato tes glosses autou] ;and looking up to heaven, he sighed, and said to him, 'Ephphatha,' thatis, ' Be opened.' And his ears were opened, his tongue was released [vinculum linguaeldesmos tes glosses] , and he spoke plainly. And he charged themto tell no one; but the more he charged them, the more zealously theyproclaimed it" (Mark 7: 32-36 ) . 1 9 Touching a coffin, the coffin of the only son of a widow, he cures deathitself. There again all begins with heartfelt mercy [misericorde] . Jesus istouched to the heart before he touches: ''And when the Lord saw her, hehad compassion on her [misericordia motuslesplagchnisthe] and said to her,'Do not weep. ' And he came and touched the bier, and the bearers stoodstill. And he said, 'Young man, I say to you, arise. ' And the dead man satup, and began to speak. And he gave him to his mother" (Luke 7: 1 3 -15) . Restoring life, restoring or giving speech in touching the child: thoseare reminders that these are first, or frequently, children (vulnerable, disarmed, innocent, and still without true speech) whom Jesus touches orwho are offered to Jesus's touch: "Now they were bringing even infants tohim that he might touch them; and when the disciples saw it, they rebuked them. But Jesus called them to him, saying, 'Let the children cometo me, and do not hinder them; for to such belongs the kingdom of God.Truly, I say to you, whoever does not receive the kingdom of God like achild shall not enter it" (Luke 18: 1 5-1 7) . 2 . Not only is Jesus touching, being the Toucher, h e is also the Touchedone, and not only first in the sense that we have just identified (that is,touched in his heart by heartfelt, merciful compassion) : he is there as wellfor the touching; he can and must be touched. This is the condition for salvation-so as to be safe and sound, accede to immunity, touching, theToucher, Him. Or better yet, touching, without touching, that whichwould come in contact with his body, namely-like a fetish, or the originof fetishism-his garment, his cloak. It is not the touch that is saving,then, but the faith that this touch signifies and attests. ''And besought himthat they might only touch the fringe of his garment; and as many astouched it were made well [safe] [et quicumque tetigerunt, salvi facti suntlkai osoi epsanto diesothesan]" (Matt. 1 4 : 3 6 ) . For he had healed "many, so10 2 This Is-ofthe Other that all who had diseases pressed upon him to touch him" (Mark 3 :10) . . . . ''And there was a woman who had had a flow of blood for twelveyears . . . . She had heard the reports about Jesus, and came up behind himin the crowd and touched his garment. For she said, 'If I touch even hisgarments, I shall be made well [saved] .' And immediately the hemorrhageceased . . . . And Jesus, perceiving in himself that power [virtutem / dunamin] had gone forth from him, immediately turned about in the crowd,and said, 'Who touched my garments?' . . . the woman . . . told him thewhole truth. And he said to her, 'Daughter, your faith has made you well[saved] . ' " Shortly afterward, Jesus saves a little girl who had died andmakes her stand up, holding her by "the hand" (Mark 5: 25-34, 41) . 20 ''Andwherever he came, in villages, cities, or country, they laid the sick in themarket places, and besought him that they might touch even the fringe ofhis garment; and as many as touched it were made well" (Mark 6: 56). ''Andall the crowd sought to touch him, for power came forth from him andhealed them all" (Luke 6: 19) . The faithless Pharisees themselves recognize the power that emanatesfrom this "touch." In the overwhelming scene that the sinner Mary Magdalene opens up when she bathes Jesus's feet with her tears, wipes themwith her hair, kisses them or anoints them with perfume, the Pharisee hostdeclares: "'If this man were a prophet, he would have known who andwhat sort of woman this is who is touching him, for she is a sinner. ' "(Luke 7 : 36-50) . 2 1 I t seems that these literal allusions t o touching are rarer or even absentin the Gospel according to John. Why? On the other hand, if one may sayso, Jesus becomes momentarily untouchable; and John is the one whogives a report of the "Touch me not" (noli me tangere/Me haptou mou) intended for Mary Magdalene at the moment when she is still in tears, nextto the grave, and has just recognized him ("Rabboni!" "Master!") : "Donot hold me [touch me not] ,22 for I have not yet ascended to the Father;but go to my brethren and say to them, I am ascending to my Father andyour Father, to my God and your God." In the evening of this same day,when Jesus has come and the disciples rejoice upon seeing him, ThomasDidymus is not among them. And so he doubts their testimony: "UnlessI see in his hands the print of the nails, and place my finger in the markof the nails, and place my hand in his side, I will not believe." Eight dayslater Jesus says to Thomas: "Put your finger here, and see my hands; andput out your hand, and place it in my side; do not be faithless, but be-f Tender r0 3 lieving. Thomas answered him, 'My Lord and my God!' Jesus said to him, 'Have you believed because you have seen me? Blessed are those who have not seen and yet believe'" (John 20: r6-29) .23 Nancy almost literally repeats this formula on the next page, and I'll cite it. There is thus, apparently, a figure oftouch there, for philosophy, literally, has never touched anything. Above all, nobody, no body, no body proper has ever touched-with a hand or through skin contact-something as abstract as a limit. Inversely, however, and that is the destiny of this figu rality, all one ever does touch is a limit. To touch is to touch a limit, a sur face, a border, an outline. Even if one touches an inside, "inside" of any thing whatsoever, one does it following the point, the line or surface, the borderline of a spatiality exposed to the outside, offered-precisely-on its running border, offered to contact. In addition, here in the case of this figure ("philosophy has touched the limit of the ontology of subjectivity," and so forth) , another need comes to light as far as this figure is concerned, throughout the chain of a remarkable demonstration whose stages I can not reconstruct here.26 This surface, line or point, this limit, therefore, which philosophy might have "touched" this way, finds itself to be at the same time touchable and untouchable: it is as is every limit, certainly, but also well-nigh at and to the limit, and on the exposed, or exposing, edge of10 4 This Is-ofthe Other way that thinking definitely keeps its place in the world of our most concrete and living relations, of our most urgent and serious decisions.27 It is for two reasons that I quote this conclusion of the chapter in full. 1. One may ask oneself what could j ustify this parenthetical concessionhere: " (that is, the human being [l'h omme, i.e., man] ) . " It does not seemsustainable except where one transfers onto this name (of) man (but whythis name, then? Or why not? In both cases, it seems arbitrary or merelyj ustifiable through some pedagogical or strategic calculation) the excess,the overflowing, and so forth, which will come into question immediatelyafterward; and thereby one admits that one presently does not know whatthe term "man" means to say, if not this experience of the excess of all de- Tender 105 comes onto that which it cannot touch, and thereby it touches itself, as weshall see; it feels itself (powerless) there where it touches (tangentially) whatit cannot attain or touch: the point or the line, the flimsy, unsubstantiallimit, here, there, whither and whence it can no longer touch. The imagination attains a limit, reaches a shore whither it can come only in not coming about. It thus tends toward that which it can only hold out to itselfwithout giving itself to hold, and still without touching; whereby it becomeswhat it is by essence, imagination, possibility of the impossible, possibilitywithout power, possibility auto-affecting its essence of a nonessence. It isnot what it is-the imagination. It is touched, in a movement of withdrawing or re-treating to the fold, at the moment it touches the untouchable. The imagination confines without confining itself to itself. In what sense and by what right can one say that it touches itself or thatit feels itself touch, touched, touching, that it feels itself by touch or bytouching itself? (Note parenthetically that, concerning what touches onthe French language at least, where the latter touches itself closest to untranslatability, "cela se touche" can mean or be understood reflexively as either "it itself touches itself" or "one touches it, it lets itself be touched [bysomething or someone else] without necessarily touching itself") Andwhat is the phenomenological, ontological status, the logical or rhetoricallegitimacy of that which we cannot without trepidation call the figure of"touch"? And what if this word, touching, Ie toucher, then became uselessand unusable, and fell into disuse, in advance im-pertinent, and at thesame time contingent, therefore, and not pertinent-incapable of "touching" the very thing itself that it comes to "touch" by accident, without anynecessity whatsoever, simply through contiguity, the very thing that it pretends to aim at? And what if this word did not keep any value, or sense,precisely, anyjustification, except where a solely ontophenomenological status-in an absolutely empirical fashion and "in our eyes," solely loaded withverbal memory and logico-rhetorical culture-were what reassures us inthe confident use of such a term? And so it is our very old habit in this orthat historical culture, "at home" in the West, to make use of these terms(the "logic" and "arithmetic" of the five senses, and so forth) so as to adj ustthem more or less well (and often not very well at all, as we are experiencing it here, and that is all of philosophy) to suit some pretended ontophenomenological evidence in "our body." Empirical ontophenomenology+ historical legacy + language of a culture: perhaps this makes a common -And in an aside you tell yourself: what a funny, admiring, and grate ful salutation you're addressing to him, to Jean-Luc Nancy. What a pecu liar way to pretend you're touching him while acting as if from now on you wanted to put his lexicon about touch out of service, or even banish it to the Index librorum prohibitorum. Or, as if you stubbornly kept re minding us that it should always have been out of service already, even if we like that-touching-precisely when it's impossible-prohibited; and we even love to call this loving-abstaining. Like the messiah. What a funny present, indeed! What an offering! Altogether as if at the moment of calling others so that they will become ecstatic before this great work and this immense philosophic treatise of touch, you whispered in his ear: "Now, Jean-Luc, that's quite enough, stop touching and tampering with this word, it's prohibited, you hear. You have to abstain from this 'touch ing,' and once and for all stop using this incredible vocabulary, this con cept nothing can really vouch for, these figures without figure and there fore without credit. And besides, if I may remind you of this again, haven't you yourself said 'there is no "the" sense of touch' ? Therefore, don't keep pretending, don't make believe, stop acting as if you wanted to make us believe that there is something one could call the touch, an understood 'thing itself' about which we could pretend to agree, there where, in touch ing upon the untouchable, this thing remains untouchable. Knowing you, I don't think this objection will stop you, I tell myself. No, you just go on, and so do I-thankfully in your steps." The emphasis is mine, of course. Before quoting the next few lines, letus already and very tersely point to three essential indications. comprises the perception of a figure but rather the arrival at the limit. More precisely, sensibility is here to be situated in the imagination's sentiment of itself when it touches its limit. The imagination feels itself passing to the limit. It feels itself, and it has the feeling of the sublime in its "effort" (Bestrebung), im pulse, or tension, which makes itself felt as such when the limit is touched, in the suspension of the impulse, the broken tension, the fainting or fading of a syncopation.32 IIIII2 This Is-ofthe Other interruptions will not always be obvious and easily accessible. We shall apply ourselves to analyzing them, at the point that is nearest or most "proximate" to the former and the latter, and that is where the "logic" of the syncope will play a determining part, under this name or another. If tact and the caress cannot be given their measure or their law in a"more or less" of touch, then perhaps they have nothing to do [rien a voir]with the experience of touching and all the figures that it has procured forus. One would have to review everything in this lexicon and this rhetoricand take infinite precautions before touching on them. For example, whatis one saying when one proposes [in French] to toucher un mot [literally"to touch a word," colloquially to have a word with, to mention] ? What isone doing then? What is one intent on doing by "having a word" andtouching one's friend with it, for example on the subject of this or that,which might be touch, touching him or her, or quite simply a word, butfor example the word "touching" ? To friends we speak and in them weconfide-briefly, elliptically, closely-so as to inform them, no doubt, tohave a word with them and "touch on it"; often, however, in order towarn them, to put them on their guard, alert them ("Get in touch withhim? Oh yes. I'll have a word with him and touch on this, should the opportunity arise, to find out what he thinks of this, and by the same tokenI'll tell him, in a word, how I see the matter at hand-I myself, so as toavoid saying foolish things, and also, as a reminder, to recall a little of thisenormous memory, the stuffed belly of a library of touch.") . How is one tohave a word and touch on it? And let oneself be touched by it? A visible,audible, readable word? We have long been struggling between the tactileand vision, the eye that does not touch and the eye that touches, like a finger or lips. It is about time to speak of the voice that touches-always ata distance, like the eye-and the telephonic caress, if not the (striking)phone call. (Imagine: lovers separated for life. Wherever they may find themselvesand each other. On the phone, through their voices and their inflection,timbre, and accent, through elevations and interruptions in the breathing,across moments of silence, they foster all the differences necessary to arousea sight, touch, and even smell-so many caresses, to reach the ecstatic climax from which they are forever weaned-but are never deprived. Theyknow that they will never find ecstasy again, ever-other than across thecordless cord of these entwined voices. A tragedy. But intertwined, theyalso know themselves, at times only through the memory they keep of it, Nothing to Do in Sight I I3 not speak-to have a word with a friend, for example, to touch on a matter with him or her-if this auto-affection of a mouth, this contact interrupted and repeated between the lips, the tongue, the palate, and so forth,did not impart speech. We must have a mouth for laughs and for laughing. Surely, we canlaugh with our eyes, but it is difficult (even if it is not impossible) to imagine a living being laughing without something like an opening other thanthe eyes. The opening in question may be presently visible and significantin the burst of laughter, or it may not; it is indispensable. For laughter asfor so many other things, more than one opening is needed. That is also why "Laughter, Presence" lets us read "the laughter of a widemouth, red and white and alluring . . . " in Charles Baudelaire's "The Desire to Paint." Now, this syncopated beat all at once scans a limit, an endurance of the limit, and an experience of tact, of touching without touching as "art"-not art in its manifest essence, in its presence, but preciselyin the multiple bursting of singularities. Though laughter may be "the substance," or even the "subject" of art, it also makes the essence of art, and ofeach of the arts, disappear. This time, Nancy puts the "asllike" [comme]which generally announces the presentation of an essence and an "as such"-at the service of a bursting diffraction, explosion, dispersion, and disappearing. But let us not forget that he also speaks, and justly so, with thissense of justice that respects absolute singularity, with a view to keeping insight this text by Baudelaire, solely this one, rather than any other: Laughter of infinite mockery, of derision, and irony: the subject of art sees it self there as what bursts, explodes, is consumed, and disappears. But also, the laughter and smile of an "inexpressible grace," of the grace with which "art" slips away, and each art disappears into another only to bloom there again, a superb flower but impossible to recognize, to relate to its model-on the vol canic soil where there is never anything like art, where all essence is petrified.3 Nancy draws the consequences of this bursting of the laugh and is respectful of these multiplicities, which philosophy, the philosophy of art inparticular, always seeks to "sublate, or to sublimate." He thus works out thelogic of these multiple singularities, which are as many instances of "coming" into presence without presence ever presenting itself as the essence ofthe presence. "Multiple singularities": and so one can read these pages in Une pensee jinie in 1990 [and The Birth to Presence in I993-Trans.] . Yearslater, he will speak of being singular plural 4 Nothing to Do in Sight II5 So be it. But how can he say that we are "properly . . . exposed" to an origin that is not "appropriable"? I'll have to ask him this. Just as I ask myselfwhy I would never have dared write that. He knows in advance that I wouldundoubtedly put up a muted resistance there-fear, perhaps, in the guise ofstiffness or philosophical rigor-against this frank assertion, this assuranceregarding the properness of an exposition to the origin: to wit, an existence,a form of "self-touching," would (itself) be properly exposed, according tohim, to what is "properly" the origin (itself) , even if the latter were not "appropriable," in the sense of "penetrable, absorbable." But what about othermodes of appropriation? And couldn't one still detect in the said exposition-proper to an origin that would properly be itself-a reserve, the ultimate resource of an appropriation? Of a reappropriation? The possibility ofthis affirmative statement ("To touch upon the origin . . . is properly to beexposed to it")-a statement that is possible for him, and not for me-maybe what inspires, motivates, dictates, and compels the thinking and desireof "touching," and especially so when one can see this thinking and this desire of "touching" invade his corpus in an increasingly speedy and intensefashion, be it with so much caution, across so many complications, paradoxes, and hyperboles; be it in the abnegation, without negation, of touching within the "without touching"; and be it through the active or implicitreading of other thinkers. And this is how I further explain, without seeking too much to justify a virtual question or objection (it does not matterhere) , that the figure and lexicon of "touch" remain rather scant as far as Iam concerned, at least on the rare occasions when, as it were, I speak in myown name. That is why those who have this easier "touch" fascinate me. Iadmire them, yet I cannot bring myself to believe in it very much-intouching, that is. Some ill-intentioned though well-programmed philosophers may conclude from this that I am more of an "idealist" than Nancy. My defense attorney would not be long in responding, playing up twoco un terclaims: I. What has conferred on "touch" its absolute privilege and its titles ofphilosophic nobility is a great "idealistic" tradition, from Berkeley's absoluteidealism to Kant's or Husserl's transcendental idealism. Plato had alreadystarted this (as we'll later see) . 2. As for idealists, isn't Nancy just another one, guilty rather because ofhis imprudence when he still credits the appropriation of a properness andwhen he quietly says: "To touch upon the origin is not to miss it: it is properly to be exposed to it"? Nothing to Do in Sight gin . . . is properly to be exposed to it. " The lexicon of touch, the underscoring, bears Nancy's signature, of course, and not Bataille's. The insistence-so irrepressible-on a certain exactitude once more ("exact," "exactly": he even boldly writes "perhaps, exactly") is signed by Nancy as well.The movement finds itself launched, then relaunched, in an impeccablycalculated play on the equivocal syntax of an expression of truth, it fa verite (a phrase remaining forever French, as if a tongue could be touched untranslatably-and on the following page Nancy evokes a certain "untranslatable" forming "each time, an absolute point of translation, transmission,or transition of the origin into origin") : . . . being- with. The origin is together with other origins, originally parted. In truth, therefore, we accede to it. We reach [nous accedons] , in exact accordance with the mode of access: we get there; we are on the brink, as near as can be, at the threshold; we touch on the origin [Nancy's emphasis.-J. D.] . "In truth, we accede . . . " [a la verite, nous accedons] is Bataille's phrase,6 and I repeat its ambiguity while diverting it from its reach-since in Bataille it precedes the assertion of an instantaneous loss of access. Everything comes to pass, perhaps, exactly between loss and appropriation-neither one nor the other, nor one and the other, but much more bizarrely and simply than that. In truth, my memory fails me: Bataille writes "we attain" [nous atteignons] : to attain, to accede-like the doubling of the approximate itself in touching at the origin. But I must cite the whole passage from Bataille: "We don't have the means of attaining at our disposal: in truth, we do attain; we suddenly at tain the necessary point and we spend the rest of our lives seeking a lost mo ment; but how often we miss it, for the precise reason that seeking it diverts us from it. Joining together is doubtless a means . . . of missing the moment of return forever. Suddenly, in my darkness, in my solitude, anguish gives way to conviction: it's insidious [sournois] , no longer even wrenching [arrachant] (through constant wrenching, it no longer wrenches) , suddenly B. s heart is in my heart. " (Nancy, Being Singular Plural, p. 13; p. 196m7; modified.-Trans.) tion o f the immortal soul with everything that i t touches o r attains (haptetai) in its love for truth-"philosophy" itself. It is a great, endless history of haptics. If together with Pascal one wereto imagine "Plato, to attract towards Christianity, " l O one of the paths ofthe demonstration would go not only (and self-evidently, and all too obviously) through a thinking of truth as light, as revelation to sight, butalso through the affinity of two haptics, two haptologies, the one in theGospels, of which we spoke earlier, and the one of which a few examplesin Plato have j ust been evoked. From Plato to Henri Bergson, from Berkeley or Maine de Biran toHusser!, and beyond them, the same ongoing formal constraint is carriedout: certainly there is the well-known hegemony of eidetics, as figure or aspect, and therefore as visible form exposed to a disembodied, incorporeallook. But this supremacy itself does not obey the eye except to the extentthat a haptical intuitionism comes to fulfill it, fill it, and still the intentional movement of desire, as a desire for presence. For desire, of course,is of itself naturally intuition istic-as soon as it is weaned of intuition;and that is its first lethal contradiction and the precursory sign of its end,its telos. Telos is haptico-intuitionistic. Shall we say of philosophy in general that it is obediently under the thumb of the finger and the eye? For,as the Republic spells it out, what is at issue here is philosophy itself and thedesire of pure psuche. We could trace the necessity and speak of the legacy of an analogousmovement in Plotinus, who uses haptical terms both abundantly and decisively (epaphe: contact; ephapsasthai; ephapteta: touch; to be in contact;thigein: to touch; thixis: a touch, and so forth) . First, touching yields presence: the One "is always present to anyone who is able to touch it." l l Correlatively, this comes down to the indivisibility of the One and psychical experience, the relation of the knowing soul with the indivisible, for the soulagrees with the One, it is in contact with it, as it were, and touches it; l2and with what is wholly simple, "it is enough if the intellect comes intocontact with it."l3 This contact is more extraordinary, more hyperbolichyperbolic as epekeina tes ousias (which is the hyphen, so to speak, betweenPlato and Plotinus)-and touches what exactly [cela meme] stands beyondBeing, the One as the Good, thus bringing it into presence: "there will notbe a thought of it, but only a touching and a sort of contact. "l4 We couldthen touch what is not! Which is to say, not only intelligible beings-beyond the senses-but also what does not even present itself any longer as122 This Is-ofthe Other And so, at the moment when he tells of this convergence and this limitpoint of intuition itself, something he will so often term "coincidence" (aswill Merleau-Ponty after him) , Bergson is still hierarchizing. And then(shall we say, as Plato does?) he subjects vision to contact. Incidence can define the angle of a thing or a look, a ray of light striking a surface; whereascoincidence calls for an experience involving contact. When vision tendsno longer to distinguish itself from the seen or the visible, it is as ifthe eyetouched the thing itself-or better yet, in the event of this encounter, asif the eye let itself be touched by it. Intuitive vision does not j ust comeinto contact, as it is said; it becomes contact, and this movement wouldpertain to its nature. And further, its motion would go-its drive would extend, rather, from the optical (or the scopical) to the haptical. Thus, forexample: "The intuition . . . then bears above all upon internal duration.It grasps a succession which is not j uxtaposition . . . . It is the direct visionof the mind by the mind . . . . Intuition, then, signifies first of all consciousness, but immediate consciousness, a vision which is scarcely distinguishable from the object seen, a knowledge which is contact and evencoincidence. " 1 8 We know that this becoming-haptical of the optical is one of thethemes of Gilles Deleuze's and Felix Guattari's A Thousand Plateaus, evenif the Bergsonian streak (to which Deleuze always laid a claim, incidentally) is not central in this context. Reference is especially made to HenriMaldiney and Alois Riegl: "It was Alois Riegl who, in some marvelouspages, gave fundamental aesthetic status to the couple, close vision-hapticspace."19 "Where there is close vision, space is not visual, or rather the eyeitself has a haptic, nonoptical function. "20 The hand is not far, there again-or more exactly thefinger ofthe hand.The finger is not far, in fact, since this even deals with the "close range,"with "close vision," and as in Bergson, as we just read, with the mind, thevery mind. About nomad space or art we read: " [T]he whole and the partsgive the eye that beholds them a function that is haptic rather than optical.This is an animality that can be seen only by touching it with one's mind,but without the mind becoming a finger, not even by way ofthe eye. (In amuch cruder fashion, the kaleidoscope has exactly the same function: togive the eye a digital function.)"21 Who better than Helene Cixous, as near as can be to her own experience,will have written, and described, the poem for this figure of the touching1 24 This Is-ofthe Other eye? Touching with the hand and lips-but as figure of the figure, precisely, and without letting us believe that a philosophical concept could literally, properly, measure up to it? In Cixous's "Savoir"-as well as elsewhere and differently, in so many places-what is given to see is given totouch, though henceforth, from the outset, it is given to read.22 This thinghappens after a surgical, that is, handmade, operation that has just restoredHelene Cixous's eyesight, just as another surgery had given another heart,the heart of another, male or female, to Jean-Luc Nancy-and so I associate my two miracle wonderfriends.23 I have quoted from his L'intrus;here, now, is her "Savoir": But at this dawn without subterfuge she had seen the world with her own eyes, without intermediary, with the non-contact lenses. The continuity of her flesh and the world's flesh, touch then, was love, and that was the miracle, giv ing. Ah! She hadn't realized the day before that eyes are miraculous hands, had never enjoyed the delicate tact of the cornea, the eyelashes, the most powerful hands, these hands that touch imponderably near and far-off heres. She had not realized that eyes are lips on the lips of God. She had just touched the world with her eye, and she thought: "�t is I who can see. " I would thus be my eyes. I the encounter, the meeting point between my seeing soul and you? Violent gentleness, brusque apparition, lifting eyelids and: the world is given to her in the hand of her eyes. And what was given to her that first day was the gift itself, giving. (Cixous, Veils, p. 9)24 Because of the proximity value, because this vector of close presence finally determines the concept and term "haptic," because the haptical virtually covers all the senses wherever they appropriate a proximity, Deleuzeand Guattari prefer the word "haptic" to the word "tactile": "'Haptic' is abetter word than 'tactile' since it does not establish an opposition betweentwo sense organs but rather invites the assumption that the eye itself mayfulfill this nonoptical function . . . . It seems to us that the Smooth is boththe object of a close vision par excellence and the element of a hapticspace (which may be as much visual or auditory as tactile) ." 25 What makes the haptical, thus interpreted, cling to closeness; whatidentifies it with the approach of the proximate (not only with "close vision" but any approach, in every sense and for all the senses, and beyondtouch) ; what makes it keep up with the appropriation of the proximate, isa continuistic postulation. And this continuism of desire accords this wholediscourse with the general motif of what Deleuze and Guattari (in follow- Nothing to Do in Sight I25 ing Antonin Artaud) claim as the "body without organs. " Consequently,it is in the "smooth" and not the "striated" space that this haptical continuism finds, or rather seeks its element of appropriation, and it is there thatit confirms and smoothes out its logic of approach: "The first aspect of thehaptic, smooth space of close vision is that its orientations, landmarks,and linkages are in continuous variation; it operates step by step [de procheen proche] . " 26 I said continuistic postulation-for the continuous is never given. Thereis never any pure, immediate experience of the continuous, nor of closeness,nor of absolute proximity, nor of pure indifferentiation-no more than ofthe "smooth," or therefore of the "body without organs. " Of all that, thereis never any "immediate" given. Where has experience ever encountered(perceived, seen, touched, heard, tasted, felt) the purely smooth? Or some"body without organs," Artaud's great fantasy, his metaphysical and nodoubt Christian fantasy? If one has never met them, if this has never givenrise to an event or an experience, if this has never come or happened, doesthis then give us a contingent fact? And would this fact preclude neitherthe right of concept nor the right of desire? Or on the contrary, is this anessential phenomenological impossibility, an eidetic law of experience andevent, a very condition of desire, which any conceptual construction-any"concept" "creation," as it were-should take into account? And thus every"philosophy," even if this acknowledgment counters an ineradicable intuitionism constituting the regulating idea of philosophy itself (as I suggestedearlier) ? A "deconstruction" begins in this very experience; it is, makes, andbears out the experience and experiment of this aporia. The concept of smooth is not smooth-no more than there is any rigorous concept of the haptical here, for the haptical then depends on thesmooth, in a correlative, determining fashion. The relation between smoothand striated, therefore, does not constitute a reliable conceptual opposition, but rather an idealizing polarity, an idealized tendency, the tensionof a contradictory desire (for pure smoothness is the end of everything, deathitself) from which only a mixed given, a mixture, an impurity comes forthin experience. Would a distinction between fact and right save the pertinence of thisconceptual opposition, as Deleuze and Guattari seem to think, at the verymoment, right at the beginning of the chapter on the "smooth and thestriated," when they are acknowledging the "mixes" of which we speak? Ibelieve this to be all the less likely in that the "fact" in question is not an126 This Is-ofthe Other The authority de jure, here, is all the less authorized to make a decisionsince, on the one hand, it rather pertains to one of the two agencies (striatedpower, and often state power) and is already implicated in the problematicopposition (like a defining element in the defined or to-be-defined) ; andon the other hand, from a purely juridical-phenomenological point of view,the recourse to experience itself shows that the sense of this mixing neverdelivers anything that might be, de facto or de jure, pure and free from thesaid mixture. Therefore, there is no pure concept, nor any pure intuition, of course,nor any immediate intuition of the haptical. Nancy, for his part, departs. He departs, he marks his departure ("Corpus: Another Departure" is a chapter title in Corpus) . He parts and sharesand separates; he no doubt also departs from this fundamental problematic, as well as from this intuitionism of the continuous or the immediate,this more radical, more invincible, more irrepressible intuitionism thanthe one simply opposed to its contrary (conceptualism, formalism, and so Nothing to Do in Sight 1 27 forth) . Nancy thus gives another sharing out and parting of the senses tothink, in this place of the limit, ofplural limits, where this tradition findsits resource. Marking and remarking the limits, rather, he spaces out thecontinuity of this contact between touching and the other senses, andeven the immediate continuity at the heart of touching itself, if one maysay so-the touching he will recall as "local, modal, fractal." Later, inCorpus (1 99 2), after Une penseefinie (1 99 0), it is on the subject of "exscription," of reading, and precisely of touching as reading, or reading as touching, that the "privilege given to immediacy" will find itself firmly challenged; and we have j ust evoked the inexorable tradition of this privilege,its invincible compulsion, and the endless resistance it will keep opposingto an interminable analysis. While Nancy, on the contrary: . . . (here, see, read, take, " Hoc est enim corpus meum" . . . ) . Of all writing, a body is the letter, and yet never the letter; or, more remote, more decon structed than all literality, a "lettricity" that is no longer for reading. That which of a writing-properly of it-is not for reading, that's what a body is. (Or we clearly have to understand reading as that which is not deciphering, but rather touching and being touched, having to do with body mass and bulk. Writing, reading, a tactful affair. But there again-and this, too, has to be clear-only upon the condition that tact does not concentrate, does not lay claim-as Descartes's touching does-to the privilege given to immediacy, which would bring about the fusion of all the senses and of "sense." Touching, too, touching, first, is local, modal, fractal.) (Nancy, Corpus, p. 76 )28 one can always ask oneself why this is necessary: what or who embodies thefigure of this Necessity here.) As soon as tactility (like sense, like the senses) is thus shared out, parted,partaken of, divided, partitioned, pluralized-in a word, syncopated, forsharing out is a syncope and the syncope a sharing out-but as well givento others, distributed, dispensed, there is no longer anything one can designate by using the general singular preceded by a definite article inFrench: Ie toucher, "the" touching. The definite article in general-itselfand properly-finds itself henceforth unemployed, perhaps, for anythingwhatsoever-as we were j ust saying a moment ago about the words meme,"same," propre, "proper, " and proche, "proximate." But how are we to writewithout them, without making believe we believe? Without each timeasking the other to believe in that for the spell of a scratching that willcome to sign the shared, imparted act of faith, and share out (divide,worry, put to pieces) the act of faith, and faith itself? This is how he exscribes, for example-and we shall understand him: "There is no 'the'body; there is no 'the' sense of touch; there is no 'the' res extensa. There isthat there is: creation of the world, techne of bodies, limitless weighing ofsense, topographical corpus, geography of multiplied ectopias-and nou-topia" (ibid., p. 1°4) . It is always the same break with immediacy and the indivisibility of thecontinuous. This break is not Nancy's, precisely; it is not his decision. Ittakes place. He recognizes it, weighs it, ponders it, thinks it. It is not soeasy. But this break, which does not mean that touching is given a leave,or that the proximate is, or the next one, or the same, or the definite article, and so forth, restructures or reinterprets these significations. It wouldbe necessary to quote all the pages dedicated to the "techne of bodies," butI have to limit myself to this extract pointing to the path, the path of another "here"-"ours," the here of our historic time, of our now, of our historic body: here, the path leading from the deconstruction of touching toa deconstruction of Christianity, its before as well as its beyond: Ecotechnics deconstruct the system of ends and makes them nonsystematiz able, nonorganic, even stochastic. . . . Finally, areality gives a law and medium, in lieu of a transcendent/immanent dialectic, of a proximity, both global and local-one within the other. Finally, we are within the techne of the next one, the fellow. The Judeo-Christian-Islamic "fellow man" resided in the particular and the universal-in the dialectization of the rwo; and without fail, this ends in the Nothing to Do in Sight 12 9 universal. But here, the neighborly fellow is next, what is coming, what takes place in approaching, what touches and also sets itself apart, localizing and dis placing the touch [la touche] . Neither natural nor artificial (as he or she ap peared by turns until now) , the "next" "fellow man" as techne is the true "cre ation" and "art" of our world, moreover subjecting to revision these words "creation" and "art," not to mention, principally, the "next," "neighborly" "fel low man." And so I prefer to say that techne is the techne of bodies shared out, or of their co-appearance, that is, the various modes of giving rise to the trac ings of areality along which we are exposed together-neither presupposed in some other Subject, nor postposed in some particular and/or universal end, but rather exposed, hand in hand, bodies laid out, shoulder to shoulder, edge to edge, close for no longer having a common assumption, but only, of our tracings partes extra partes, what is between-us. (ibid., pp. 7 8-80) § 7 Tangent I I35 Exemplary Stories ofthe "Flesh" fore any event that we would still produce by way of an act of languageand on the background of a foreseeable horizon, even before we touch it,or perhaps, if it does not anticipate in this fashion, then at the same timeat which we touch it, as if the idea itself of simultaneity, even continuity,were born for the first time in contact with the contact between twopoints of contact? Tangentially? Should one have touching power (to touch him) ? l Or laugh touching, ashe would, perhaps, also say? (As for me, I'd lean toward saying "weep" touching: to weep, to cry(for) it. But I sense that it comes down to the same thing. We agree whenit comes to shedding tears of laughter, for this "touch," this poor deardissociated, spaced out, severed from itself, in a word.) From now on, I'll let this formula float between its two senses, especiallyaround the value of enabling power (possibility, faculty, sovereignty) , whichhere and elsewhere is not less problematic than the value of touch: to havethe power to touch him, to be capable of touching him; and to have "touching" power, the capability for touch, potently to be with this singular sensethat is called touch. Potent [en puissance] , in the double sense of the force ofpower (that is, freely, sovereignly) and of the indefinitely reserved virtuality,in retreat, of dunamis. I'll leave this indecision open because what I wouldlike to attain-him, if you like-is this possibility, touching (it) , all thewhile meditating with him, simultaneously, on what touching, touchingpower, "is" or what it "does" to (tell) the truth. Would there be synchrony, an idea of synchrony, and in general some syn-,therefore a very idea of presence, presentation, and the auto-presentation ofpresence, if we could not touch it, if we were not capable ofthis very thing,touching (it)? He said in the passage cited earlier: to present is to make sensible, and sensibility equals the touching of the limit, touching the limit, atthe limit.2 What does this mean? But how can one still say anything that does not in advance get surrounded, invested, preoccupied, in all the historical places of these figuresof touch, in their rhetorical circle, in their logical or hermeneutical twirling around? Indeed, this question-one, singular, acute-belongs to an immensefamily (resemblances, common traits, genetic variations and mutations,elementary laws of kinship) . Very old, even archaic, since it has given riseover twenty-five centuries to an immense philosophical literature that wecan't even skim here. No doubt, we remember him saying, "a very long detour should be Exemplary Stories of the ((Flesh"; 1 II -And in an aside you tell yourself: what a funny, admiring, and grate ful salutation you're addressing to him, to Jean-Luc Nancy. What a peculiar way to pretend you're touching him while acting as if you wanted again to put his lexicon about touch at the service of a tradition, or worse, a filia tion itself Or, as if you reminded us that this lexicon and its usage should always already have been related to agelessly well-worn or even usurious ways; even ifwe like that-touching-anew, precisely, when it's impossible prohibited; and we even love to call this loving-abstaining. What a funny present, indeed! What an offering! Altogether as if at the moment of calling others so that they will become ecstatic before this great work and this im mense philosophic treatise of touch, you whispered in his ear: Now, Jean Luc, that's quite enough, give this word back, it's prohibited, you hear. Leave it to the ancestors, don't make any compromises with it, don't let this megalovirus contaminate you, and once and for all stop using this incredi ble vocabulary, this concept nothing can really vouch for, these figures with out figure and therefore without credit. Don't keep pretending, as they do, don't make believe, stop acting as if you wanted to make us believe that there is something one could call touch, an understood thing itself about which we could pretend to agree, and say something new, in the very place where, in touching upon the untouchable, this thing remains untouchable. Touch is finitude. Period. Stop at this point. Haven't you yourselfsaid "there Tangent I 1 39 i s n o 'the' sense o f touch"? Knowing you, I don't think this objection willstop you, I tell myself -Nor you. Would you like to touch him, as you say, in the way thepoint of a buttoned tip touches, during a fencing duel? Also, Americanssay touche, in French, with a funny accent, when a point is scored. -On the contrary, here what matters most of all to me is his singularity, his "plural singular being, " even when I speak of the others to the others. It's this absolute singularity of his signature that I exert myself in trying to attain. -You exert yourself? What does that mean? Let us start again from what we nicknamed earlier, that is, the effort offorceful exertion [l'effo rcementJ . We wondered what this necessarily finiteexperience offorceful exertion may signify. Force, of course (and even themysterious one- virtus, dunamis-that Jesus, as we recall, recognizes inhimself when someone touches him) , but also "exerting oneself," in itsself-relation. This self-relation institutes itself and is born to itself as exertion at the moment when a limit comes to insist, to resist, to oppose (itself) to the effort that this limit literally determines. I chose the word "exertion" [effo rcementJ because it bespeaks the effort as well as the limit nextto which the tendency, the tension, the intensity of a finite force stops (itself) , exhausts itself, retracts or retreats from its end back toward itself: atthe moment, the instant, when the force of the effort touches upon thislimit. (I spoke earlier of the objectivity of being(s) determined not only asthat which is exposed before the gaze, but that which opposes a resistanceto touch. The hand (being-before-the-hand or at-hand [sous-la-main] , orthat which meets a resistance to manipulation) might well reconcile, conjoin, and adjoin these two positional values of the objectivity of the object.) Every thinking of effort comprises at least a phenomenology of fi n itude, even if, in the case of Maine de Biran and especially Ravaisson, thisthinking accommodates the infinite (will or pure activity, grace, spiritualfreedom) against the background of which a finite effort is set off But aneffort always signs a finitude. It is there perhaps that touching is not a sense, at least not one senseamong others. A fi n ite living being can live and survive without any othersense; and this occurs with a host of animals that have no vision (it is possible to be sensitive to light without "seeing"), no hearing (it is possible tobe sensitive to sound waves without "hearing") , no taste or sense of smell140 Exemplary Stories of the "Flesh" live without seeing, hearing, tasting, and smelling ("sensing," in the visual,auditory, gustatory, and olfactory senses) , but we cannot survive one instant without being with contact, and in contact. Aristotle said this verywell, as cited earlier. That is where, for a finite living being, before and beyond any concept of "sensibility," touching means "being in the world."There is no world without touching, and thus without what we just termedforceful exertion. That is how I am tempted to interpret the privilege that Maine de Biransimultaneously accords to effort (force + limit) , to tactility, but to thehand as well, the "organ of touch," in a more problematic mode this time.He ties together what these signify in an original fashion, even if his discourse forms part of an immense contemporary debate (the famous question, raised by Molyneux, Locke, Berkeley, Condillac, Buffon, Diderot,4Voltaire, the Ideologues [a circle that in addition to Cabanis and Destutt deTracy included Ginguene, Daunou, and Volney] , Charles Bonnet, andBarthez, among others, concerning the problems of those who are bornblind) , which won't be reconstructed here.5 Some Cartesian sources of thesame argument go back more specifically to the First Discourse in Descartes's Dioptrics, in which he compares the stick of the blind to the "organ of some sixth sense given to them in place of sight. "6 A German streakalready comes to blend with the French or Anglo-French medium of thistradition. In his Memoire sur fa decomposition de la pensee, Maine de Birancites Schelling and Fichte, following Joseph Marie de Gerando.7 One could say that the "Introduction" to Maine de Biran's The Influenceof Habit on the Faculty of Thinking8 begins with touching. While proposing to unite ideology with physiology, Biran pretends that he is following a physicist's example by not concerning himself with essences or firstcauses, but only with "effects" and "phenomena," and their relation andsuccession, "leaving behind one, and under the veil that covers them, firstcauses which should never become for man objects of knowledge." And headds: "We know nothing of the nature offorces."9 We know only their "effects," and for that very reason it is pointless toseek out what the soul is and how it can be united with the body: "Physical science does not concern itself with essences-why should metaphysics? Tangent I It is our intimate sense that must lead us and not the false glimmer ofimagination or abstract methods."l0 To be sure, it is a limited analogy, but it is certainly analogous to a Kantian or Husserlian gesture. One starts with a received impression, or sensation, a word held to be synonymous with it here: "primary faculty" of the"organic living being" [l'etre organise vivant] . Each of these words countsoriginarity, the life of the living, organic or organized faculty (as well as organ) . Now, if impressions are divided into active and passive, motor andsensitive; if the activity and distinction of the ego immediately connect withmotor activity, then, from a phenomenal or phenomenological point ofview, the two types of impression cannot be disentangled. And this wouldhinge on the "nature of our organization," either necessarily or contingently, but in any case starting from a fact with which one must begin:"such is the direct correspondence, the intimate connection which existsbetween the two faculties of feeling and moving, that there is almost noimpression which does not result from their mutual co-operation and whichis not consequently active in one situation and passive in another" (Mainede Biran, Influence ofHabit, p. 5 6 ) . The word "almost" stands out ("almost n o impression"). Although i t isdifficult to fit an example in this category of the exceptional (that is, pureactivity or pure passivity) , it is clear that Biran requires this possibility inorder to preserve the operating power of the conceptual opposition and todistinguish the predominating element in each case. This logic of predominance makes it possible at once to lift or soften the pure conceptual opposition (between activity and passivity-which Condillac would haverecognized, but that he later forgot so that he "confuse[d] things") and tointroduce axiomatics of force and effort; not force as cause in itself butforce in its phenomenal effects. What will be called "sensation" is the mostpassive impression (where "feeling predominates up to a certain point" [myemphasis-J. D.] and where "the movement which occurs with it is asnothing" : "as nothing," and not nothing) and what will be termed "perception" is the impression where "movement takes the upper hand [prendle dessus]" (my emphasis-J. D.). Therefore, there is always a part of activity and a part of passivity, though now the one takes the upper hand,now the other predominates. Differential of force or hegemony. Maine deBiran then proposes to examine the organization of these two parts, feeling and movement, in the exercise of "each of our senses," and he beginswith the "organ of touch" [l'o rgane du tact] . 142 Exemplary Stories of the "Flesh" Why? Indeed, the answer is not given at the beginning but only toward the end of the course, when it becomes necessary to tackle the other senses, and when, at the end of the analysis of tactility, there is praise for the sense of touch, which "combines the two faculties [passive and active, sensory and motor] in the most exact proportion." (Maine de Biran also likes the word "exact," though we may wonder here what an exact pro portion might be, "the most exact," between passive and active, and where one might find its criterion and its measure.) Maine de Biran does not contradict those who content themselves with a comparison, those for whom "it is customary to compare the different sense impressions with those of touch proper." Without objecting to it, he relates this hearsay doxa ("it is said") which turns touch into the genus of which the other senses would only be the kind, the species: "all our sensations, it is said, are only a kind of touch. That is very true." And this comparatism or analo gism banks on a logic of inclusion. All our sensations are comparable to touch; they are as, they are like species of it, because touch is the genus of which the other senses are the species.1 But after Maine de Biran has thus assented to received opinion, he ven i tures farther out and praises touch and its incomparable excellence. If touch cannot be paralleled by any other sense organs, it is also from the point ofview of activity, and therefore motor activity. The other senses will correspond to touch only in accordance with their mobility, which is what will make them agree with the motor activity that is appropriate to touch, what will correspond to or come to an understanding and cooperate with touch [s'entendra avec Ie toucher] . Motor activity is therefore the specific difference, if not the essence, of touch-whence (we'll get to this) a certain privilege for the hand. The analogy between the other senses on the one hand and touch on the other will depend on the proportion of movement (motor activity, mobility) found in them. But only touch comprises a mo tor activity that is properly its own-and hence turns it into something more, something other than simply a sense, more and other than simply the locus of a passive sensation. All our sensations, it is said, are only a kind of touch. That is very true if one thinks only of their sensory or passive function; but with respect to activity and movement, no other sense organs are similar [ne supporte le paralleleJ . Only in proportion to their mobility are they more or less capable of corresponding to or of cooperating [s'entendreJ with touch, of profiting by its warnings and Tangent I 143 of associating their impressions with it. We shall make this dear in a rapid analysis of the senses. (ibid., p. 61) the chapter "The Spatiality of One's Own Body and Motility," with thepages dedicated to deficiencies of "unsound" or pathological touching or"potential" [virtuel] touch, as well as, in the chapter "Sense Experience,"with the "motor significance of colours" and "motor physiognomy" of allsensations, and even of this "synaesthetic perception" that "is the rule," ofthis "intersensory object," of the "intersensory unity of the thing" thatmakes up the most continuous theme of this book and seems inseparablefrom the concept of world, being in the world, or just being-a conceptorganizing this phenomenology of perception (see Merleau-Ponty, Phenomenology ofPerception, pp. 210, 2 39 , et passim) . A little earlier, in the passage cited just below, sensation presents itself ascommunion. Let us here note the return of the haptical figure of contact,primordial contact, to speak of the experience-no less-of being and theworld. The logic of these phrases runs throughout the book; one oftencomes across the literal mark they leave: Every sensation is spatial; we have adopted this thesis, not because the quality as an object cannot be thought otherwise than in space, but because, as the pri mordial contact with being, as the assumption [reprise] by the sentient subject of a form of existence to which the sensible points, and as the co-existence a/sen tient and sensible, it is itself constitutive of a setting for co-existence, in other words, of a space . . . this assumption [reprise] implies also that I can at each mo ment absorb myselfalmost wholly into the sense of touch or sight . . . the unity and the diversity of the senses are truths of the same order. . . . it is a priori im possible to touch without touching in space, since our experience is the experi ence a/a world. (ibid., p. 221 ) 1 5 and "partialities," orienting the reading of Bergson not only toward a phenomenology-complete with "reduction" and so forth-but also towardhis own phenomenological bent: Now we can bear witness to the vitality of his works only by saying how he [Bergson] is present in our own, showing the pages of his works in which, like his listeners in 1 9 00, we with our own preferences and partialities think we per ceive him "in contact with things." . . . For if this is what time is, it is nothing that I see from without . . . . So time is myself; I am the duration I grasp, and time is duration grasped in me. And from now on we are at the absolute. A strange absolute knowledge, since we know neither all our memories nor even the whole thickness of our pres ent, and since my contact with myself is ''partial coincidence" (to use a term often used by Bergson which, to tell the truth, is a problematic one) . In any case, when my self is at issue the contact is absolute because it is partial. I know my duration as no one else does because I am caught up in it; because it over flows me, I have an experience of it which could not be more narrowly or closely conceived of Absolute knowledge is not detachment; it is inherence . . . . Since it is a non-coincidence I coincide with here, experience is susceptible to being extended beyond the particular being I am. My perception [l'intuition] of my duration is an apprenticeship in a general way of seeing. It is the princi ple of a sort of Bergsonian "reduction" . . . . . . . Intuition is definitely not simply coincidence orfUsion any more. It is ex tended to "limits" . . . 1 6 . And since we have already paid so much attention to the corpus of "Hocest corpus meum," and to the Christian body and the Eucharist, and toirony that thinks, troubled and troubling in the hands of Nancy, let us dono more than situate here a certain connection between Merleau-Ponty'sthinking of motor activity and the Last Supper. His tone and intention arequite different from Nancy's. The passage can be found in the first pages ofthe chapter on "Sense Experience" in Phenomenology a/Perception. MerleauPonty has j ust insisted-notably on the subject of the perception of colors-on "motor physiognomy," motor reactions, "motor significance," andthe amplification of our motor being. Here, now, is the analogy, the "justas ... in the same way," reminding us of more than one "my body," a "mybody" that I wholly "surrender" [je livre] in this way: In the same way I give ear, or look, in the expectation of a sensation, and sud denly the sensible takes possession of my ear or my gaze, and I surrender [je livre] a part of my body, even my whole body, to this particular manner of vi- Exemplary Stories ofthe "Flesh" brating and filling space known as blue or red. Just as the sacrament not only symbolizes, in sensible species, an operation of Grace, but is also the real pres ence of God, which it causes to occupy a fragment of space and communi cates to those who eat of the consecrated bread, provided that they are in wardly prepared, in the same way the sensible has not only a motor and vital significance, but is nothing other than a certain way of being in the world sug gested to us from some point in space, and seized and acted upon by our body [que notre corps reprend et assume], provided that it is capable of doing so, so that sensation is literally a form of communion. (Merleau-Ponty, Phenomenol ogy ofPerception, p. 212) Here ends this anticipatory digression. A later chapter deals with touchaccording to Merleau-Ponty. This motif of motor activity here allows usto come back to Maine de Biran-whom, in truth, we had not really left. any longer. In a language that (for good reasons) is not Maine de Biran's,one could acknowledge its transcendental status-all the more so since itis first evaluated under the angle of knowledge and the relation to an object: "It is only, therefore, as a motor organ [specificity of tactility/touchJ . D.] that touch [le tact] contributes essentially to putting the individualin communication with external nature; it is because it combines the twofaculties in the most exact proportion that it is susceptible of such nice,such detailed, such persistant [sic] impressions; in short, it is in virtue ofthis that it opens a feeding ground for intellect and furnishes it with itsmore substantial nourishment" (ibid., p. 61) . 1 7 The sensibility o f sight i s n o doubt the most "delicate" but i t couldscarcely be "circumscribed" if one failed to take into consideration its relation to touch, which is to say the "mobility peculiar" to the gaze and especially its "association," its "close [intime] correspondence with touch": "It isonly because of its mobility that the eye maintains such intimate relationswith touch [le tact]" (ibid., p. 62) . The analogical " [just] as" always commands the logic of this community of the senses: "How could the handssay to the eyes: Do as we do, if the eyes were immovable?" (ibid., p. 62n3 ) .After "as" comes "almost" (the difference o f the almost would open up theinterval that we earlier risked nicknaming "transcendental": touch is notquite a sense-not a sense as or like the others) : "For that matter, we canapply to sight almost all that we have said of touch. In the natural state andin the ordinary exercise of the organ, the two functions-sensory and motor-correspond with and balance each other with no mutual disturbance"(ibid., p. 63) . Maine de Biran seems more uneasy when relating hearing to touch, buthis procedure is always the same: the recourse is to analogy by reason of orproportionally to motor activity. "In order to hear well," he notes, "it isnecessary to listen " (ibid., pp. 63 -64) . And this presupposes "putting intoaction the muscles," a "tension," an "effort." If, in this case, the effort hasbecome "imperceptible" owing to the ear's immobile passivity, a supple ment of motor activity comes as the remedy, taking up with touch again.A natural supplement, of course, and a teleological one! " But nature herself has taken care to supplement these faults; she has restored equilibriumby associating in the most intimate way her passive impressions with theactivity of an organ essentially motor" (ibid. , p. 64) . But it is especially tothe vocal organ that this supplement of motor activity finds itself entrusted. Through the effect of a sympathy so habitual that it does not Exemplary Stories ofthe "Flesh" strike us at all, sounds transmitted to the ear and the cerebral center set inmotion the vocal organ "which repeats them, imitates them, turns themback [les rejlechit] ," "incorporates" them in the "sphere of the individual'sactivity. " An interesting theory of echo and double imprint follows. Thecorrespondence with touch goes through the echo. Passivity and activityare thus coupled, and this is what it takes to turn hearing, listening, andthe voice into kinds of touching, modalities of haptical approach or appropriation. As always, the proper and the proximate are given (or rather,supposed to be given) in the same movement: "Thus, the individual wholistens is himself his own echo. The ear is as if instantaneously struck bothby the direct external sound and the internal sound reproduced. Thesetwo imprints are added together in the cerebral organ, which is doublystimulated [s'electrise doublement]-both by the action which it communicates and by the action which it receives. Such is the cause of tetes sonores[literally, sonorous or resonant heads] " (ibid., pp. 64-6 5 ) . 1 8 Affinity and dependence: this double relation with touch thus determines hearing as well as sight. But according to Maine de Biran this is stillmore evident in the case of taste and smell. Tastes are "the touch inherent[propre] in the tongue and the palate," and the sense of taste is thus theone that is "most closely related to touch"; while what can be said abouttaste "applies still more directly to smell," these two senses being "closely[intimement] connected with each other as with their internal organs. " Maine d e Biran never forgets the animal. H e compares the passivity ofsmell (there again, the movement of respiration makes up for it, supplementsit [suppltee]), or rather its role among the external senses, at the same rankas the polyp or the oyster "in the scale of animal life" (ibid., p. 67) . Sincesmell is the most passive of the senses, it is as close as can be to the sixthcategory of impressions, pure sensations, which come to us from inside thebody-no perception here, no effort, or at least "no perceived effort," "noactivity, no discrimination, no trace of memory." And when, in order toqualify these pure sensations, these purely internal and passive sensations,Maine de Biran concludes: "all light is eclipsed with the faculty of movement," he confirms and gathers several axioms: 1. This analysis of the senses is ruled by the point of view of the perceiving consciousness and objective knowledge. 2. The figure of light finds itself as if naturally associated with that, atthe very moment when sight is nevertheless interpreted as a kind of touch. 3. Above all, the reference to movement, the "faculty of movement," is Tangent 1 1 49 nothing but a motor will ( pure ego) , there would be no effort, but therewould not be any either if there were nothing but pure sensibility. I am notj ust conveniently inventing the schema of twinning. Here, for example, asearly as the introduction to the Memoire, is a passage, the passage of a certain "rather," that bears witness to the rhetoric exerted so as to justify theconcept of effort itself: "We can already begin to perceive that activity, asthat which is distinctive of the ego and its ways of being, is directly attached to the faculty of moving, which ought to be distinguished from thatoffeeling, as a main branch is distinguished from the trunk of the tree, orrather as twin trees are distinguished which cling together and grow intoone, with the same stem [dans fa meme souche] " (Maine de Biran, Influence ofHabit, p. 56; slightly amplified.-Trans.) The stem [souche] 2° of the effort, therefore, is the stem itself. The effortworks the stem, in the stem of the ego, and since it is also the origin of theego, it is an ego before the ego, ego without ego or ego before ego. This relation to oneself, this faculty to say I or to posit oneself, "self-identical," as I, can only institute itself, from the stem itself, in a memory, with persistence, in repeated efforts, and in self-retention. And so it should not surprise us that the clearest formulas on this subject appear at the momentwhen Maine de Biran deals with what he terms reminiscence ["memory"]and that the most interesting formulas discreetly put in communication athinking of force, potential power, these temporalizing dynamics of the effort, with a thinking of the virtual: The motor determination is a tendency of the organ or the motor center to re peat the action or the movement which has occurred for the first time. When this tendency passes from the virtual to the actual [effectifJ , as a result of re newed external stimulation, the individual wills and executes the same move ment. He is conscious of a renewed effort. . . . here are the elements of a relation, a subject which wills, always self-identical, and a variable term, resistance. . . . The motor being who has acted, and who acts now with greater facility, cannot perceive this difference without recognizing his own identity as will ing subject. But this recognition necessarily entails that of the end of the ac tion; they presuppose each other, and are closely united in the same impres sion of effort. (ibid., pp. 70-71) c. Third beat: " If-the object still remaining on my hand [my emphasis-J . D.]-I wish to close the hand, and if, while my fingers are foldingback upon themselves, their movement is suddenly stopped by an obstacle on which they press and [that] thwarts [ecarte] them, a new j udgmentis necessary; this is not l There is a very distinct impression of solidity, ofresistance, which is composed of a thwarted movement, of an effort [that]I make, in which I am active. . . . Let us stop an instant on this impression of effort which comes fromany thwafted [contraint] movement. We must learn to know it well" (Mainede Biran, Influence ofHabit, pp. 57 - 5 8) . Exemplary Stories ofthe ('Flesh" "We must learn to know it [la, i.e., this impression] well," in the firstplace because it is a matter there of becoming knowledgeable about thecondition itself of the knowing. Indeed, an analysis follows, which ascendsalong the three segments in time of this history of the hand and manualtouch, with a view to showing that without a willing motor subject, thereis no effort, and without effort, no knowledge. And without the hand, noteven an idea for the subject of his [sic] own existence, as it were. It goes on: Effort necessarily entails the perception of a relation between the being who moves, or who wishes to move, and any obstacle whatsoever which is opposed to its movement; without a subject or a will which determines the movement, without a something which resists, there is no effo rt at all, and without effort no knowledge, no perception of any kind. If the individual did not will or was not determined to begin to move, he would know nothing. If nothing resisted him, he likewise would know noth ing, he would not suspect any existence; he would not even have an idea of his own existence. (ibid., p. 58) imal; yielding the same knowledge, the same will, the same will to know,but frequently also the same obscurantism. Maine de Biran's remark about an elephant's trunk is not disprovingthis humanualism. On the contrary. The elephant's trunk "fulfills approximately the same functions as the hand of man." Approximately. Kantwithin the same anthropo-teleological hierarchy-does not neglect thefuture of the orangutan or the chimpanzee who could one day developnear-human organs, organs that can be used to handle, touch, palpate,grope and feel obj ects and speak ("zum befiihlen der Gegenstande undzum sprechen") . 23 Maine de Biran, for his part, jumps straight to the elephant, and if the latter is placed at the top of the scale of living beings, itis only to the extent that, thanks to what is "approximately" a knowinghand, namely, its trunk, the elephant resembles human beings to a certainextent. A long note once again invokes Buffon's authority. Knowledgeableintelligence and above all motor activity and motility, which condition itthese are the organizing criteria of this anthropo-zoological comparatismand this teleological hierarchy: The elephant's trunk fulfills approximately the same functions as the hand of man; motor activity and sensible feeling can be found in it equally united to a perfect degree. Therefore, as Buffon remarked, this organ is doubtless the one to which the elephant owes the intelligent features distinguishing it. When comparing the faculties of various species of animals, one may perhaps not find it diffi cult to prove that these faculties are not so much proportional in num ber or in relation to the refinement of the senses than to the activity and the perfection of the motor organs; less to the energy and very [propre] delicacy of sensible feeling [La sensibiLite] than to the prompt correspondence, the con stant equilibrium that sensible feeling enjoys with regard to motiLity.24 Several paths are open to whoever may wish to inquire further into thishuman destination of the hand in such a discourse about the sense oftouch. One may ask oneself what the exemplarity of this human hand signifies. In Nancy's discourse, in what he says about "my body" as well asthe "techne of bodies," this seems to me absent, precisely, or implicitly andpractically called into question. And what he says is as foreign to the humanistic philosophy of the hand as to this continuistic intuitionism, thiscult of natural immediacy, which has inspired so many celebrations oftouching. We need to reread "techne of bodies," in Corpus again and again,since this "question of the hand, " which is also a history of the hand, aswe know, remains-should remain-impossible to dissociate from thehistory of technics and its interpretation, as well as from all the problemsthat link the history of the hand with a hominizing process.26 It is also thequestion of the eye and the question of the mouth, of course. But we needwhat we deemed to be the necessary starting point: for Nancy the question of the mouth (bucca) is not to be reduced to the question of oralitythat speaks (os) . There are several paths to interpret the exemplarity of this human hand,and that is because, even with Maine de Biran, it can have a teleological andthus irreplaceable (seemingly dominant) sense, as well as a pedagogical andsecondary one, which is virtually pregnant with every kind of metonymy:manual touching as the best example, a convenient and eloquent sample, albeit replaceable and dispensable. The "figure" of the hand could well be thebest ontoteleological figure, the best rhetorical figure, or a trope among others to expose what an "organ of touch" or tactility is in general. Althoughthe teleological sense gives its orientation to the pedagogical sense of the example, although the two senses do not seem to be dissociable in Maine deBiran and so many others, they remain distinct in principle and de jure.This can also be explained by the quasi-"transcendental" paradox evokedearlier. "Transcendentalism" is always guided by a more or less surreptitious"exemplarism." As soon as touch is determined as the master sense or theoriginary sense by way of a reasoning that turns it into something other andmore than a (sensitive and passive) sense, one may include it in the list ofthe senses or just as well exclude it. And as soon as the tactile is consequently a sense that is at the same time localizable and unlocalizable, its local representation (for example or par excellence, the hand or the fingers ofthe hand) becomes necessary and just as well contingent and arbitrary. Where can we find a proof, or at least a sign, of this? Well, for example, Tangent I 155 i n the fact that the same philosophy o f effort and motor spontaneity, thesame discourse about an essential link between effort and touch, the samepraise of their common preeminence in the human "personality" can bedisplayed without a determining reference, perhaps without even an allusion, to the hand. Felix Ravaisson, as far as I can tell, never mentions thehand in his thesis on habit (De l'habitude [18 3 8] ) . Yet he plainly, and oftenword for word, derives his axioms from Maine de Biran, whom he moreover often cites-which does not limit the originality of work that leadselsewhere to what I have just for convenience's sake termed his axioms. Theones that matter to us here have to do with motor activity, effort, andtouching. If movement presupposes a power exceeding resistance, the relation between power and resistance can be measured by the consciousness ofthe effort that thus envelops activity and passivity. Effort situates the locusof equilibrium between "action and passion," as between "perception andsensation." Ravaisson then calls on Aristotle (invoking the Peri psuches, onthe subject of force), and on Maine de Biran especially, as he takes the consciousness of effort for the manifestation of personality, under "the eminentform of voluntary activity. "27 In his La philosophie en France au XIXe siecle(1868) ,28 Ravaisson praises Maine de Biran for having translated "I thinktherefore I am" into "I will therefore I am"-and not only, as MerleauPonty (quoted earlier) also noted, into "I can." But what difference is therebetween "I am willing to be able to" [je veux pouvoir] and "I am able to bewilling to" [je peux vouloir] ? Now, as effort cannot be dissociated fromtouch, touch at the same time fulfills it and covers the entire field of experience, every interval and every degree between passivity and activity. Touch [tact] , the eminent sense of effort, is also the name of all the senses: "Effortis fulfilled in touch [tact] . Touch [tact] extends from the extremity of passionto the extremity of action. In its development it comprises all their intermediate degrees, and, at every degree, it bears out their law of reciprocity."29 And so, touch occupies two places in the analyses dedicated to this "development"; this seems to comply with the Biranian legacy. A. On the one hand, touch, as such, occupies a median and ideal regionof effort poised between passivity and activity. On this score, it is the very best thing about a human being: " It is in the median region of touch, it is in this mysterious middle term of the effort, that one fi n ds, with reflection, the clearest and most assured consciousness of personality. "30 This attention paid to the "middle term" no doubt confirms a faithfulAristotelianism. It is, however, of interest here from another point of view. Exemplary Stories ofthe "Flesh" touch everywhere; the principle and the end are confosed. This immediate in telligence is concrete thought, where the idea is fused in Being. This immedi ate will is desire, or rather love, which possesses and desires at the same time.32 B . But on the other hand, and simultaneously, touch covers the field ofthe other four senses, from the most passive and least mobile (taste and Tangent 1 1 57 one must implant will in a desire, "primordial instinct": "nature itselE "3 8Following a gesture that I believe to be typical, and of which Ravaissonwas not the last to offer an example, as we shall see, his invocations ofSaint Paul,39 Saint Augustine,40 Malebranche, and Fenelon immediatelyrelay, in order to spiritualize and evangelize it, the Aristotelian inspirationthat already lies at the core of this philosophy in the very interpretation ofdesire (orexis) : "Nature is wholly in desire, and desire in the good which attracts it. And so, these profound words from a profound theologian canstrictly be verified: 'Nature is prevenient grace.' It is God in us, God concealed solely by reason of being too far inside, in this innermost intimacyof ourselves that we cannot fathom. " 41 Some might claim, and may even demonstrate (this is the second faceof the same answer) , that what is hiding, in this withdrawal of the humanhand, so as to act in secret, is the hand of God. Is this just another figure?How is one to separate this "prevenient grace" from all the senses and waysof the Gospel, from its light or flesh? And Incarnation? And particularlythe miraculous touch of Christ? § 8 Tangent II I591 60 Exemplary Stories of the "Flesh" and even to the effects of empirical habit, or even the habitus of the pureEgo, which is still a different thing (Ideas II, p. lI8) . Only on the nonmaterial side is spontaneity immediate-the living, animate, spiritual side ofthe body proper that is my own, and human, and the body of an ego-man(Ich-Mensch). The hand is my hand, but first as hand of man; this egological body, this living body proper (Leib) is an organ of the will (Willensorgan) , the one and only Object which, for the will of my pure Ego, is moveable immediately and spontaneously and is a means for producing a mediate spontaneous movement in other things, in, for ex ample, things struck by my immediately spontaneously moved hand, grasped by it, lifted, etc. Sheer material things are only moveable mechanically and only partake ofspontaneous movement in a mediate way. Only Bodies (Leiber) are immediately spontaneously ("freely") moveable, and they are so, specifically, by means of the free Ego and its will which belong to them. It is in virtue of these free acts that, as we saw earlier, there can be constituted for this Ego, in manifold series of perceptions, an Object-world (Objektwelt), a world of spatial corporeal things (raumkorperliche Dinge) (the Body as thing [das Ding LeibJ included) . The subject . . . has the "faculty" (the "I can") to freely move this Body. (Ideas II, pp. 159-60)4 Let us leave aside, at least for now, the discussion made necessary, apropos of this concept of freedom, by Nancy's use of the same word, "freedom," to designate an experience that no longer essentially refers to theegological subject [sujet egologique] , as is the case here. For Nancy, the experience of freedom is not primarily the experience of a subject, a will, oran "I can." Conversely, I'll stop insisting on this confirmation of my earlier remarks: in Husserl, as in Plato and so many others, the authority of the "eidetic" figure and of optical intuitionism, the implicit philosophy of thegaze-as paradoxical as this may appear-always and necessarily folfills itself, firmly and incessantly strengthens and confirms itself, in an intuitiontactually fi l led-in and in the hyperbole of continuistic haptocenteredness.Hence, in each instance, touching is no longer just one sense among others, since it conditions them all and is coextensive with them. And since itis not a sense like the others, it is designated as sense, sensory faculty, by theplay of an everlastingly equivocal metonymy. But why then does one keeppretending to treat it as a sense, as one of the senses, throughout the tradition? And furthermore, if in concert we agree to have it designate an in- Exemplary Stories ofthe "Flesh" This analysis of touch may tempt us to think that the privilege that itgrants the hand or the finger has to do in the first place with what sentence [3] specifi e s, that is, the case in which "the one or . . . the other Bod- Exemplary Stories ofthe "Flesh" ily part as a physical object" can touch one or the other part of the samebody-or be touched by it. Yes. And it is also true that this cannot be saidabout every external part of the body. But why only the hand and the finger? Why not my foot and toes? Can they not touch another part of mybody and touch one another? What about the lips, especially? All of thelips on the lips? And the tongue on the lips? And the tongue on the palateand many other parts of "my body"? How could one speak without this?(This question merely allows me to point toward some of the most obvious issues at stake in these choices.) And the eyelids in the blink of an eye?And, if we take sexual differences into account, the sides of the anal orgenital opening?5 Some but not all of these questions arise again later, especially when Husserl takes up other animalia, primal presence [l'archipresence] , and appresentations [l'appresentation] , in chapter 4 (paragraphs43ff.), on "Psychic Reality in Empathy, " where the hand and the fingermoreover still play a dominant part. Once more the hand's privilege can be explained, if not necessarily justified. We can explain its title of phenomenological nobility, and of nobility unadorned, by virtue of the primacy of the sub-objectivity just discussed, as well as the strictly anthropological limits of this phenomenologyand this phenomenological moment in Ideas II For all its ambition andoriginality, phenomenological reduction here does not suspend the Ego'shuman appurtenance or determination, at least not in the passages that interest us here. Things here are subtle and the stakes are serious enough tocall for prudence and minute attention to detail, sticking to the text asclosely as possible. What introduces the section in which our passageabout touch can be found ("The Constitution of Animal Nature") is thedefinition of a project regarding the "essence of the soul, the human or animal soul" (der Menschen- oder Tierseele) (p. 96) in its connection with thebody proper, a project Husserl pursued in many other texts. It is thus alsoa literal resumption of the great project of Peri psuches, following a phenomenological reduction, and it concerns the living or animate being ingeneral-thus opening onto the abyssal problem of life, phenomenologyas thinking of the living, transcendentality of the living present, and soforth.6 All too soon, Husserl summons up "a rigorous phenomenologicalmethod"; immediate, accomplished, and "perfect" intuition (vollkommene Intuition) of the psychical; "originary presenting intuition [intuition dona trice originaire] (in our case, experience) ," the sole founding ground of a theory even if this theory is determined as predicative in mediate thinking Tangent 11 (Husserl, Ideas II, p. 96). But very soon, in the very name of this phenomenological intuitionism, there is a need for this general project, whichseemed to concern every living being (human or animal) , to restrict itselfto us, since we "phenomenologists" alone can have an immediate, full, andoriginary intuition of what we are talking about. And this "we" withoutany transition is determined as "we, men. " The Ego here is viewed as Egothe-man from the moment when one has distinguished the real [reell] psychic Ego from the pure (transcendental) Ego-something Husserl doeshere explicitly in order to delimit his field-and from the moment whenthe said soul is "bound together with Bodily reality or interwoven with it."At the moment when he is announcing that he will study this link and theconstitution of this body proper that we find "under the heading 'empirical Ego,' which still needs clarification," well, says Husserl (who is nottelling us how or where it can be found and why it can be found preciselyunder this name) , "we find furthermore also [finden wir ferner auch] theunity 'I as man' [lch-Mensch (ego-homme)] . " Husserl specifies "the Ego whichnot only ascribes to itself its lived experiences as its psychic states and likewise ascribes to itself its cognitions, its properties of character, and similarpermanent qualities manifest in its lived experiences, but which also designates its Bodily qualities as its 'own' and thereby assigns them to thesphere of the Ego [lch-Sphiire]" (Husserl, Ideas II, p. 99) . After discussing this "I as man," Husserl does lead us back to a purelypsychic Ego, the one "Descartes, in his marvelous Meditations, graspedwith the insight of genius," this subject who enters the scene and exits itbut is not acquainted with being born and "perishing" (pp. 109-10) , thispure Ego that must be able to accompany all my representations, as Kantsays, on the condition, Husserl adds, that one widen the meaning of thislatter word to include obscure consciousness, and so forth (p. II5) . Andeven if, in this exploration of the pure Ego, Husserl comes to consider themoment when it "posits . . . a man" and in him "a human personality [unepersonne humaineJ" ( p. II 7) , it is true that the world itself (the real or fictive world, no matter: "each and every possible and phantasizable world") ,as correlate of this pure Ego, "for this pure Ego," is in fact not necessarilyhuman. It is also true that the determination of the "real psychic subject"can as well refer to any living being; Husserl says it expressly: "the animal,man or beast" (p. 128) .7 Nevertheless, it remains that in the chapter dedicated to "Psychic Reality" in general ( paragraphs 3 0 to 34, pp. 128-50) , thehuman subject had already taken up more and more space and the animalr66 Exemplary Stories of the ''Flesh'' 1. Mter all, why not cut out in the animal field in general an originalobject, a very original one, man, and constitute such a phenomenologicalanthropology? There is nothing unspeakably shameful or unjustifiable inthis-on the contrary. 2. There is no other choice (and then difficulties set in) when the principle of principles, intuitionism, phenomenology itself, commands us tocommence with "us," the Ego most proper, most proximate, and most selfproximate-self present otherwise than by indirect appresentation (which - pure Ego that "we" are, as near to us as can be, comes before the most radical phenomenological reduction, the one that suspends the thesis of theworld in general. The privilege of the hand seems all the more difficult to analyze and justify, since two heterogeneous, possibly contradictory, imperatives here seemto command the exception. On the one hand-we have already notedthis-as a point of departure for the analysis of the body proper, it is firsta matter of the perception of an external thing determined as an object, an"external object, " j ust as there will be an internal object as well. On theother hand, in this objectal structure of apprehension, as we shall verify,Husserl is very much set on describing the reflexive specificity (and therefore more immediately ego-phenomenological quality) of the sensation ofthe living body proper, and its "self-sensing. " And in this regard, what ispossible for touch (and the hand does indeed show this more easily than thelips, the tongue, the eyelids, or the anal or genital opening) is in no waypossible for sight or hearing (whose difference Husserl then examines, Tangent II without broaching the senses of smell or taste at this point) . And almost allthe resources of the analysis that comes after the passage just cited are spentin the demonstration of this reflexive, or ego-phenomenological, excellenceof touch, the demonstration of the absolute and incomparable unity oftouch. This will later lead to a radical and unequivocal conclusion: it isonly thanks to touch that there is a body proper; or more precisely thebody proper "becomes a Body [zum Leib wird ]" only "by incorporatingtactile [sic] sensations rim Abtasten] ," "in short, by the localization of thesensations as sensations" ( Husserl, Ideas II, pp. 158-59) . For after Husserlhas described the double apprehension proper to touch, he moves on atonce, emphasizing, with an energy that marks the whole chapter: "But inthe case of an Object constitutedpurely visually we have nothing comparable[Ahnliches haben wir nicht beim rein visuell sich konstituierenden Objekt] "(ibid. , p. 155) . Husserl at once pushes aside a virtual objection. Indeed, some peoplemight let themselves be tempted by a tactilist interpretation of sight. Wehave encountered many temptations of this type in the Cartesian, preCartesian, and post-Cartesian traditions down to this century and even after Husser!' This is a facile approach, which Husser! challenges outright:according to him, there is nothing in this but a way of speaking, a metaphor, an analogical confusion devoid of phenomenological rigor: "To besure, sometimes it is said [man sagt zwar mitunter] that the eye is, as itwere, in touch with the Object [tastet es gleichsam ab (le touche, pour ainsidire)] by casting its glance over it. But we immediately sense [i.e., remark,notice-Trans. ] the difference [aber wir merken sofort den Unterschied] "(Husser!, Ideas II, p . 155) . What difference? Before I repeat this question, let m e insist o n the reachof this gesture. Dare one say, by way of illustration, that what the questionhas in view has to do with everything that preoccupies us here? Or that ittouches on everything that is at stake and matters to us in this book? Husser! evidently knows what touching means properly speaking; this he understands and is intent on knowing, and he posits that, in order to be solidand consistent, a serious philosophical discourse must on principle refer tothis strict sense, which is also common sense: everyone knows what touching must mean, in the end, and knows that no one has ever touched anything with his or her eyes. A rigorous philosopher, a responsible phenomenologist should resist the figures of everyday language with its as and as if(gleichsam) ; he must resist them and recall us to evidence itself: the eye Exemplary Stories of the ((Flesh" for mit, and it seems justified; 1 0 it is perfectly faithful to the whole drift ofthe argument. The local coincidence that is important for Husserl in thetouching-touched pair is grounded in a temporal coincidence meant togive it its intuitive plenitude, which is to say its dimension of direct immediacy. (Let us keep in mind this question of time: this passage, where"localization" is the main concern, is not thematizing it but only treatingit via paralipsis; we'll get back to this in a moment. For if one questionsthis absolute simultaneity of the touching and the touched-and the activeand the passive-for an immediate and direct intuition, this whole argument risks becoming fragile.) Coincidence, intuitive plenitude, direct immediacy-that is, according to Husserl, what characterizes the experienceof the touching-touched. The dependence of sight is thus marked, in addition to its failings. If the eye and the visual sensations are "attributed tothe Body," "that happens indirectly by means of the properly localized sensations" (my emphasis-J. D.), which is to say tactile ones. Actually, the eye, too, is a field of localization but only for touch sensations [seule ment pour les sensations de contact] , and, like every organ "freely moved" by the subject, it is a field of localized muscle sensations. It is an Object of touch for the hand; it belongs originally to the merely touched, and not seen, Objects. "Originally" [originairement] is not used here in a temporal-causal sense; it has to do with a primal group of Objects constituted directly in intuition (direkt anschaulich) . The eye can be touched, and it itself provides touch and kinetic sensations; that is why it is necessarily apperceived as belonging to the Body. (Husserl, Ideas II, p. 156) Tastempfindnis ist nicht Zustand des materiellen Dinges Hand) " (ibid.,p. 1 57) · Husser! is intent on grounding the privilege of the tactile in the constitution of the body proper on the properly phenomenological necessity ofthis distinction. Now, it is better to remain very close to the letter of thetext before we ask the questions seemingly raised by the reasoning or theargument to which this network of phenomenological evidence gives rise,before we question the demonstrative procedures or the theses that, intruth, seemingly act in advance as parasites or contaminants of the allegeddescription. Let us first of all quote the consequence that Husserl proposesto draw from this distinction in speaking of "the hand itself (eben die Handselbst) ," of what comes to pass or what 1 sense on "this surface of the hand(aufdieser Handflache)," and above all what "I can say," from there, I, the"subject of the Body" : The touch-sensing is not a state of the material thing, hand, but is precisely the hand itself (eben die Hand selbst), which for us is more than a material thing, and the way in which it is mine entails that I, the "subject of the Body" (das "Subjekt des Leibes") , can say that what belongs to the material thing is its, not mine. All sensings pertain to my soul; everything extended to the material thing. On this surface of the hand 1 sense the sensations of touch, etc. And it is precisely thereby that this surface manifests itself immediately as my Body. One can add here as well: if I convince myself that a perceived thing does not exist, that I am subject to an illusion, then, along with (mit) [en meme temps] the thing, everything extended in its extension is stricken out too. But the sensings do not disappear. Only what is real [reell] vanishes from being. Connected to the privilege of the localization of the touch sensations are differences in the complexion of the visual-tactual apprehensions. Each thing that we see is touchable. (Husserl, Ideas II, pp. 157 -58) 1 1 Tangent II 17 5 to the sensing o r sensible impression, be i t real [reell] (be it, as Husserl re calls, "a real optical property of the hand") ; and it pa rtakes-that is, it (the exteriority perceived as real) must even partake of the experience of the touching-touched, and of the "double apprehension," even if it is in a hy lomorphic or noetico-noematic fashion, even in the case of illusions. With out an outside and its "real quality of a thing" announcing itself in the sen sible impression or sensing, already within its hyletic content, the duplicity of this apprehension would not be possible. This exteriority is needed; this foreign outside is needed-foreign to the "touching" and the "touched" sides of the phenomenological impression at the same time, there where the latter does not offer itself in sketchy adumbrations. (Moreover-let us pause at this last point for a moment-if in immanent and phenomeno logical perception there is never any sketchy adumbration, as for the mate rial and transcendent thing, no more sketches for what offers itself to sight than to touch, then the criterion for the prevalence of one over the other seems more problematic than ever, at least in this zone of the body (Leib) proper's immanent properness, of which Husserl is studying the constitu tion and analyzing first the "solipsistic" moment.) This detour by way of the foreign outside, no matter how subtle, furtive, and elusive, is at the same time what allows us to speak of a "double" apprehension (otherwise there would be one thing only: only some touching or only some touched) and what allows me to undergo the test of this singular experience and dis tinguish between the I and the non-I, and to say "this is my body," or, quoting Husser! himself, to draw the consequence that "I, the 'subject of the Body,' can say that what belongs to the material thing is its, not mine." For that, it is necessary that the space of the material thing-like a differ ence, like the heterogeneity of a spacing-slip between the touching and the touched, since the two neither must nor can coincide if indeed there is to be a double apprehension. No doubt, in the sensible impression or sens ing, I-still I-am the touching and the touched, but if some not-I (ma terial thing, real [reell] space, extension, as opposed to phenomenological "spreading out and spreading into," and so forth) did not come to insinu ate itself between the touching and the touched, I would not be able to posit myself as I, and "say" (as Husserl says) , This is not I, this is I, I am I. And it is there, precisely because of extensio, because of visibility and the possibility at least for the hand to be seen, even if it is not seen (a possibil ity involved in the phenomenological content of the sensible impression) , that manual touching-even just touching my other hand-cannot be re- Exemplary Stories of the "Flesh" duced to a pure experience of the purely proper body. This would hypo thetically be the case for the heart touching, however (but even that is not so certain) , and Husserl speaks of it in the following chapter. What he says about this then is important for us, for two sets of reasons at least: A. The first reasons are architectonical, in a way. In chapter 4, Husserl broaches the great question of empathy in the constitution of the reality "I as Man." To that end, as in the previous chapter to which I have just re ferred, he takes up his starting point again in what he terms "solipsistic ex perience, " the one where "we do not attain the givenness of our self as a spatial thing like all others (a givenness which certainly is manifest in our factual experience) nor that of the natural Object, 'man' (animal being) , which we came to know as correlate of the 'naturalistic attitude,' a mater ial thing upon which the higher strata of what is specifically animal are built and into which they are, in a certain way, inserted, 'introjected' Cin trojiziert' sind)" (Husserl, Ideas II, p. r69) . 12 I quote this long passage because I would later like to suggest that we already have to presuppose this introjection in the experience termed "solipsistic" of the manual touching-touched, where it is already at work. ( Husserl situates the introjection as a late and upper layer of experience, as an exiting moment out of solipsism.) How could the duplicity of the double apprehension appear without the beginning of such an "introjec tion"? All this should lead to the reproblematization of what Husserl as serts in such a striking and enigmatic way at the end of paragraph 45, about the "grammar" that would befit the expression of pure, purely proper, purely "solipsistic," psychic life, before any "introjection"; and thus about "an objectivity which is precisely double and unitary [doppeleinheitliche Ge genstandlichkeit] : the man-without 'introjection. '" Hence the question: where does introjection begin? What is one speak ing of, and how can one speak of it, when there isn't any introjection yet at all? Can there be a random, pure, immediate, not-spaced-out-in-itself phe nomenological intuition, of this "thing" that seems to defY any grammar? If there is some introjection and thus some analogical appresentation start ing at the threshold of the touching-touched, then the touching-touched cannot be accessible for an originary, immediate, and full intuition, anyj, more than the alter ego. We are here within the zone of the immense prob lem of phenomenological intersubjectivity (of the other and of time) , and I shall not re-unfurl it once again. Let me merely revive the question here: shouldn't a certain introjective empathy, a certain "intersubjectivity," al- Tangent II 1 77 B. Let us not forget that it is in the said "solipsistic" sphere of the experience of the body proper that Husserl first proposes all these analyses (ofmanual touching as well as of Herzgejuhl, the "heart sensation"; of the "forexample, 'I feel my heart"': "z. B. ich 'empfinde mein Herz"') . Now, let useven suppose, as Husserl seems to do, that one may retain an "I feel myheart" within this sphere of appurtenance or solipsistic properness; let ussuppose that this "I feel my heart" is possible even before I can say it, sincesaying it already presupposes the grammar of a break in the solipsisticsphere, a break as grammar, even if it is only to myself that I say it. ( Butisn't grammar, which is also a techne, like rhethoric, to be found there already-already irreducibly announced-in the possibility of this "localization," this phenomenological distinction of places, that Husserl recalls?He does so all the time to speak of touch and discern this "touched, andnot seen" phenomenological localization, which is distinct from the spatial, objective determinations of extensio.) Well, even within this hypothesis of an immediate "I feel my heart," a purely, properly "solipsistic" heartsensation, Husserl never dares speak-it stands to reason-of this "double apprehension" of the touching-touched, which he analyzed earlier onand profitably drew from so as to assert the "privilege" of touch. And so,there is a certain embarrassment when it is further a matter of connectingwith touch an example ("I feel my heart") that illustrates better than thehand the feeling, which is first solipsistic, of a body proper. First stage: "Inthe case of the solipsistic subject we have the distinctive field of touch inco-presence with the appearing Bodily surface and, in union with that,the field of warmth; in second place we have the indeterminate localization of the common feelings (Gemeingefohle) [affects communs] (the spiritual ones as well) and, further, the localization of the interior of the Body,mediated (vermittelt) [mediatisee] [my emphasis-J. D.] by the localizationof the field of touch" (Husserl, Ideas II, pp. 1 73 - 74) . I emphasized "mediated" (vermitteft): here again it implies that this localization is mediated by means of a tactile localization, which would be immediate. This purported immediacy of touch comes into question, immediately afterward, in the following sentence-the second stage-with theexample of the heart: "For example, I 'feel my heart.' When I press the sur- Exemplary Stories of the "Flesh" face of the Body 'around the heart,' I discover, so to say, this 'heart sensation,' and it may become stronger and somewhat modified. It does not itself belong to the touched surface, but it is connected with it" (ibid. , p. 1 74). For reasons that are now evident (he attempts to find again the internalproperty of the body proper, and the most solipsistic possible) , Husserl isalready keen on connecting this heart sensation with the experience oftouch, even if the sensation "does not itself belong to the touched surface[surface tactile] ." But since there is no "double apprehension" there (precisely because the touching-touched then seems-seems, indeed-absolutely to be "in union with that" [ne faisant qu'un avec lui] and then seemsto pertain to some incredible touching without any tactile surface) , Husserlhas to find a phase or an intermediate stratum of touch in order to upholdhis demonstration, and there, with my hand, I touch the inside of my bodyby "feeling through" a surface. There begins, in this place, to be some surface, and therefore some touching, in a stricter sense, but also, with surface,some visibility, even if the visible in fact eludes actual sight. "Likewise, ifI not only simply contact the surface of my Body but press on it morestrongly, press into the flesh (das Fleisch eindrucke) , i.e., with my touchingfinger 'feel through' to my bones or inner organs (just as, similarly, withother bodies [Korper] I feel through to their inner parts)" (ibid.) . 13 But-third stage-after the immediate "heart sensation" (internal "touch"without any visible corporeal surface) , after the half-visible manual touchthat "feels through" a surface, here is the touch of the hand visible fromboth sides, the touching and the touched: Besides, solipsistically there belongs to every position of my eyes an "image" aspect (ein "Bild"-Aspekt) of the seen object and thus an image of the oriented environment. But also in the case of touching an object, there belongs to every position of my hand and finger a corresponding touch-aspect (ein Tast-Aspekt) of the object, just as, on the other side, there is a touch-sensation in the finger, etc. , and obviously there is visually a certain image of my touching hand and its touching movements. All this is given to me myself as belonging together in co-presence (for mich selbst in Komprasenz zusammengehorig gegeben) and is then transferred over in empathy: the other's touching hand, which I see, app resents to me his solipsistic view of this hand and then also everything that must belong to it in presentified co-presence (in vergegenwartiger Komprasenz) . Yet to the appearance of the other person there also belongs, in addition to what has been mentioned, the interiority of psychic acts [l in terioritepsychique ' de lacte] . (ibid.)rI Tangent II 1 79 This last example (the visible hand touching a visible object) defines the typical situation upon which Husserl establishes the privilege of touch in the strong sense-as the possibility of "double apprehension" : touching touched. And this possibility, which depends on the hand or in any case a visible part of my body, presupposes a surface, the visibility of it, and ("then," dann, says Husserl: but we may wonder what j ustifies this succes sion) the possibility of moving toward empathy and the indirect appresen tation of the other man's solus ipse. Let me quote this passage again: " . . . and is then transferred over in empathy: the other's touching hand, which I see, appresents to me his solipsistic view of this hand and then also everything that must belong to it in presentified co-presence ( . . . undgeht dann in die EinJuhlung uber: die tastende Hand des Anderen, die ich sehe, apprasentiert mir die solipsistische Ansicht dieser Hand und dann alles, was In vergegen wartiger Komprasenz dazugehoren muss) ." (ibid.) Hence our question: if this possibility of appresentative empathy, of indi rect or analogical access, already partakes of the solipsistic "moment"-be it as a virtuality but thus also as an essential possibility-how can it be said that it comes "then," afterward, finding itself grounded in an intuitive and pure presence or co-immediacy? And thus if we assume the "interiority of psychic acts," isn't it necessary, from the outset, that visibility, being ex posed to the outside, the appresentative detour, the intrusion of the other, and so forth, be already at work? And would this not condition, or at least co-condition, that on which it seems to depend and that it seems to follow, moreover in the very inside of the touching-touched as "double apprehen sion"? Mustn't the intruder already be inside the place? Isn't it necessary that this spacing thus open up the place for a replacing, and that it make room for the substitute, the metonymical supplement, and the technical? Let me be more precise about the meaning or orientation of our ques tion. Denying the possibility of a tactile experience of the touching touched is not the point; but in acknowledging what its manual or digital example implies (as best and paradigmatic example, or "guiding thread" of the analysis) , I ask whether there is any pure auto-affection of the touch ing or the touched, and therefore any pure, immediate experience of the purely proper body, the body proper that is living, purely living. Or if, on the contrary, this experience is at least not already haunted, but constitu tively haunted, by some hetero-affection related to spacing and then to visible spatiality-where an intruder may come through, a host, wished or180 Exemplary Stories of the ''Flesh'' cess at the same time. It has been an early threat to what it was meant to make possible. It has reintroduced into sense the other sense and the other of sense, in all the senses and ways of the word sense [sens] . 1 5 § 9 Tangent III I83 Exemplary Stories ofthe "Flesh" 2. Thus at the principle of what "we have the human body say," there is, according to Nancy, who names the most decisive theme of this phenom enology, a certain phenomenon, a phenomenology of "self-touching": But the body is not this Living Temple-Life as Temple and the Temple as Life, self-touching as a sacred mystery-except on the condition that the cir cularity grounding it be completely finished. (ibid., p. 65) 3. And here, especially, is the connection between this "human body," the "self-touching" of this flesh, and the body of a Christian onto theology, in its eucharistic ecstasy par excellence-or in this "communion," mentioned earlier,3 apropos of Phenomenology ofPerception. At this point Nancy quotes Merleau-Ponty, and he then emphasizes the definite article ("Ie corps") sev eral times in this chapter, for it is what is thus signified by it that he is after: The body, therefore, is nothing other than the auto-symbolization ofthe ab solute organ. It is unnamable like God, it exposes nothing to the outside of an extension, it is the organ of self-organization, unnamable like the rot of its self-digestion (Death in Person)-unnamable, as well, as this self-texture to ward which strains a philosophy of the "body proper" ("What we are calling flesh, this interiorly worked-over mass, has no name in any philosophy," says Merleau-Ponty) .4 God, Death, Flesh-the triple name of the body in all of ontotheology. The body is the exhaustive combination and common assump tion of these three impossible names, where all meaning wears itself out. (ibid., pp. 65-66) 5 itation of the sensible" : yet Husserl would never have spoken of it in suchterms, it seems to me, and this would not have interested him for a singlesecond, supposing that he even sought to lend an ear to it-no more thanto a "description" that "overturns our idea of the thing and the world"(Merleau-Ponty, Signs, p. 166 ) . Similarly, Husserl would not admit to being "obliged to say" whatever it might be, and "obliged to say that thesense of touch here is diffused into the body [repandu dans Ie corps] ," giventhe stratified reasons that we have already examined. Husserl speaks abouta sense of touch that is not diffused throughout the body. I imagine thatHusserl would have also asked what "comes to rest upon or dwell in it, "rigorously and not metaphorically, means to say (the two terms are hardlycompatible, as a matter of fact) when used to describe the manner inwhich "an exploratory power" relates to a "physical thing" when it "becomes animate." All this shifting is preparing and blazing the way for adiscourse carried out in advance, the discourse of flesh and incarnation,which will increasingly and in a complex and refined way become thepath of Merleau-Ponty's thinking-and we have already seen how Nancyveers from it. Starting with the next page we pass from the translation of leibhaft as"in person" or "in the flesh" to incarnation, to "my own incarnation" as"carnal subj ect," and this in the name of what has be to "taken literally,"precisely where Husserl would never have concluded from the fact that athing can be present or "perceived 'leibhaftig,'" that the thing-any thing-has flesh (in the sense, this time, of the living, animate, and incarnate"body proper"), or that there is a "flesh" of the world. It is in this rathernon-Husserlian passage, this audacious translation, always proposed in thename of Husserl-and even the letter of Husserl's text, thus "translated"that Merleau-Ponty gets involved: "When we say that the perceived thingis grasped 'in person' or 'in the flesh' [leibhaft] , this is to be taken literally:the flesh of what is perceived, this compact particle which stops exploration, and this optimum which terminates it all reflect my own incarnation and are its counterpart. Here we have a type of being" (MerleauPonty, Signs, p. 167 ) . We can imagine Husserl's spontaneous resistance-justified o r not-tothis "translation," to this discourse, at every step and every turn. But thisliteral displacement of the letter, in which, however, "literally" is still said,signs Merleau-Ponty's whole design in Signs and The Visible and the Invisible. Both the violence of interpretation and the necessity of philosophicalr Tangent III writing that is given over to the figure are accepted, claimed, and signed. This is even the conclusion of "The Philosopher and His Shadow. " The others are there, already, with their gestures, spoken words, "to which our own respond . . . to the point that we sometimes turn their words back upon them even before they have reached us, as surely as, more surely than, if we had understood . . . for although meaning is everywhere figu rative, it is meaning [sens] which is at issue everywhere" (ibid., p. 181) . Objecting to these statements themselves is not the issue for us here. In a moment we'll follow their consequences as far as the figural relation be tween the senses of touch and sight are concerned, but it is fitting first to recall two interpretative preliminaries. 1. We can never sufficiently emphasize that Husserl's resistance is pre cisely to a metaphorical slant on the subject of the becoming-touch of sight or the becoming-seeing or becoming-visible of touch. The principle of this resistance, in the name of the proper and the sense said to be proper, which is also common sense, is an axiom of phenomenology in its Husserlian discourse. Even if translating or metaphorizing Husserl's lan guage is unavoidable, does one have the right to disregard its axiomatics on the subject of what language should be or should not do? Who says what is right, here? Let us leave this question hanging and proceed toward a second reminder on the subject of reading Husser!' 2. Merleau-Ponty's major concern is not only the "reflexive" access to the "incarnation" of "my body," in this fi r st allusion to the touching-touched of the hand; it is also and immediately to involve the other, and my experience of the other's body or the "other man's"-the other as other human be ing-in the being touched of my own proper hand that is touching. And here again, we are not objecting to the interest or necessity inherent in this movement (which mobilizes the immense, fearsome problematic of Ein fohlung and the appresentation of the alter ego or the other man in Husser! ' and the destiny of this problematic in France) . But shouldn't we mark-in a limited, pointed, but acute fashion-where Merleau-Ponty gives in to a rather ambiguous-and problematic-gesture in his reading of Ideas II (a reading aiming to be as literal and faithful as possible, supported by notes and German terms) ? This gesture is important for us, not so much for rea sons of integrity or philological discipline (though I am keen on those as well), but because of some of its paradoxical and typical consequences. What are they? Before stating them formally, let me again quote from "The Philosopher and His Shadow" and emphasize some passages: Exemplary Stories of the "Flesh" My right hand was present [assistait] at the advent of my left hand's active sense of touch. It is in no diffirentfashion that the other's body becomes animate be fore me when I shake another man's hand or just look at him [Husserl, Ideas II, pp. I73-74] . In learning that my body is a "perceiving thing," that is able to be stimulated [reizbarJ-it, and not just my "consciousness"-I prepared myself for understanding that there are other animalia and possibly other men. It is imperative to recognize that we have here neither comparison, nor analogy, nor projection or "introjection" [ohne Introjektion (ibid., p. I75)] . The reason why I have evidence of the other man's being-there when I shake his hand is that his hand is substituted for my left hand . . . . (Merleau-Panty, Signs, p. I68)8 The Husserlian references and citations must not delude us. At the verysame time when Merleau-Ponty claims that he is making a comment onHusserl or seeking inspiration in him, he puts the shoe on the wrong foot,literally, turning upside down, short of completely misreading, the sense ofHusserl's text, which I have, for this very reason, already sought to situate.The page in question clearly says that I can never have access to the body(Leib) of the other except in an indirect fashion, through appresentation,comparison, analogy, projection, and introjection. That is a motif to whichHusserl remains particularly and fiercely faithful. And when he says "without introjection," indeed, this is not to qualify our access to the other's living body, but the access that others have-that they have, just as I haveto their own proper bodies ("without introjection") . But this access thatothers have without introjection to their bodies, I can have-to their ownproper bodies-only by introjection or appresentation. Husserl wouldnever have subscribed to this "It is in no different fashion . . . [ce n'est pasautrement . . . ] " ("It is in no differentfashion that the other's body becomesanimate before me when I shake another man's hand or just look at him" [Signs, p. I68] ) , which assimilates the touching-the-touching [Ie touchanttoucher] of my own proper body or my two hands with the contact of theother's hand. Let us again reread this passage in Husserl. He has beenspeaking of the appearance of the other person (Erscheinung des fremdenMenschen) , "understanding of the other's psychic life," and especially ofthe "system of signs 'expressing' psychic events" in the language that is "actually spoken" and its "grammar": "Since here this manifold expression appresents psychic existence in [carnal] Corporeality, thus there is constitutedwith all that an objectivity which is precisely double and unitary: the man-without 'introjection'" (Husserl, Ideas II, p. I 75) . "Without introjection": these words do not describe my relation to therII Tangent 111 Ir Tangent III sentation and t o recognize its irreducible gap even i n the said touching touched of my "own proper" hand, my own body proper as a human ego, and so forth. And this would strictly be neither Husserlian nor Merleau I 93 Pontyian. Even between me and me, if I may put it this way, between my body and my body, there is no such "original" contemporaneity, this "con fusion" between the other's body and mine, that Merleau-Ponty believes he can recognize there, while pretending he is following Husserl-for exam ple, when he follows the thread of the same analysis and writes: "The con stitution of others does not come after that of the body [with which Hus serl could agree, but without inferring what follows.-J. D.] ; others and my body are born togetherfrom the original ecstasy. The corporeality to which the primordial thing belongs is more corporeality in general; as the child's egocentricity, the 'solipsist layer' is both transitivity and confusion of self and other" (Merleau-Ponty, Signs, p. 174; my emphasis-J. D.). This "confusion" would be as originary as the "primordial thing" and would make possible the substitutions (that we have noted are impossible) between the other and me, between o ur two bodies, in what Merleau Ponty unhesitatingly terms "the absolute presence of origins. " In another example, he writes: The reason why I am able to understand the other person's body and existence "beginning with" the body proper, the reason why the com presence of my "consciousness" and my "body" is prolonged into the compresence of my self and the other person, is that the "I am able to" and the "the other person ex ists" belong here and now to the same world, that the body proper is a pre monition of the other person, the Einfuhlung an echo of my incarnation, and that a flash of meaning makes them substitutable in the absolute presence of origins. (Merleau-Ponry, Signs, p. I75) And so, must we not think, and think otherwise (without objecting to it frontally and integrally) , that the said "same world" (if there is some such world, and if it is indeed necessary to account for it, and account for its "effect," as "sense of the world") is not and will never be the "same world"? The fact that this proposition is intelligible and even convincing for "every man," throughout more than one possible world, does not con tradict its content. When I take into account a whole history, from ho minization to socialization connected to verbal language and its pragmatic conditions, and so forth, I can convey to "every man's" ear that the world of each person is untranslatable and that finally there will never be anyI94 Exemplary Stories of the "Flesh" "same world. " These two possibilities are not incompatible; they evencondition, and call for, one another, as paradoxical as this may sound. So that vision should touch the limit, that it should touch its limit, that it should touch itself intact. Painting is always on the threshold. It makes up the threshold between intactness and touching-between the intactness and touching of light and shadow. . . . Access is no longer of the order of vision, but of touch . . . . . . . there is no ''Art'' in general: each olJe indicates the threshold by being it self also the threshold of another art. Each one touches the other without pass ing into it, and there is properly speaking no art of touching (not even a "mi nor" art such as those for taste and smell) , for touching is sense as threshold, the sensing/sensed apportioning of the aesthetic entelechy. Touching is the light/darkness of all the senses, and of sense, absolutely. In touching, in all the touches of touching that do not touch each other-touches of color, traced, melodic, harmonic, gestural, rhythmic, spatial, significative touches, and so on-the two sides of the one sense do not cease to come each toward the other, acceding without access, touching on the untouchable, intact, spacing of sense. Barely to touch: to skim the surface. Sense levels off. . . . There is sense only on the (flowering) surface of sense [it n'y a de sens qua jleur de sens] . Never any fruit to be harvested-but the painting of fruits as their coming ceaselessly re sumed, ceaselessly re-brought into the world, superficially, as on the rosy sur face of the skin [a jleur de peau] . I Ir Tangent III 195 the name of what "Husserl wanted to say" has to do with this purported"co-perception." Thus interpreted, it reduces, on the one hand, the irreducible difference between the originary, direct intuition of my own bodyproper touching itself (without Einfohlung, as Husser!, at least, puts it)and the indirect appresentation that, by way of sight (and Einfohlung, thistime) , gives me access to this man there, insofar as he sees-to this seeingman. On the other hand, the "co-perception" reduces the irreducible difference between sight and touch, according to Husserl-we have insistedon this enough. Concerning the "as" in "I see that this man over there sees,as 1 touch my left hand while it is touching my right" (Merleau-Ponty,Signs, p. 1 70), everything leads us to think that Husserl not only would haveobjected to its phenomenological legitimacy; he would have seen in it oneof those facile rhetorical turns about which his misgivings-precisely onthis point-were great, as noted earlier. With-the one and the other of the with. Having reached this pointand before we go any further in the company of Merleau-Ponty-I wouldlike to make another anticipatory digression toward Nancy. What his bookEtre singulier pluriel (Being Singular Plural) sets out to do is to think thecum and the "with" in other ways-precisely in the chapter titled "TheMeasure of the With." 1 refer the reader to the progress of its analysis, and Tangent III 199 merely retain here what comes down, again, to our question o f touch (andconfirms the need for this "deconstruction of Christianity," Nancy's newproject that we keep bringing up) , of "distance [ecart] and contact," theparting into "on the one hand" and "on the other hand," one part and theother of a sharing out of the with: With regard to this constitution, then, and at the heart of Judeo-Christianity and its exact reverse side [always "exact," to be sure: even at the "heart" and "reverse side" he still dares to say "exact"-J. D.] , it is a matter of understand ing how the dimension of the with both appears and disappears all at once. On the one hand, the proximity of the next, of the fellow [du prochain] , points to the "next to" of the "with" (the apud hoc of the etymology of avee in French) . . . . [ Nancy then develops this semantic logic until its internal and ineluctable reversal.-J. D.] On the other hand, this is why . . . the simul taneity of distance [eeart] and contact, that is, the most proper constitution of the cum-, is exposed as indeterminateness and as a problem. In this logic, there is no proper measure of the with: the other draws it away from it, within the alternative or dialectic of the incommensurable and of common intimacy. In an extreme paradox, the other turns out to be the other ofthe with. (Nancy, Be ing Singular Plural, pp. 80-81) It is always the law ofparting and sharing at the heart of touching andcon-tact, presentation, appearance, and co-appearance: sharing out asparticipation and partition, as continuity and interruption, as syncopatedbeat. An ethics, politics or law, and a thinking of an "inoperative community," also come out, through the test of this incommensurable, the"other of the with"-and not even in the reassuring "simultaneity of distance and contact," but what, in it, thus remains an "indeterminateness"and "a problem. " At the moment when Nancy's thinking is thus decided(and, as has been noted, it often is) , and always sets itself to think whilemeasuring exactly the "incommensurable" and measuring itself with [a]the "incommensurable," his thinking is "with" Merleau-Ponty, as nearand far as possible in relation to the Merleau-Ponty who claims, it will berecalled, to coincide with a noncoincidence ("it is a non-coincidence I coincide with here"), which in fact does resemble Nancy's "simultaneity ofdistance and contact." However, at this point ("problem," "indeterminateness") , "the other of the with" interrupts all contemporaneity, coappearance, and commensurability. Earlier in Being Singular Plural (p. 56ff.), moreover, in the section "Coappearing," Nancy analyzes what he terms the "chiasmus" between two 200 Exemplary Stories of the "Flesh" longer means much, if the said "tradition" ("since the beginnings of Greekontintuitionism, which is finally homogeneous, undifferentiating, absolute,stubborn, absurd, and in the final account insensible or "smooth" -i.e.,deaf, blind, and impassive) the fate of this intersensibility (henceforth irreducibly tropological, figural, and metonymic) allows one to see and hearand feel and taste a bit of touching everywhere: indeed, who would denythat we can touch with our voice-close or far away, naturally or technically, if we could still rely on this distinction, in the open air or on thephone-and thus, even touch to the heart? Whether they are maintainedor subverted, these "parallelisms" are no longer determining-nor, finally,are they determined or even determinable. And these battles for the hegemony or equality, for the aristocracy of onesense, or the democracy of all the senses-don't they then become trifling,no matter how virulent, how fiercely embroiled, tooth and nail [acharnees] ?In their polemical duels, these battles are possible only insofar as there isno longer any sense proper, strict and circumscribable, to each of thesesenses, but only tropological displacements and substitutions, that is, prosthetic possibilities. If there were any possible accord about a sense proper-strict and circumscribable, stabilizable, irreplaceable, not reducible toprosthetic substitution-you can bet that no discord could have lastinglyarisen, whether about "parallelism" or "exorbitant" "privilege." This is notbecause it would be necessary to start from an undifferentiated sensibilityor a body without organs-quite the contrary-but from another organization (natural and technical, originary inasmuch as prosthetical) of whatis termed sensibility, the "body proper," or the "flesh"; and in the final account, without too much faith either in common sense or in a historicalculture that withholds its name and passes itself off as natural, or in thecommon sense of a culture that still forces us to count the senses on thefingers of a single hand, the hand of man-man always. There is not onesense-nor one, two, three, four, five, or six. We are to feel and count otherwise, and besides, we are doing it-that is how it goes. And that is whythe technical, that is to say, prosthetics, never waits. In the end, this is whatNancy, to me, seems to mean when he speaks of a "techne of bodies" -we'll talk about this again-and what these days comes under the some- Tangent III 20 5 Now, how can we explain, without prosthetic and tropological play, andwithout the originary supplementarity just designated, that Merleau-Pontycould make so much room for antagonistic motifs (or that he had to, lateror at the same time)-namely, for touching, distancing, noncoincidencethat dissociates within both seeing and touching, for the imminence of anever-concealed access, for interruption, the invisible and the untouchable-while having "parallelized" the senses of sight and touch, or, as a firstoddity, additionally conferred an "exorbitant privilege" on the former andremained so eloquent about confusion, coincidence, reflection, originarity,primordial presence, and so on? For The Visible and the Invisible is, in thisrespect, as rich a text as it is heterogeneous, and all the more profuse sinceit stays on the move and undecided with respect to all these alternativesand their logical consistency. It is impossible here to do justice to this greatwork "in progress," and especially to detect in it in a very rigorous fashionwhat serves as further development to The Structure ofBehavior28 and Phenomenology ofPerception. However, let us recall, for example-though toohastily-the attention given to "replacement" [suppteance] and "substitution," in Phenomenology ofPerception, thus to a certain spontaneous, quasipretechnical prosthetics, in the course of Merleau-Ponty's famous analysesof the "phantom limb,"29 the "unsound" or pathological sense of touch, or"potential [virtuel] " touch (ibid. , pp. I09, n8) . Let us also think of the difference that he explores between the "alleged 'purely tactile' which I try toextract by investigating blindness" and "integrated" touch, of the nonjuxtaposition between "tactile and visual data" in normal subjects (according to[Dr. Kurt] Goldstein); and especially of the synaesthetic unity of the senses,"intersensory unity of the thing," man as sensorium commune (Herder) :"Synaesthetic perception is the rule" (Merleau-Ponty, Phenomenology ofPerception, pp. 229, 235, 23 9) . "For the senses communicate with each other.Music is not in visible space, but it besieges, undermines [it]" (p. 225) . This206 Exemplary Stories of the "Flesh" language, which Husserl would have often judged too metaphorical, makesit permissible to speak of synaesthetic analogy finally grounded in a spatiality that is common to the visible and the tangible, as well as a touching "by the eyes," for example: "The very fact that the way is paved to truevision through a phase of transition and through a sort of touch effectedby the eyes would be incomprehensible unless there were a quasi-spatialtactile field, into which the first visual perceptions may be inserted" (ibid.,p. 223) · I t is insofar as vision that is properly spatial already "prepares" for this("the way is paved") and secures a "phase of transition" through "a sort oftouch effected by the eyes" that the "tactile field," which is only "quasispatial, " seems to come beforehand-so that the visible comes alreadybefore what comes before it. Vision properly speaking is ahead of whatnonetheless seems to condition it. Such a presentation of things is rathersignificant-and quasi-teleological, let us add. This presentation will persist in The Visible and the Invisible, in terms that are close to this (seeing "isbeing premeditated . . . the visible body provides for the hollow whence avision will come, inaugurates the long maturation at whose term suddenlyit will see, that is, will be visible for itself" [Merleau-Ponty, Visible and theInvisible, p. 147] ) . Indeed, although Merleau-Ponty gives the greatestweight to this synaesthesia, he never excludes a hierarchical order from it,and then confers on vision a heavy primacy, accompanied by an "it seems tome" as serious as it is authoritarian. For example, "the senses should not beput on the same basis, as if they were all equally capable of objectivity andaccessible to intentionality. Experience does not present them to us as equivalent: it seems to me that visual experience is truer than tactile experience,that it garners within itself its own truth and adds to it, because its richerstructure offers me modalities of being unsuspected by touch" (MerleauPonty, Phenomenology ofPerception, p. 234n1; my emphasis-J. D. [slightlymodified-Trans.] ) . This did not prevent him a little earlier from associating o n the same basis or plane-of "primordial contact with being"-"touch or sight," "seeor touch," and to state: "Thus the unity and the diversity of the senses aretruths of the same order" (ibid., p. 221; my emphasis-J. D.)-an ambiguous formulation that does not allow us to set things straight. Are the"truths of the same order" for diverse meanings that still become united,or for a diversity that is equivalent to a unity? In any case, if "our ownbody" proper is "as the heart," it is also a heart that sees or gives life to the Tangent III 20 7 living: " Our own body is in the world as the heart is in the organism: itkeeps the visible spectacle constantly alive, it breathes life into it and sustains it inwardly, and with it forms a system" (ibid. , p. 203) . Let us at last note that this same book very often (too often for an exhaustive survey) deals with the "example of the hand," the pair "eye andhand" (ibid. , p. 216 ) or the "set of manipulanda " (ibid. , p. 105) .3 0 (Thisconfirms to what extent this phenomenology of perception is an anthropology; it overshadows the problems of both animality and hominization.) In order to map things out at first, we can at least try to follow thedotted outline of a few of his lines when-without any betrayal or denial-their tracings scramble the statics of borderlines that would stabilizea "parallelism" or establish a "privilege." In The Visible and the Invisible, the matter of the looking eye will later,and everywhere, remain an overflowing theme, to be sure: at the origin ofthe world and the very notion of world, it knows no border, in a way-noexternal border. Still, this theme that spills overboard is visibly overrun atonce by knowing as well as by saying, first of all-even before the internalfold of a running border, which cannot be distinguished from it and iscalled the invisible, overruns it. Knowing and saying, on the other hand,can neither see nor be seen: "It is at the same time true that the world iswhat we see and that, nonetheless, we must learn to see it-first in thesense that we must match this vision with knowledge, take possession ofit, say what we and what seeing are, act therefore as if we knew nothingabout it" (Merleau-Ponty, Visible and the Invisible, p. 4) . By the same token, the eye's authority is questioned, or called into question, in the eye of the world, precisely: "But am I kosmotheoros? More exactly: is being kosmotheoros my ultimate reality?" (ibid., p. I I 3 ) . Likewise, we must take into account the original way in which h e treatsthe invisible, an invisible that is not intelligible or ideal, but an invisiblethat would not-though right at the visible-be "the invisible as an othervisible 'possible,' or a 'possible' visible for an other" (p. 229) . That is whywe must "raise the question: the invisible life, the invisible community,the invisible other, the invisible culture. [!] Elaborate a phenomenologyof the 'other world,' as the limit of a phenomenology of the imaginaryand the 'hidden'" (ibid., p. 229) .3 1 The singular motif of the invisible-visible invades everything; it is all atonce overflowing and overrun, exceeding its bounds or lost on its borders,internally coiled over a running border that puts its outside in-unless it 208 Exemplary Stories of the "Flesh" lets everything affect it, in particular everything that was up to then kept circumspectly and respectfully at bay, that is, beginning with "noncoinci dence," with which it seems henceforth that "I" no longer coincides so easily. And more hospitably now, it is the threshold of the sense of touch that is openly greeting noncoincidence, interruption, all that makes re versibility or reflexivity always inaccessible, and only imminent-the threshold of touch, certainly, but a sense of touch (in this instance de prived of any given reversibility between touching and touched) always conspicuously put on an equal footing-which should be an equal hand -with all the other "senses" or other organs of my body, sight or eye, hearing, ear or voice. This seems particularly obvious (or gripping, or bet ter grasped by the ear) in "The Intertwining-the Chiasm." Here, in the course of one of the most explicit definitions of "the flesh we are speaking of," the example of the hand comes pedagogically to drive the discourse, even there where this discourse is intent on demonstrating that feeling is somewhat "dispersed. " The argument is balanced and stretches between two poles, as if it wanted to say: there is some dispersion, but neverthe less . . . ! "There is no 'the' sense of vision," but nevertheless . . . there is "that central vision"! "There is no 'the' sense of touch," but neverthe less . . . there is "that unique touch"! Which moreover is like an "I think" that finally is nothing but my flesh. Among the remarkable traits of the passage quoted below, a continuous transition seems to proceed-as if on its own, as if this went without saying-from an infrastructural exem plarity of vision ("my visible is confirmed as an exemplar of a universal vis ibility . . . [thought] must be brought to appear directly in the infrastruc ture of vision") to the dispersion without dispersion of a "unique" way of'I touching of which the first example is "my hand. " Let us quote this argu I ment, therefore, from the moment when Merleau-Ponty makes use of the word " [we] touch" in a figurative sense to say "a second or figurative mean ing of vision"; and let us once more underscore the work of the example, the "exemplar, " or the "for example": At the frontier of the mute or solipsist world where, in the presence of other seers, my visible is confirmed as an exemplar of a universal visibility, we touch a second or figurative meaning of vision, which will be the intuitus mentis or idea, a sublimation of the flesh, which will be mind or thought . . . . Thought is a relationship with oneself and with the world as well as a relationship with the other; hence it is established in the three dimensions at the same time. And it must be brought to appear directly in the infrastructure of vision. Tangent 111 209 announcing and naming the concept of flesh, could not be said about any other living being, nor in any other way except in the first person of a hu man plural: that unique touch that governs the whole tactile life of my body as a unit, that I think that must be able to accompany all our experiences. We are proceed ing toward the center, we are seeking to comprehend how there is a center, what the unity consists of, we are not saying that it is a sum or a result; and if we make the thought appear upon an infrastructure of vision, this is only in virtue of the uncontested evidence that one must see or feel [why "see," at first? Why "see or feel"? What is the value of this "or"?-J. D.] in some way in order to think, that every thought known to us occurs to a flesh. (Merleau Ponty, Visible and the Invisible, pp. I45-46) It is fairly obvious that this "we," this "us," this "every thought known to us occurs to a flesh, " can imply nothing but a "we, men"; and that this concept of flesh, of the "infrastructure of vision," and finally and correla tively of "world," and "flesh of the world," can in no way refer to other "animals," other living beings. This would be less obvious if the precau tions Merleau-Ponty takes to withdraw his project from some anthropol ogy were more convincing, and if a discourse about the status and the rights of this "we" -as well as nonhuman or supposedly handless "ani mals"-were sufficiently developed at this point. My hypothesis, that is, that this "we" is a "we, men," does not seem to be contradicted by the very last "working note," which announces the "plan" of the book and purports to reject "any compromise with humanism," and any beginning "ab homine as Descartes" did. The projected blueprint would hardly have avoided such a "compromise, " I think; and we could probably say the same of the architecture of Phenomenology ofPerception. While the second part he announces (Nature) is a "description of the man-animality inter twining" (resembling Husserl's Ideas II, precisely in its middle section) , the third part is "neither logic, nor teleology of consciousness," but "a study of the language that has man." A privilege for man, therefore-man who is thus called, and, from this point on, called upon to answer for the logos that he does not have, to be sure, but that has him; and above all, which "is realized" solely "through man" and "in man." In truth, this logos is noth.'1 ing but the visible: " The visible has to be described as something that is re'i alized through man, but which is nowise [nullement] anthropology (hence against Feuerbach-Marx I844) " (ibid. , p. 274) . Tangent III 2II I s i t enough t o assert it? Doesn't this "nowise" [nullement} have the energy of a denial? How can something "be described" that "is realizedthrough man" without or beyond an "anthropo-logy"? An anthropo-logy?Especially if what is thus realized "through man" and "in man" is preciselyLogos, the Word? Using another "nowise," Merleau-Ponty further speaksof "Logos also as what is realized in man, but nowise [nullement] as hisproperty" (ibid., p. 2 74) .32 It is therefore always in the form of a denial-a fairly unconvincing denial-that Merleau-Ponty protests against an anthropological interpretation of his design. For example, when he undertakes to demonstrate that" [wJ hen we speak of the flesh of the visible, we do not mean to do anthropology, to describe a world covered over with all our own projections"and "it is indeed the paradox of Being, not a paradox of man, that we aredealing with here" (ibid., p. I36 ) , one of his arguments leads to hands, ourhands: "Yes or no: do we have a body-that is, not a permanent object ofthought, but a flesh that suffers when it is wounded, hands that touch?We know: hands do not suffice for touch-but to decide for this reasonalone that our hands do not touch, and to relegate them to the world of objects or of instruments, would be, in acquiescing to the bifurcation of subject and object, to forego in advance the understanding of the sensible andto deprive ourselves of its lights" (ibid. , p. 1 37) . What makes reading Merleau-Ponty s o troublesome (for me) ? Whatmakes the interpretation of his mode of philosophical writing a thing atonce passionately exciting and diffi c ult, yet also irritating or disappointing at times? It may be this, in a word: we reencounter the movement thatwe had evoked-this experience of coincidence with noncoincidence, thecoincidence of coincidence with noncoincidence-transferred to the order of (inconsequential) consequence or (interrupted) continuity in philosophical discourses, and in a way that is not always diachronic-following the evolution or mutation of a way of thinking-but synchronous attimes. Shall we give the philosopher credit for this, as I am often temptedto do, or, on the contrary, regret that he was unable to carry out a morepowerful reformalization of his discourse in order to thematize and thinkthe law under which he was thus placing himself-always, in foet, and allthings considered, preferring "coincidence" (of coincidence with noncoincidence) to "noncoincidence" (of coincidence with noncoincidence) ? Letus remain with our favored subjects, as they are treated in The Visible and the Invisible, and give a few examples of this. 212 Exemplary Stories of the "Flesh" And above all, the logic of this "extract" leads back-reasserting it-to this exemplarity of the hand and the finger, importing with it, in the think ing of flesh, the whole discursive machine that we are questioning here under the heading humanualism. For example (one month earlier) , adjustment and reciprocity govern everything: One would here have to study in what sense the other's sensoriality is impli cated in my own: to feel my eyes is to feel that they are threatened with be ing seen-But the correlation is not always thus of the seeing with the seen, or of speaking with hearing: my hands, my face are also of the visible. The case of reciprocity (seeing seen) , (touching touched in the handshake) is the major and perfect case, where there is quasi-reflection (Einfuhlung) , Ineinan der; the general case is the adjustment of a visible for me to a tangible for me $ 1 Tangent 111 21 5 and of this visible for me to a visible for the other-(for example, my hand) . (ibid., p. 245) Or again, a few months later, this point of the chiasmus where nothingseems to count but reciprocity: "So also the touched-touching. This structure exists in one sole organ-The flesh of my fingers each of them is = phenomenal finger and objective finger, outside and inside of the finger inreciprocity, in chiasm, activity and passivity coupled. The one encroachesupon the other, they are in a relation of real opposition (Kant)-Local selfof the finger: its space is felt-feeling" (ibid., p. 261) . It would be unfair and violent to reach a conclusion here and close theargument upon the reservations that this exemplarity of the hand, with allthat it implies, inspires. Such a closing would be unworthy of what remains open and at work in pages so strong, so alive, which have contributed so much to open a pathway for the thinking of its time, and ourtime. We shall proceed by questioning (always following Nancy's tracks) ,this time, this "other's sensoriality . . . implicated in my own" and this"crystallization of the impossible" that seems to sign the very last notes inThe Visible and the Invisible (March 1 9 61) : The defi n ition of the intuitus mentis, founded on analogy with vision . . . . This analysis of vision is to be completely reconsidered (it presupposes what is in question: the thing itself)-It does not see that the vision is tele-vision, transcendence, crystallization of the impossible. Consequently, the analysis of the intuitus mentis also has to be done over: there is no indivisible by thought, no simple nature . . . all these are "figures" of thought and the "ground" or "horizon" has not been taken into account. (ibid., p. 273)§ 10 Tangent IV 2I6r Tangent IV 217 so on. This list of names is far from being final or enclosable, and we shallhave the opportunity to specify this. Later, Aquinas or John of the Cross,for example, will appear in it. One can hardly isolate Husserlian phenomenology in the trend of theselegacies or filiations, to be sure. By the few signs that we have gathered upto this point, however, we can recognize that it retains a particularly strongand often hegemonic hold on the French zone of the said trend today. Thatis one of the reasons why I have laid such stress precisely on the MerleauPontyian interpretation or transformation, which has just detained us, ofthis phenomenology of touching. By following these lines of force on theFrench slope of this trend (let us repeat this in order to remove any possible misunderstanding), I am trying to understand how Nancy shares thingsout, and does this at least virtually. For as has been said, he almost nevercites Merleau-Ponty, even where there is enough room for us to assumethat he is familiar with Merleau-Ponty's thinking. Likewise, Nancy doesnot, I think, cite either of the two books that we are about to tackle (at firstsimply following the thread that links them to Husserl's Ideas II, our mainguideline here) : neither Didier Franck's nor-with one belated exception,to be specified subsequently-Jean-Louis Chretien's. As always in our Nancean use of these words, "sharing out" first of allmeans participation, indisputable proximity, affinities, crossings, crossoversand crossbreedings-a sort of community or contemporaneity of thinking,language, and discourse. I summarize this under the heading "tangency. " But they also mean something else-as always in the Nancean sense ofthese words-that is, a partitioning that imparts the parts, an other depar ture ("other departure" is a quotation from Nancy that I shall shortly clarify) , another way of proceeding, another writing, as well as the uneasy tur bulence of another determination (which is often concealed and barelydecipherable under the shelter of utterances seemingly stemming from thesame koine), another experiencing of decision making, another gesture ofthought, which is also another experiencing of the body, that is, anotherbody and another corpus. Let me put this bluntly, with just a few wordswhose meaning remains largely undecided: this difference, this partition ing, this alterity of bodies follows the line (a line that is often barely visible and still quite enigmatic) partly of the technical and partly of a beyond Chris tianity. The self-seeking body, seeking to touch itself without touching itself, like any other, throughout Nancy's corpus, is partly a body that is originarily and essentially friendly and open to the techne (transplantation, Tangent IV 219 1. I am culling the first one from two chapters, titled "Glorious Body"and "Incarnation"-in a book that continuously has it out with the historyof the Christian body, and thus with what we term "flesh." While here andthere I have questioned the translation of Leib as "flesh" [chair] (and weshall come back to this) and wondered about the extraordinary way inwhich this word and concept, "flesh" [fa chair] , has stretched across the220 Exemplary Stories of the ''Flesh'' the body of God, or the world of bodies, but nothing else. That is why, des tined to signify, oversignify, and insignify his body, man, the "man" of "hu manism," has slowly dissolved this body and himself all at once.) God had made himself into a body; he had stretched out . . . . This ambivalence of the truth of the body, as glorious body, works its way through all of ontotheology. . . . And if the body is, par excellence, what is created, if "created body" is a tau tology-or rather "created bodies," for (the) Body is always in the plural-then the body is the pLastic matter ofa spacing out without form or Idea. The body is the very plasticity of expansion, of extension, in accordance with which exis tences take place. . . But the body is a coming into presence, in the way and . tion for the techne of coming into presence. Techne: "technics," "art," "modal ization," "creation. ") . . . . Its coming, thus, will never be finished; it goes as it comes; it is coming-and-going; it is the rhythm of bodies born, bodies dying, bodies that are open, closed, bodies in pleasure, bodies in pain, bodies touch ing one another, distancing themselves. Glory is the rhythm, or the plastic ex pression, of this presence-which is local, bound to be local. Incarnation But all along this tradition, there is the other version of a coming into pres ence and its techne. The other, the same-they are indiscernible yet distinct, paired as in lovemaking. "The" body will always have been on the limit of these two versions, there where, at the same time, they are touching and push ing one another away. The body-its truth-will always have been the in between of two senses and ways-and among those, the in-between of left and right, up and down, front and back, phallic and cephalic, male and female, in side and outside, sensible sense and intelligible sense, do nothing but interact expressibly. Incarnation is the name of the other version of the coming. When I say ver bum caro factum est (logos sarx egeneto), I am saying in a sense that it is caro that makes for the glory and the genuine coming of verbum. But all at once I say-in another meaning altogether-that verbum (logos) makes for the gen" uine presence and sense of caro (sarx) . And though, in a sense and in a way (once more) , these two versions are part and parcel of one another, and though "incarnation" names them both together, yet, in another sense and another way, they exclude one another. (Nancy, Corpus, pp. 54-58) Tangent IV 223 If one reads on (as one needs to do) , one will perhaps see, in the place ofa certain "here lies" (although Nancy does not want any individual here) ,a persona making a comeback after twelve years, namely, Psyche, "ausgedehnt, weiss nichts davon," the mask or ghost of the reclining, extendedone, who knows nothing about this: ''A corpus is needed, which is to say awriting of the dead that has nothing to do with the discourse of Death-226 Exemplary Stories of the ''Flesh'' and everything to do with this: the space of bodies is not acquainted withDeath (fantasizing space abolished) but knows each body as a dead one,as this dead one who shares out for us the extension of his or her 'here lies'[ci-git] . It is not the discourse of being- toward-Death, but the writing ofthe dead ones' horizontality as the birth of the extension of all our bodies,all our more than living bodies" (ibid., p. 49) . To keep "giving the key" and inscribe what follows to resonate with itor rather serve as counterpoint, let us recall finally that Nancy is also verysensitive to the strange-aporetic-relation that Husserl's phenomenology, like everything that trails it, has with its own limit. It is a limit that it"touches" and "transgresses," too, by the same token. The aporia here consists in touching, attaining, reaching, and meeting a limit that bars anypassage, to be sure; but also, by the same token, in getting embroiled inthe contradiction that consists in passing the limit that one should notcross at the moment one touches it. In a passage evoked earlier, Nancyrefers to Husserl's Cartesian Meditations and specifies: "It is undoubtedlyhere, more than anywhere else, that Husserl shows how phenomenologyitself touches its own limit and exceeds it: it is no longer the egoical core,but the world 'as a constituted sense' that shows itself to be constitutive[Cartesian Meditations, p. 137] .3 The constitution is itself constituted. "4 I refer to this as an aporia because, first of all, concerning touch, everything started in this book with what Aristotle's Peri psuches already callsaporias. But it is also because the force of the remarkable book by DidierFranck, Chair et corps: Sur fa phenomenologie de Husser! (where we are aboutto follow certain pathways) particularly stems from its own tireless debatewith certain aporias of phenomenology.5 It is greatly to his credit that innaming them and analyzing them as such, he never seeks a pretext inthem that would lead him to a conclusive verdict of paralysis, or to criticize, discredit, disqualify, and even less to abandon or simply interruptphenomenological work-even when this work works against the principles it puts forward as its own. The first of these aporias seems to prohibit any access to what definedthe very perspective of the book, and its problematic and program, that is,an "analytics of incarnation,"6 which is simultaneously invited and prohibited by the need, indicated above all in the Cartesian Meditations, totake into account a "splitting of the ego" and the "pregiving [pre-donation]of the alter ego. "7 Although Franck mentions Merleau-Ponty only infrequently,S we can Tangent IV 227 imagine the virtual presence of the latter's way of treating flesh-and precisely in his relationship with Husserl. But we can also imagine a chargedsilence discreetly filled with implicit, virtual reservations about MerleauPonty's reading of Husser!, somehow surveying him from above, preciselyon the subject of Einfohlung and the alter ego. The first aporia would thushave to do with the closing of an egology, the reduction to the eidos ego inwhich intuition-like the variation that leads there-cannot fail to presuppose the giving of other egos. The alternative would then be between,on the one hand, a breaking away from solipsism "without phenomenological justification," and, on the other, the "skeptical absurdity" of a "transcendental empiricism. " Noting that this "aporia" "has not escaped Husserl's vigilance," Franck immediately announces that the "solution" mightcome by way of an analysis of the immanent temporality of the ego, whichwould bring out either a doubling of the flux, and thus the involvement ofthe alter ego in the eidos ego, or the taking into account of an "archefacticity" [UrfoktizitiitJ of the ego-two things that Husserl seems moreoverto recognize in a text from 1931 that Franck cites (Chair et corps, p. 6 7) :"Teleology. Implication o f the eidos transcendental intersubjectivity i n theeidos transcendental ego. Fact and eidos."9 Instead of going along with all the consequences that Franck drawsfrom this, step by step (it would be necessary to do this but is impossiblehere) , I limit myself, as always, to what touches on touching, and moreprecisely contact as "contact from oneself to oneself. " Now, after he hastaken into account the famous passages about touching in Ideas II, afterhe has answered "perhaps" to the question seeking to fi n d out whether"touching, as contact from oneself to oneself first of all," constitutes, inasmuch as it is fleshly, the support of localized sensations,lO Franck takes onthe theme (which he views as essential) of a sort of priority of flesh overimmanent time. He then comes to name contact ("which is to say contact, at bottom," he notes in parentheses) as the very thing itself ("flesh,"in truth, "touching, as contact from oneself to oneself first of all") that ispresupposed by immanent temporality itself and is therefore what wouldprecede time itself, by reason of this presupposition. Without flesh (that is,without contact) , there is no pure temporalization. Far from being firstand being only (as absolute proximity) the self-presence of a spatial here,contact is what makes possible the temporalization of time. Contact givestime-a formula that comes back more than once in these pages. But it isfrom an "absolute movement," not temporal and yet the origin of time,228 Exemplary Stories of the ((Flesh" I Tangent IV 229 out and parting of time? What relation with spacing and metonymies, plasticity, prosthetics, and technics, which are important for us here in the ecotechnics and techne of bodies? And so forth. I would invoke the double motif, which is classical in Husserl, of epoche and the nonreal [non-reelle] inclusion of noemata in the phenomenological life (Erlebnis) of consciousness here, if I had to bring forth arguments from a point of view that would be neither Nancy's nor Franck's (and yet would not oppose them) about what phenomenologically suspends contact in con tact and divides it right within tactile experience in general, thus inscribing an anesthetic interruption into the heart of aesthesic phenomenality. On the one hand, from the threshold of its possibility onward, epochal reduc tion suspends the reality of contact in order to deliver its intentional or phenomenal sense: this interruption or suspensive conversion gives me the sense of contact, as such. I therefore cannot fully have both contact and the sense of contact. For on the other hand-another interruption, another con version, another unpertaining [desappartenance]-the noematic content (corresponding to the includedness, which is then real, of a hylomorphic noesis or correlation) can only appear and can only be phenomenalized, by really pertaining neither to the touched thing (whatever it is, transcendent or immanent thing, my skin or the other's) nor to the stuff of my Erlebnis. Such is the law ofphainesthai. This double possibility (epoche and real non pertaining of the intentional sense content) would open up the spacing of a distance, a disadhering [desadherance] , a diffirance in the very "inside" of haptics-and aisthesis in general. Without this diffira nce, there would be no contact as such; contact would not appear; but with this diffirance, con tact never appears in its full purity, never in any immediate plenitude, ei ther. In both cases, the phenomenality, or the phenomenology, of contact is interrupted or diverted; it is suspended in view ofcontact. Such haptical (or aesthesic in general) diffirance, which is interruption, interposition, de tour of the between in the middle of contact, could analogically open onto what Nancy calls a "syncope" or what Chretien terms interval the "inter vallic character of touch itself," in a book to which we shall soon refer. 1 2 But whatever concrete, "technical," o r "prosthetic" form i t wears to deter mine itself between a skin and something, or between two skins (instru ments, veils, clothing, gloves, condoms, and so on) , this diffirance of the be tween, this elementary diffirance of inter-position or intervals between two surfaces is at the same time the condition of contact and the originarily spaced opening that calls for technical prosthetics and makes it possible,230 Exemplary Stories of the "Flesh" without any delay. What calls for "technics," then, is phenomenological necessity itself. It is not even a moment; it is an anesthetic instance, a unpertaining that maintains its hold on aesthesic appertaining or participation,and pertains to it-that is to say insensibility in, and as, sensibility; anesthetics as the very ecstasy at the heart of pleasure. Phenomenologies mustbow before the truth of this ecstasy-not give up in front of pleasure, butply it and pray. Faced with pleasure as diffirance. Ply, plait, pray, and inventsubstitutes, prostheses, fetishes, culture, technics-that is, all of "history,"as it were, before and beyond "the hand of man." Let us now come back to the passage in which Franck puts the word"precede" in quotation marks ("flesh must 'precede' temporality") . Thequestion comes down to the one raised by the conversion of omnitemporality into untemporality in the next paragraph. The nerve of the argument seems at the same time powerful and troubling, in accordance witha necessity that is logical yet arbitrary: for what "gives time, " what makestime possible, or even what is coextensive with time, that is, omnitemporal, would not be temporal, at least not in time. This argument interests ushere to the very extent that what is thus designated, what is supposedly"preceding" time-with all the consequences that Franck wants to drawfrom this-is a hyletic sensuality of flesh as contact, contact as self-contact: However strange this priority of flesh over immanent time may appear, stranger still is that this has not escaped Husserl. The latter had already im plied this priority in the text where he criticized his own analysis of internal time-consciousness and asked himself whether he should not presume a uni versal intentionality of impulses that would constitute all originary present and ensure the unity of the flux; 13 and he expressly acknowledges and recog nizes this priority in a 1930 manuscript: In the flux of primordial presence, we have a bodily perception, always al ready (immer schon) and immutably (unabdnderlich) ; and thus in the tem poralization of immanent time, my bodily perception continually goes through this whole time, omnitemporally constituting this body syntheti cally, identically. 14 (Franck, Chair et corps, p. 190) It will have been noted that Husserl here in no way speaks of any "priority" of flesh over time, though Franck gives him credit for not havingdisregarded this "priority. " Husserl speaks of omnitemporality, and con- Tangent IV 231 Let us come back to this configuration. Just before the opening of thechapter "The Caress and the Shock," Franck recalls the "aporias" that hehas followed in their development (ibid., p. 155) and concentrates this reminder around the notion of Verflechtung, interlacing [entrelacement] (now,at least since Merleau-Ponty, commonly translated into French by entrelacsand into English by "intertwining")-here, first of all, the intertwining between originary presentation and (indirect, analogical, empathic) appresen- Tangent IV 233 A. Translation. I have already evoked this delicate passage across the border between German and French. Since Merleau-Ponty, the more or lesssystematic translation of Leib by "flesh" [chair] may, strictly speaking, bej ustifi e d. We could substitute "flesh" for "body proper" for the good reasons that Franck gives for doing so (ibid. , p. 99 ) , 1 8 despite the risk of someunerasable connotations that "flesh" may risk importing, be it noted, wherethe question of the "Christian body" keeps reopening. To be sure, noteverything in the word "flesh" comes down to Christian semantics; asserting such a thing would be absurd or imprudent. However, it would beequally imprudent to ignore the filing and scraping action of this semantics, even where the ones using this word may be anything except "Christians" and would not for a single moment dream of putting their discourseabout flesh at the service of a Christian cause intentionally. Likewise, wecould justifY-strictly, but only in certain cases or contexts-the translationof Leibhafiigkeit by "incarnation." But don't things become less certain with regard to the translation of the use that Husser! and Heidegger, for example, make of the adverb or adjective leibhafiig? Or Leibhafiigkeit-when all this word does is constitute anoun based on the common use of the adjective? May one legitimately seein it a more or less thematic and deliberate reference to some flesh or in- 234 Exemplary Stories of the «Flesh" carnation, or, as Franck suggests, one that is denied, avoided, and re pressed? Besides, common sense itself stops us from believing that the ref erence to flesh and incarnation-beneath the word leibhaftig-is at the same time explicit or thematic (thus lending Franck the authority to trans late it steadily by "incarnate" or "carnally") and denied, avoided, repressed, in any case unacknowledged (which is also something Franck says: his the sis comes down to maintaining that, despite the frequent use of this word in some texts, in Heidegger as well as Husserl, "the question of the sense of flesh does not arise" [ibid., p. 2I] ; 19 hence, the translation of leibhaftig by "incarnate"-which is certainly not illegitimate-but also giving "incar nate" a powerfully vested meaning, which is an altogether different mat ter) . Neither in Husserl nor in Heidegger does this everyday expression (leibhaftig), in the quoted texts, necessarily refer to some living flesh, it seems to me, but only to what relates to the ipseity (Selbstheit) of the thing itself, to the experience of it that is given, without re-presentative or sub stitutive detour, whether this thing is present to intuition in general (in Husserl) or perceptive intuition (in Heidegger, about Husserlian phenom enology, that is, in the text that Franck cites: we'll come back to it) .20 This is so, even when this thing is not essentially living-no more than the ex perience that relates to it-and has neither flesh nor "bone" [n' a chair ou os] , nor anyone, or any person, allowing one to say, as one says all too often and easily in French, that it then presents itself in the "flesh and bone" [en chair et en os] , in theflesh, in person, which is to say, for example, an essence aimed at by an intuition of an essence [W"esensschau] or a transcendent ma terial thing aimed at by a perceptive intuition, such as this bridge about which Heidegger speaks in the text21 that is quoted at the beginning of a discussion deserving all the more to be closely followed in that it condi tions the problematic, the strategy, and the fundamental lexicon of Franck's original book. I suppose that the latter would be the first to know that he is carrying out an active displacement here-too violent, some might say; I would say, powerful in its interpretation-of the everyday use and our ear's traditional reception of the word leibhaftig. When he, in two instances,l. modifies Ricceur's translation of 1deen 122 and substitutes "incarnate" for "bodily" -already an equivocal risk, indeed-the result is not less am biguous, or less chancy, where it is only a question of the intuition of an essence in its ipseity.23 For the essence in question may be the essence of anything whatsoever and even of that which, though appearing to be leib haftig (an everyday expression, therefore, here to express the thing itself, Tangent IV 23 5 the thing appearing in a presentive intuition [intuition donatrice] ' and mostoften in a perception, but always without representative substitute) , doesnot necessarily have a "body proper" or a "flesh" -any more than (necessarily, essentially, structurally) does the intuition that tends to it. This equivocality started in France, as we know, where it was all too often thoughtnecessary to translate leibhaftig (the everyday, figurative term, as I wouldlike to insist-and risk a banality) by "in person" or "in the flesh" [en chairet en os] (alas, the Italian translation of Husserl also says in carne ed ossa) .But still-one could have understood the phrases "in person" or "in theflesh" in a weakly figurative fashion, as one can in German, I think, in theoriginal text, without turning everything that appears before intuition orperception (and therefore the world itself, if we follow Merleau-Ponty) intoa flesh in the proper sense, an incarnation, or a carnal thing. Franck must therefore reject both the everyday use of the word (whichis vaguely and conventionally metaphorical) and the reading of this use(which is also common, and vaguely and conventionally metaphorical) inorder to justifY his intervention and the systematic recourse to the lexiconof literal incarnation (if I may put it this way) in translating leibhaftig. Hedoes this in a complex passage; in it, I believe I can read an uneasy awareness, right after the sentence modified in Ricreur's translation of Ideen 1 towhich I have j ust alluded: One must not mistake incarnate givenness, which defines evidence in general (before any criticism and thus any problem concerning what is apodictic, for example) , for a metaphor, a manner of speaking, a trait proper to Husserl's style. There would be in this a double presupposition, possibly sharing the same root: first, the one concerning the trivial concepts of metaphor, utter ance, and style, which is rather ignorant about the part played by flesh in Husserl's analysis of language; second, the one concerning a phenomenologi cal state-of-things in itself, which is j uridically unconnected to any relation with flesh. Now, if one keeps to the second one, all of Husserl's analyses assert that flesh accompanies each perception-incarnate givenness in which flesh is all at once given and giving. (Franck, Chair et corps, p. 19) But can't we take Husserl's frequent use of the word leibhaftig to be conventional and metaphorical (indeed, "a manner of speaking, a trait properto Husserl's style") without giving in to a trivial concept of metaphor (that,on the other hand, we can deconstruct) ? Can't we legitimately dissociate itfrom the part that Husserl-on the other hand, elsewhere, within specific Exemplary Stories of the "Flesh" per) of the Leib, the Leibkorper that Husserl also discusses. Doesn't Franckhimself note this?25 And doesn't he specify it elsewhere, precisely on thesubject of appresentative pairing and the constitution of the other's body? If one firmly maintains the difference in meaning of bodily flesh and body, and if one holds to the very letter of this description [by Husserl in paragraph 54 of the Cartesian Meditations-Trans.] ' one can hardly see from where the sense bodily flesh might come ["the sense animate organism," in Dorion Cairns's translation of the Cartesian Meditations-Trans.] ; it can evidently not derive its origin from my body. What emerges from this is that the other body cannot take on any sense that my own body proper does not possess, and that the constitution of the other cannot take place. Husserl's use of the words Korper and Leib makes complete sense; he initially assigns them opposed mean ings but then uses them indiscriminately later on. In addition, when a body takes on the sense of bodily flesh and consequently the sense of bodily flesh in a world, bodily flesh belonging to another world, this signifies that it is by way of the incarnation of a body and the incorporation of a flesh that there is some world. When we have determined the conditions making this incarna tion and this incorporation possible, we shall have attained the origin of the world. ( Franck, Chair et corps, pp. 150-51) (Chair et corps, pp. 159-60) . About the constitution of flesh as physical flesh, that is, as "physical thing," there again Franck precisely speaks, already, of a "fundamental aporia" (ibid., pp. 98-99) . Though perplexed by these problems, I do not have at my disposal a satisfying linguistic solution for a regular, unequivocal translation of Leib -and especially leibhaftig or Leibhaftigkeit. I am not acquainted with any translation of these words that might fit within one word, and so I merely underscore the dangers that lurk in translating in a unique, regular, and systematic fashion, without any further precaution, the word Leib by "flesh," and especially leibhaftig by "in the flesh" [en chair] , "carnally" [charnelle ment] , or in an "incarnate" way [deforon ((incarnee"] . When one organizes an entire problematic and rests an entire interpretative handiwork and a program ("analytics of incarnation") upon such an "active" translation, doesn't one run the risk of effacing or cutting out the body, there where there is some remaining (some "body," proper or improper-or just body); and conversely, of adding some-when leibhaftig does not necessarily re fer to "body" or "flesh" ( proper or improper) ? When Husserl speaks of Leib-but much less, perhaps not at all, when he employs the word leib haftig-it is life that he implies (life, in phenomenology, is already an enormous problem-it has kept a fair number among us, including Franck, at work for quite some time) , yet very often the mind as well Hus serl often insists on the Geistigkeit of Leib or on geistige Leiblichkeit. By making flesh ubiquitous, one runs the risk of vitalizing, psychologizing, spiritualizing, interiorizing, or even reappropriating everything, in the very places where one might still speak of the non properness or alterity of flesh.26 falling to one's lot o r part) : the essential facticity o f this aleatoric event-focalization would set up a locus of resistance to eidetic variation. I would like to emphasize in this happy, lucky, and seductive condensation that it is accompanied by a series of terminological and programmatic decisions and performative naming acts (declared or not) , the justification of which remains elliptical or suspended at times. Here, now, isthe first interpretation of the tactile, of contact with oneself as contactwith the other, "pure auto-affection as pure hetero-affection": Originarily proper, flesh, the origin of the proper, is originarily unproper and is the origin of the unproper. More precisely: if my flesh is originarily constituted tactilely, that is, in the first stratum in the order of constitution [an implicit reference to Ideas 11, thus essentially giving credit to Husserl's text-J . D.] , this is a fortiori valid for the flesh of the other [why "a fortiori"?-J. D.] . And carnal relations, the refer ence of one flesh to another, are thus first ofall a con-tact [why "first of all" ? What if, b y reason o f the indirect appresentation o f the other's body-over there, of the other here-one had all at once to go through sight, and mirrors, or hearing, or smell? Or through an altogether different synaesthetic, or anes thetic, or already mechanical, organization?-J. D.]. Where does my flesh end if not where the other flesh makes itself felt to it [a elle sefait sentir] ? "Where ends" further means "where begins." My flesh is at its limit, on the verge of being exceeded, altogether on its own border, which is the border of the other -that is, mine. Husserl has grasped this co-belonging of flesh: "The apper ception of one's own bodily flesh [Leib; chair] and the apperception of the other bodily flesh [Leib; chair] essentially belong together. "27 The contact of oneself with oneself as contact of oneself with the other (pure auto-affection as pure hetero-affection) is the contact of one flesh with the other. (Franck, Chair et corps, pp. 167-68)28 This double naming not only presupposes that the defi n ition of carnal difference be originarily sexual-provided that a caress is always sexed (see the previous note and the questions that it raises) . It immediately associates the caress (of one flesh by another) with the shock (between two bodies) . Now, the caress is a shock; it is "also" a shock, says Franck: this presupposes that, while the caress cannot be reduced to "shock," it always implies some shock, just as flesh (Leib) always implies some body (Karper) . Further on, this is reiterated: "Originarily, intentionality is a carnal pairing; sexual dif ference, the caress and the shock determine its most general structure . . . . The origin of transcendence is the caress, but, immediately turning into shock, it is also its reduction" (ibid. , pp. 169 - 70) . Why two nouns, then-caress and shock? And where is one to locate any blow that, like a shock, also involves the flesh and not only the body (and yet the body as well)-if one is to keep this distinction and this trans lation of it? What if there were some blow struck within the caress? Where would one situate it, in this network of distinctions that all have to do with hapties? What does "immediately turn into" mean here? Does it im ply some originarity of the caress, some anteriority, be it subtle and in stantaneous, of the caress and therefore of fl e sh before the body? Would the caress come before the shock, as the flesh before the body? And before the blow? The answers to these questions are suspended here, but we can quickly perceive what is classically at stake in them-that is, whether or not the everyday appellation "body" (Karper) [corps] refers to something secondary or not. -J ' Tangent IV 241 such invariable and resisting variation), it will no doubt thwart the eidetic pre tensions of any constitutive analysis, to the extent that it intervenes in any constitution of transcendence (and let us keep in reserve the problem of tem porality) . No doubt, phenomenology thus demands an interpretation of this archefacticity to which Heidegger first dedicated himself. (ibid., pp. 168-69) Let us gather schematically what seems to set apart, from the outset andvirtually at least, this book by Didier Franck from Nancy's "corpus" as faras the themes that are important to us are concerned, without in any waydisputing or diminishing the originality of Franck's book and the need forit. No doubt, there hardly seems to be anything more necessary and convincing than to take into account the nonproper (the other, in a word) inthe sphere of the proper or my "flesh," with all the consequences thatFranck is right to draw from this. But doesn't this reckoning contend in242 Exemplary Stories of the "Flesh" "we, humans," oh yes, there are certainly enough things to say that are notsimple! But, first, this anthropocentric privilege (sometimes unavowed) , be ittranscendental, is not always consequent in relation to the most ambitioustranscendental reduction, the one that should suspend every thesis involving the existence of the world or in the world, including that of human beings. Second, this same privilege sometimes drives one to neglectwhat is not "human flesh," outside of the human world and sometimeseven in the human world (the Kihper- body) , technical prostheses, animalsin the human world and outside of it. Third, at the very point where acertain historicity of transcendental archefacticity is taken seriously (asFranck says and does) , this selfsame anthropological privilege tends toovershadow the historicity that produces-human-beings-and-technics, alwaysin a prosthetical way-what I have more than once, using common words,termed hominization or the emergence of "the hand of man. "34 Fourth,and finally, when this privileging of the human imparts itself too readily,it frees the path more easily-unless it has already entered it-toward thisanthropotheological, or even Christian, thinking of flesh, tactility, the caress, in a word, the Christian body, which I am not trying to denounce orreject here, but to "think"-"to ponder," "to weigh." § I I Tangent V Let us start over again. Let us come more directly to the double motif thatwe have been grazing against since the beginning-no doubt obliquely andvirtually, but insistently-while always tending to touch with tact. I. Jean-Luc Nancy's stated project of a "deconstruction of Christianity," 244 Tangent V 24 5 touch with something other than themselves and are touched by something other than the same self that touches: the touching cannot be thesame as the touched even when the touching touches itself Then someother is in itself. One does not touch when one touches nothing, when onetouches on nothing and tampers with it. There is nothing more logical, more logico-grammatical, nothing thatmakes more sense than this axiom. Hence the difficulty (let us not say theimpossibility) conferring on the untouchable the legitimacy, dignity, necessity, and the very signification, that we recognized for it in other discoursesand in di fferent senses, from Levinas to Merleau-Ponty, for example. Transivity does not let itself be reduced, even in the presumed reflexivity of selftouching (to which, incidentally, Chretien is a party from the very beginning [Lappel et la reponse, p. 102] ) . The difficulty lies not so much inreflexivity or reversibility, which Chretien acknowledges and takes into account (between me and me, i.e., Merleau-Ponty: "To touch is to touchoneself"-or between things and myself, i.e., Maldiney: "In touchingthings, we touch ourselves to them, as it were; we are simultaneouslytouching and touched."), but has to do with symmetry. There may be somereversibility or reflexive folding but it is in the exposed incurvation of adisymmetry. Chretien's initial statement ("This reversibility does not yieldany symmetry" [p 104]) fulfills itself in his modern repetition of Aquinas, o For the moment let us allow this yes to burn and its flame to rise; we'llsee a need for it later. Tangent V 24 7 Why, and how, can the "transitivity" be "foremost" and "radical" ? Hereis where the reference to Aquinas becomes necessary; it christianizes thishaptologics. Aquinas comments on and relaunches Aristotelian theologydealing with intellectual contact and the intellect's touching the intelligible(we spoke of this earlier) , and he thereby simultaneously asserts the immediacy of intellectual touching and the primacy of the intelligible. Spiritualtouching9 as pure act knows neither any intervallic medium nor any distance; it even transcends the value of affect. Being a touching without affection, an active and actual touching, it is no longer mediatized as "carnaltouching" would be. But for all its immediacy, it nonetheless remains"transitive." It is no longer simply flesh, but spirit already; it is no longertemporal or potential, but eternal-like the pure act or Aristotle's firstmover. Transitivity that is maintained is a transition from self to self-purereflection as pure transitivity. Hence a break from the phenomenology ofcarnal auto-affection, that is to say, from a sensible haptology. What thissays is that the sense of touching may not come from the senses; the propersense of touch is foreign to sensibility. Such is this story, this history extraordinaire-the ordinary story and history of Christian language: far fromtaking spiritual or intellectual touching for a metaphor of sensible touching, we on the contrary have to convert (it is a conversion, indeed) the interpretation of sensible touching so as to decipher in it the incarnate tropeand the carnal figure of a purely spiritual touch. This conversion is not arhetorical operation; it is a conversion of the body, its becoming-flesh. "Byactually touching the intelligible that it is itself, spirit eternally accedes toitself and transits from itself to itself. It becomes what it touches and as ittouches. The primacy of the intelligible is always clearly asserted. There isthus a radical difference from the 'my absolute contact with myself' ofwhich Merleau-Ponty speaks and from auto-affection" (ibid., p. 1 51) .10 By the same stroke (and this indissociability, this rigorous consequencemay be what gives this text its originality and impressive, imperturbableforce) , the Christian body of this conversion presents itself as a historicbody marked in its very essence by the historical event of revelation, Incarnation, the Eucharist, by the giving, the announcing, the promising,and the memory of "Hoc est meum corpus." There is no longer any denialwhatsoever of the body's historicity, no assertion of an abstract historicitywithout a history of touch, as in some phenomenologies of essential archefacticity, or some (Heideggerian) thinking of Offenbarkeit (revealability) asmore originary than Offenbarung (revelation) . It is as a Christian body that Exemplary Stories ofthe "Flesh" the Christian body presents itself here and signs itself, which is to say asthe post-sin, post-Incarnation historical body-as what it is, which is tosay as what it aspires to be, in spirit, in its truth. It is up to others todemonstrate, if they can bring proof, that they have nothing to do, see,make, and touch with the history and story of this truth. By the same stroke (and this stroke will not be long in converting itselfinto a fiery caress), the notion of contingency takes on a fully historical meaning, from its etymological contact with touching. Chapter 10 analyzed theremarkable condensation to which the word "contingency" gives rise inFranck's writing. Here, in a gesture that is analogous yet radically different(partially explaining the lack of a reference to Franck, no doubt), Chretienin his turn determines and emphasizes the word "contingency"-throughthe (originary and etymological) contact between touching (the self-touchingof the divine spirit that goes up in flames by itself) and the historical contingency of the creature that "comes after it" and lets itself be touched byit. Only since the history of creation, and then incarnation, does contingency have any sense. The creature is contingent. Contingency touches ontouch as the experience of created humanity-in historical time, foreverand eternally. Mter he has quoted Aquinas about touching the "first intelligible," Chretien thus produces, re-produces, or motivates the word "contingency": "It is from contact with itself as intelligible that the divine spiritis inflamed and sets itself on fire eternally, and it is by letting itself betouched that it sets on fire what comes after it. What is most necessary iscontingency itsel£ in the etymological sense of the term-the very contactfrom where the eternal flash of light [eclair] springs forth, from which allis suspended and all depends" (ibid., p. 1 5 1). Why this flame? A flame that sets on fire, no doubt (transitively) , but because it first sets itself on fire ("the divine spirit is inflamed and sets itself onfire eternally, and it is by letting itself be touched that it sets on fire whatcomes after it")? The flame is not only a figure for desire and love, whichwill soon inspire, aspire, and spiritualize this hapto-onto-theo-teleology ofChristian flesh (the Christian "repetition" of "desire" according to Aristotle,which we had already followed in Ravaisson) ; l l and as early as the next sentence: "Only the thought of love, however, gives flesh all its spiritual charge,and leads touch to its highest possibility" (ibid., p. 1 5 1). The flame is the becoming-love of Aristotelian desire (orexis) , because ittouches and affects, and it signifies first of all the spontaneity of a causa sui:a flame is inflamed and sets itself on fire; in any case, it seems to catch fire Tangent V 2 49 without any outside cause, and in this way, it is divine-like the First Moveror Pure Act, the thinking of thought,1 2 the desirable God who moves byhimself and inspires desire. But here Aristotle's God is infinitized. He wasalready discontinuous and transcendent in the scope of the sublunaryworld, and he now becomes infinitely distant or discontinuous without anypossible analogy with the world of creatures (though mediation by the Son,and Incarnation, as we shall see, may extend its hand to this analogy, oreven shake hands with it). By burning as if by itself (reflexively), the flametouches and inflames (transitively) . It is as if one had to start from fire tothink the touching of self-touching, and not the opposite. It would not only be from fire but from flames, since light is the jointmeaning of what is thus more than a figure-a light that self-touches,therefore, and touches itself and us, and that we can touch. But this haptical light of self-consuming flames eludes worship; it does not dwell, asan image to be adored. It is the truth of a light without idols and icons, aniconoclastic light-and its flame spontaneously burns down effigies. Thatis why we said it is "more than a figure," rather a transfiguration of figurality itself Touching, this luminous touching, becomes naturally moreiconoclastic than vision. "Presence without image and without representation," Chretien calls this luminosity (ibid., p. 1 5 2) . No wonder that thishaptologetics of the flame-if one can put it that way-intersects, sometimes literally, with Levinas's discourse about the caress ("intimate proximity" that "never becomes possession," "naked exposition to the ungraspable," and so on) Y This is, indeed, what immediately follows the passage just quoted. Hereis the flesh, then, the flesh itself, what is called the flesh, that which callsfor the Christian caress, and Christian love, and Christian charity; and wehad turned toward this flesh for such a long time, even while reading discourses on the flesh whose intentions were evidently not Christian (withMerleau-Ponty or Franck at the top of the list)-"flesh" to which "onlythe thought of love . . . gives . . . all its spiritual charge": What is most necessary is contingency itself, in the etymological sense of the term-the very contact from where the eternal flash of light [eclair] springs forth, from which all is suspended and all depends. Only the thought of love, however, gives flesh all its spiritual charge, and leads touch to its highest possibility. Indeed, from the finite to the infinite, all continuity breaks up, yielding to an increasingly forceful discontinuity, and all resemblance flourishes in an even more luminous dissimilarity. Contact with Exemplary Stories ofthe "Flesh" the infi n ite is necessarily of an order that is different from contact with the fi nite. (ibid., pp. 151-52) (The hand of the Father, then, the hand with which he touches us, isthe Logos and is the Son. This passage follows a discourse on the caress:Chretien cannot be certain that Aquinas gave it a mystical sense. Moreover the word "caress," as Chretien pens it, comes to translate and interpret Aquinas's contactus mutuus (and although Chretien's use of the wordis legitimate, it would be difficult to neutralize it) . This movement, fromthe caress to the Son, is also something that we have followed with curiosity and up to a point in Levinas. It is not the same Son, to be sure, although each time, in his ascent, in both Levinas and Chretien, he bearsthe initial capital letter of a proper name in the singular-the Son, theline to follow, in the direction indicated earlier.) 1 8 I purposely started at the end, which is to say, with the "spiritual touch,"the one that "no longer presents any medium or distance" and is no more"of the order of affection" than "auto-affection"; but that is also the one towhich "only the thought of love" gives "all its spiritual charge." When thehand of man corresponds with the hand of God in this "divine contact"whereby "flesh listens," when the "merciful hand of the Father" is the Logos (of) his Son, then in return one better understands both the generaleconomy of the book (titled L'appel et la reponse) and the logic proper to itslast chapter, "Le corps et Ie toucher" (The Body and Touch) . Indeed, itopens with the experience of ecstasy and excess. Where looking and hearing intersect, this experience is attested and delivers "the sense of thesenses," the carnal nature of the voice that itself presupposes the flesh of"our whole body." Chretien proposes many things that Husserl, as we recall, would have deemed equally frivolous and metaphorical or heretical forphenomenology as a rigorous science. And in fact, as we shall see, it is acertain phenomenology that Chretien disputes with, even while callingupon it respectfully. "Eyes listen and voices look on, ecstatically. The senseof the senses is the excess of sense, giving itself only through the word andwithin it. Now, there is no voice except a carnal voice, and our whole bodyis what it presupposes in order to be what it is, and what, in return, thevoice makes into its mouthpiece and thus into the highest manifestation ofspirit" (ibid., p. 101). How can self-feeling, which through suffering or pleasure characterizesthe "tactile body, in the widest acception of the word," open transitively onto excess or ecstasy? This is the place for the needed return to Aristotleand the common place for all the aporias wanting a solution, on the subject of a sense, the sense of touch, which has regularly been characterized, Tangent V 253 with the help of a great number of references and authorities, as "the mostfundamental and universal" (ibid., pp. 10 3 -4, II2, 12 7-2 9 , 1 33 ), "the commonest one" (pp. I04-II), and thus also the most "unfindable" (p. 108),the "hyperbolic sense" (p. II 9 ) . The final chapter's program and problematic are in fact already clearly announced in the book's introduction. 19 At this point, rather than reconstituting the linear path of this chapter'srich complexity (although the reader is invited to do so, and more thanonce), let me try to define a few edges instead-the ones seeming at thesame time to call for some questioning and to situate some partitions anddividing lines, from our point of view. As always, they are the parting linesthat bring one close to Nancy's corpus and depart from it all at once, atleast in the reading proposed here. and its superiority in humans: man is a tactile being; his very humanity depends on it" (ibid., p. 11 3 ) .22 What is properly man's, namely, the hand, once again corresponds to this excellence of the human sense of touch: "How is one to describe and specifY this excellence of human touching? The hand, proper to man, nat urally comes to mind because of its extreme tactile sensitivity and its power to discriminate and explore, to such a degree that some thinkers make it the privileged organ of touch" (ibid., p. 11 3 ) . Although things manual and human(ual) are o n a par here, as they so often are; although this teleological excellence of human touching is most often embodied in the hand; although the "hand" is the very thing itself that most often extends between human touching and divine touching (between the hand of man and, on the other side, the "merciful hand of the Father": Logos and the Son, the Word that "is" the Son), Chretien has to account for a fact that he deems "surprising and disconcerting": though Aristotle has, "in unforgettable pages," "meditated on the essence of the human hand," he seems not to "give any particular role to the hand" in the excellence of the sense of touch. "It behooves us to note," Chretien writes, "that Aristotle does not put the perfection of the human hand di rectly and expressly in relation with the perfection of human touching" (ibid., pp. 11 3 -14) . of the sensible body, that is, of the tangible, says Aristotle.) But what willdetain us here in the first place is that, as in Ravaisson's logic, just recalled,this (relative) silence about the hand finds itself invested with an evengreater spiritual or teleological power at the service of an end that is placedeven higher-an overbid for the hand. Aristotle keeps silent about thetactile hand (or about the digital touch [doigteJ) , and this is because heputs it even higher; it may be that the hand is an "organ of organs" that"can become anything because it is nothing, and in that way is like thesoul" (ibid., p. II4) .24 When he then wonders what to make of this silenceabout the feeling of fingers [doigte] and whether it is necessary to "speakup in Aristotle's place," as Galen did, Chretien also seems ready to "acknowledge this silence as heavily loaded with a strong philosophicalmeaning that invites thoughts of a sense of touch without organs, in asense still to be determined" (ibid., p. 11 5 ) . ther, and his Hand which touches us, that is, Incarnation, or the Word hisSon, and so forth. But simultaneously, and on the other hand, it is necessary to rely upon this Aristotle, and Aquinas, and then John of the Cross,and first of all on their transitivism, in order to go against or beyond another "modern" thinking of flesh that is phenomenological in kind. Thelatter thinking is deemed too reflexive, narcissistic, self-centered, or toocentered on its finiteness; hence the question that Chretien asks himself after wondering about Aristotle's "silence": "Does touching, which constitutes animal life, deliver up flesh, leaving it on its own to feel itself? Doesany continuity exist between the Aristotelian concept of flesh and its contemporary concept, which insists on its quasi-reflexivity-or on the contrary, should one separate them radically? Touching is the place of this decisive question" (ibid., p. 115) . The thinking of flesh wants a hand, and first of all God's hand, but onealso has to know how to do without the hand of man, or aim beyond itin any case. Then one has to come back from it all-and this is Incarnation, this is flesh-in order to receive the hand of man from God. Thequestion then comes back, but perhaps lacks the time to dwell as a question in this dwelling, and it comes to ask itself, and comes down to asking oneself whether the question is properly formulated, that is, formedin a fitting manner: what is a hand? What are hands? What gives the handits being a hand? More precisely: who gives the hand its being a hand?Who offers a hand? ation, which is to say the mediation between the mediate and the immediate-what an incarnation always is: "While this spiritual touch no longerpresents any medium or distance; while, as pure act, it is no longer of theorder of affection; while unlike carnal touching, which is always mediate,it is totally immediate, it is nevertheless unfailingly transitive. By actuallytouching the intelligible that it is itself, spirit eternally accedes to itself andtransits from itself to itself. It becomes what it touches and as it touches"(ibid., p. 1 5 1). B. Second translation. It is then sufficient to translate Aquinas into Johnof the Cross: "'This touch [divine touch, toque de la Divinidad] ' is a 'substantial touch; that is, of the substance of God in the substance of thesoul.' It takes place 'without any intellectual or imaginative shape or figure.' The 'merciful hand of the Father,' with which he thus touches us, isthe Son. Therefore it is the Word that is 'the touch that touches the soul'(el toque que toca al alma) . . . The flesh listens" (ibid., p. 1 53) . "Without any shape o r figure," then. The figuration o f the figure vanishes, as does the image from the imaginary. God's hand is no longer a figuration. One hands the hand of man in passing, one comes to pass throughit-the accepting and listening hand-but one immediately passes it anddoes without it. In the very passage itself. The hand of God is the hand inthe proper sense, beyond any icon, idol, or human tropologics. Moreover,human touching, in its very finiteness, in its mediacy, could already accedeto this-to this "presence without image." Let's read it again: "But touch,in and of its own finiteness, is precisely already open to a presence withoutimage and without representation, as well as to an intimate proximity thatnever becomes possession, and to an exposure naked to the ungraspable.Of what I touch and what touches me, the excess over me is endlessly attested in the caress" (ibid., p. 1 5 2) . The stroking hand that caresses no longer is a prehensile hand, then, ora knowing one, but rather a hand that is exposed, giving, and accepting;it is the hand of salvation, the God-ward goodbye hand.27 How can one go about the passage from the unfigurable, which is to say,the hand of God in its proper sense, to the figure of its figurative sense,which is to say, the hand of man? How about the passage from spiritualtouching, which is infinite and immediate, without "medium" or "distance," form or figure, to "carnal touching, which is always mediate"? Howabout the passage from the immediate to the mediate, and thus to flesh? Tangent V To all these questions, which come down to the same thing and which areall questions ofpassage, and therefore of transition and transitivity, and figural transfer, there is but one answer, it seems to me: passage, like Passion,Incarnation, Transubstantiation, "Hoc est enim corpus meum," and soforth, and the mediation between the infinite immediate and the finitemediate, just as between infinite and singular finite in general, betweenGod and Man: it is Logos fashioned into flesh, the Son, the Hand of theMerciful Father. Although this is doubtless also verifiable, I won't repeat here-to conclude for the time being, as in the preceding chapters-that this anthropotheological thinking of flesh does not leave any spare room for a questioning of technics (ecotechnics or the techne of bodies, to put it in Nancy'sterms) , nor of the animal, or rather animals, nor of the hominization process that produces what is termed the hand in "everyday" language, nor ofthe possibility of prosthetics onto which spacing in general opens, and soforth. (Transplantation of the heart, and even the Sacred Heart, is the locus here of a notable example, but I shall do no more than mention it.) Iwon't put it that way, although I believe it is just so. Indeed, it does seemas if everything in Nancy's thinking about exscription and the syncopeleads back toward this spacing (irreducible even in temporalization itself),which Chretien would reduce to this phenomenon of finitude, and finiteflesh that touching assigns to the interval, to mediatizing interposition,and to the "medium" and "distance" that spiritual touching (which is infi nite, immediate, etc.) will have first of all elevated, and uplifted and relieved.Indeed, Chretien makes room for spacing, as well as for everything thatdepends on it, but it is a finite place, which can be relieved, in the elevation of Logos and Incarnation. He also makes room for substitution, thatis, the figuration of the unfigurable, the hand of man, the heart of man, andso forth. And one could think of substitution as does Levinas (though hedoes not use this term in the same way) , or in a more literally Christianway, as does the tradition that leads to [Louis] Massignon. The Passion ofthe Son, Incarnation, Logos, Transubstantiation, Passion are substitutionscalling for Substitution or Imitation; and in a certain manner, here, too,there is a hominization process, but it is finally and always already the hominization of God, the gift of a God who makes himself into Man, throughthe mediation of the Son or the Word, and the Hand of the Merciful Father. This hominization is a humanization after thefashion of God, according to the Face and the Hand of God; it goes through this very Christian Exemplary Stories ofthe ''Flesh'' "death of God" of which we spoke earlier. And so forth. But Chretien willnever translate this substitution into any prosthetics, transplanting, ortechne-and especially not into a heart transplantation. And though theremay be some spacing in it, Incarnation will never be the phenomenon ofan irreducible finitude; it would never lend itself to thought in whatNancy terms "a finite thinking" for "the sense of the world." Two ways of thinking substitution, therefore, but two tangential ways-though no doubt incompatible. It is a rather troubling, even dizzying,duality, and may lead to the temptation-Temptation itself-to substitute one for the other. I can imagine, desire, and dread as well, as a "mortal sin," the least venial, perhaps the most serious and least expiable Temptation (because it isthe lightest) , that is, attempting, and letting oneself be tempted, to thinksubstitution without sacrifice. What there would remain to think is the place, the placing of this replacing, or the neutral spacing (chora, I might say) , that would still extendits hospitality to this virtual substitution of substitution, unless it shoulddetain it forever as a hostage. PA R T I I I -What about you? From where does this body come to us? The question is one and multiple, traditional yet still virginal, as if un touched, in spite of the plowing of philosophers and theologians. I knew, I thought I had known for a long time, that if there is a work of think ing today that measures up to this, to this question, and actually mea sures itself against it as the incommensurable, in acts of language and re flection, then it is Nancy's work, even when it doesn't acknowledge all the references that I have just evoked, beginning with Aristotle and the Gospels.3 I thought I had known this for a long time. To be sure, a search I• I (which may have been too hasty) through a number of Nancy's early works-roughly until the middle of the 1980s, and strangely including, therefore, The Experience ofFreedom-had shown us that neither the theme nor the figure of touch lays siege to his discourse, invests in it, or above all invades it, as will be the case-we can establish it today-in all his re cent publications. Let me insist that this is an issue of the theme and the figure-and this is more than just one difficulty among others. Because if there is "the" sense of touch, which is to say this motif of which Nancy speaks and that he now thematizes increasingly, while saying "there is no 'the' sense of touch," there are also-before or beyond this object of thought or dis course, beyond what is called touch [Ie toucher] , which he is henceforth dealing with-all these figural and apparently nonthematic operators with which he is continually playing (as I am doing here), through which and thanks to which Nancy has long since put touching into words, and said it and touched it. But insisting is not nothing. Even if it did nothing but bring to the light of day what was sleeping in the shadow, even if it exhibited literally, and as such (thus painfully baring its body) what had until then been a used-up metaphor, a familiar trope we use without paying much atten tion to it-well, this intensification of insistence is no longer a simple rhe torical movement. It comes down to thinking and to the thinking body of thought. Two examples: I am choosing them almost randomly in my index; for, on the score of "Touching," in Nancy's corpus, I have prepared for myself an index at the end of each book. An index is a certain order-a taxo nomic and deictic order, and also a way of obeying orders, under the thumb of the finger and the eye. From this index I would like to tackle a small number of entries. Why would such an index not be exhaustive even after one has reread the whole work, more than once, from beginning to "To self-touch you" I . The first example touches upon a figural manner of making use of thetactile schema. It is an example of "touch" in Nancy's language, or moreprecisely, an example of the manner in which Nancy touches on or tampers with language and what touches on language, in language, and forlanguage. The heart is never far away, his heart, first of all, which I do notwant to avoid mentioning. The heart is one of those interior surfaces ofthe body that, in principle (unless one performs the unimaginable, at leastfor now, operation of open-heart surgery on oneself) , no "self-touching"can ever reach-what might be termed the heart's hide.4 A thinking oftouch must at least go through a theory of skin. Now, what is skin, thepellicular, peau, peel, pelt, fell, or hide? In Corpus, Nancy has invented expeausition, a great and necessary word.5 The heart: absolute intimacy of the limitless secret, no external border,absolute inside, crypt for oneself of an untouchable self-interiority, place ofthe "act of faith" (about which we read in "The Deconstruction of Christianity"),6 inmost core of that which symbolizes the origin of life, withinthe body, by its displacement of it (metabole of the blood) . And yet nothing appears at least to be more auto-affective than the heart. But so manyof Nancy's texts have touched upon the heart over the past few years (thisdeserves another study intersecting with the present one) .7 Here, then, isone of the first examples I noted when I referred in a seminar a few yearsago to his "Linsacrifiable" ("The Unsacrificeable"),8 in which he analyzesthe remarkable denial whereby Western sacrifice is constituted, from Plato'sPhaedo to Hegel and to Bataille. A "deconstruction of Christianity" is thusalready announced. According to this analysis, it is a matter of the spiritualization, which is also a dialectization, of sacrifice, its sublation in autosacrifice or in the sacrifice of sacrifice. By denying itself, by denying in itself an ancient sacrifice, it covers over an infinite process of negativity withthe name of sacrifice, which is sacred or sacralizing. In doing so, it installsin its heart-"at the heart," says Nancy, at the "heart" of this process-thesacrificial destruction that it claims to go beyond or abandon. It repeats,one could say, the "ancient" sacrifice. The heart is not only the insensitivefigure of the center or of secret interiority; it is the sensible heart, the rhythm,respiration, and beating of the blood, the bloody heart or the bleedingheart, an uncircumcised heart (and further on Nancy evokes the "circum-268 Punctuations: "And you. " cision" of the heart):9 ''At its center, this double operation simultaneouslycombines, in an onerous ambiguity, the infinite efficacy of dialectical negativity and the bloody heart of sacrifice." 1 0 There then follow, in the next sentence, two instances of the word"touch." They deserve an infinite analysis, on the scale of that upon whichthey touch, namely, precisely, a process of infinitization, the very same onethat was questioned in the preceding chapter: "To touch upon this denial,or, to put it succinctly, this manipulation, is to touch upon this simultaneity; it is to be obliged to wonder whether dialectical negativity washedaway the blood, or whether the blood must, on the contrary, inevitably hemorrhage from it. In order to prevent the dialectical process from remaining a comedy, Bataille wants the blood to flow" (my emphases-J. D.) . l l I n this case, one may easily say that it is a question of a manner of speaking, of some kind of trope. Just try to find someone who has ever literally"touched" a denial. At times Nancy seems to be drawing on the fund of anold rhetoric that says "to touch" for "to concern," "to aim," "to think," "torefer to," "to speak of," "to take as its object," "to thematize" precisely, in aprecisely pertinent fashion, and so forth. But because, in the same sentence,one sees first the hands of "manipulation" (another figure but more strictlydeterminate) , next the "blood" rise up or take shape, the literality of"touch" thereby becomes more sensitive, nearer, less conventional. One begins to ask oneself: whence comes and what comes as the authorizing instance of this figure of "touch"? Why does one say "to touch" for "to speakof," "to concern," "to aim," "to refer to" in general, and so forth? Is it because touch, as Aristotle said, is not a "unique sense"? More and more,Nancy plays this game-the most serious game there is-which consistsin using, as if there were not the slightest problem, this common and ancestral figure of tactile language in order to draw our attention to "'the'sense of touch" itself-that there is not. He invests this very invasion that,little by little, prevents us from distinguishing between thematic sense andoperating function, between the proper or literal sense of this sense and allits tropological turns of phrase. When this nondistinction becomes troubling, one can no longer avoid eyeing this double writing. Is it touchingupon something or is it touching upon touching itself, there where, having more or less surreptitiously drawn our attention to the irreducible figure of touching, this writing makes us put our finger on language, touching itself by touching us and getting to us while making us notice what isgoing on with touching, to be sure in a manner that is as obscure as it.
https://ru.scribd.com/doc/36441506/Derrida-on-Touching-Jean-Luc-Nancy
CC-MAIN-2020-34
en
refinedweb
Execute a system command #include <stdlib.h> int system( const char *command ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The behavior of the system() function depends on the value of its command argument:; } ANSI, POSIX 1003.1 abort(), atexit(), close(), errno, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe(), exit(), _exit(), getenv(), main(), putenv(), sigaction(), signal(), spawn(), spawnl(), spawnle(), spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(), wait(), waitpid() Processes and Threads chapter of Getting Started with QNX Neutrino
http://www.qnx.com/developers/docs/6.5.0SP1.update/com.qnx.doc.neutrino_lib_ref/s/system.html
CC-MAIN-2020-34
en
refinedweb
Hi, i want to know the correct use of if else statement in groovy. I have a text file with the following content: c='0' in table x: a=N b=N a and b are saved in project properties tha i can retrieve in my test. Can someone confirm me if the following statement is correct: try{ if( a=='N' || b=='N' ){ assert c == '0' }else if ( a=='Y' || b=='Y' ){ assert c=='1' }catch (AssertionError e){ ... Question: if i put a==Y and b==Y in the first IF and put a==Y and b==Y Will work correctly? In my opinion it's not working, it asserts c==1 and we have a and b == N OK so see the follwing example: It should fail for me but it doesn't try{ def b = 14 def a =1 if(a == '2'){ assert a == b } }catch (AssertionError e) .... ok i found my problem, it works without try catch block . Yes Rao. But in my code there were more problems because some data were string and some not, so i first remove the try catch block then i convert my data correctly and i just use the if else and assert. it works well for what i was looking for. Sorry for all mistakes.
https://community.smartbear.com/t5/SoapUI-Open-Source/What-is-the-correct-use-of-IF-ELSE-statement-with-Groovy/td-p/192707
CC-MAIN-2020-34
en
refinedweb
ResourceCollection Class Represents a resource collection. Namespace: DevExpress.XtraScheduler Assembly: DevExpress.XtraScheduler.v20.1.Core.dll Declaration public class ResourceCollection : ResourceBaseCollection Public Class ResourceCollection Inherits ResourceBaseCollection Related API Members The following members accept/return ResourceCollection objects: Remarks The ResourceCollection class represents a collection of Resource objects. Its properties and methods can be used to perform common collection operations such as adding new or deleting existing items. Individual items can be accessed using indexer notation via the ResourceBaseCollection.Item property. The scheduler's resources are stored within its storage which can be accessed via the SchedulerControl.Storage property. The resource settings are stored in the ResourceStorage object which is returned by the SchedulerStorage.Resources property. Resources themselves are contained within the ResourceStorageBase.Items collection.
https://docs.devexpress.com/CoreLibraries/DevExpress.XtraScheduler.ResourceCollection
CC-MAIN-2020-34
en
refinedweb
String vs string (regex and GePrint) [SOLVED] On 29/10/2015 at 12:18, xxxxxxxx wrote: User Information: Cinema 4D Version: Platform: Language(s) : --------- Hi, one more question, maybe i'm doing it wrong (best choice !!) When I'm trying to get back value from a STRING resource i have to push it into a String object... When I'm trying to print some thing with GePrint("my life"), i have to push it from a String object... Nothing wrong ? But if i want to use regex or to_string() std::stoi("002") it can be painfull. I have to convert and juggle withs 2 different type of string. "String" came from C4D with #include "c4d_string" and "string" inside std library with #include <string> .... Finally my fist question is simple. GePrint() just want C4D String. So how did you do to print Int32, Float ? Can't it can convert it on the way ? And how did you do when you have to use std string for other library (my example is regex) ? Maybe my arm is in one of my eyes ?? I'm doing it wrong ? Thank in advance !! ;-) On 29/10/2015 at 15:21, xxxxxxxx wrote: FloatToString() and IntToString(). The String type in C4D is only useful in C4D. In order to do other things (like regex), you need first to get a C-style string (CHAR* ) using GetCString() and then set that to std string. For Unicode, it is even better. You get a unicode encoded Int16 block using GetUcBlock(). Have no idea how that block gets converted into a std lib wide-char string - might be system dependent as well. On 30/10/2015 at 02:58, xxxxxxxx wrote: Hello, as Robert already showed there are some convenience functions to convert basic datatypes to Strings: String::FloatToString(), String::IntToString() etc. You can also use FormatNumber(). We would like to remind all that one should not use classes from the standard library if possible. If it is needed to convert a String to a std::string this can be done with GetCStringCopy(): // This example converts the given String into a C-String to use it with the standard library. const String string = "foobar"; // convert to c string and insert into std string. Char* cstring = string.GetCStringCopy(); std::string stdString(cstring); DeleteMem(cstring); But if you want to use regular expressions you could also use the build-in class RegularExprParser. Best wishes, Sebastian On 30/10/2015 at 04:01, xxxxxxxx wrote: Many thanks for the code snippet. I'll keep in mind. Maybe you have the inversed one. I can't make work String::SetCString() ? I did one myself to convert String to string... Beware it's ugly. std::string timer_visibility::myToStringC(String& str){ std::string buffer; buffer.clear(); UInt32 j = str.GetLength() - 1; for (UInt32 i = 0; i <= j; i++) buffer.push_back(str); return buffer; } This is what I want to do, this is simple. I would like to enter frames number in a STRING resources and parse it like a printer dialog. So you can display and hide an object with this string 12,15,20-25,40 This way your object, with the selected tag, will be visible on the frame 12 , 15 and range from 20 to 25 and finally only visible on frame 40. So i need to verify value from user (to be sure of what he put in) with this regex "([0-9]+)([,-]{1}[0-9]+)*" And i need to split out my visibility string by coma(,) with a sregex_token_iterator. With all this groups i can find easily if the group is only one number. So it only one frame. Or if it's multi number with hyphen and this mean a range of frames. Maybe I'm creating a new wheel. Useful or not. My code is a bit dirty for the moment but almost working. The last split with hyphen (-) not work but I'll figure it out. I'll optimize my whole code after with your recommendations. On 30/10/2015 at 06:12, xxxxxxxx wrote: And to roll back i do this. Ugly too. String timer_visibility::myToStringC4D(std::string& str){ String output; char buffer; UInt32 l = str.length(); for (UInt32 i = 0; i < l; i++) output.Insert(i, Utf32Char(str _) ); return output; } _ On 30/10/2015 at 10:08, xxxxxxxx wrote: Hello, this code seems to work perfectly fine: std::string stdString("foo bar"); String str; str.SetCString(stdString.c_str(), stdString.length()); GePrint(str); best wishes, Sebastian On 30/10/2015 at 10:12, xxxxxxxx wrote: Hi, > So how did you do to print Int32, Float ? here is my older code for C4D String that allow to print Int, Float and other types. On 02/11/2015 at 04:29, xxxxxxxx wrote: Hi, Remotion4D. Thanks, your link and making this code public helped me to understand many things. I added it to my library S_Bach, greatful snippet ! I replace my own with your ! It's seems work perfectly. And Kuroyume0161 thanks your write. It just take me one day to remember to use String:: namespace... So String::FloatToString(); and String::IntToString(); are now my best friends. Thanks all, I'm a bit more confortable with C++ and the API now. So I see now how my question was simple. But it could be useful for anyone like me who didn't make c++ from many time and who discover in same time this API.
https://plugincafe.maxon.net/topic/9165/12165_string-vs-string-regex-and-geprint-solved
CC-MAIN-2020-34
en
refinedweb