text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Subject: Re: [boost] Request for comments on super-project workflow doc From: Peter Dimov (lists_at_[hidden]) Date: 2014-01-04 19:37:31 Robert Ramey wrote: > John Maddox brought up the question of "bridge libraries" (?) . An > example would be the serialization library includes tests for boost > variant but doesn't use boost variant itself. So if one includes just the > modules which the serialization library uses to build - you'll get one set > of modules which won't include the ability to run the test set. If you > include all the modules which test set requires, you're going to include > half of boost. Yes, in general, there are three sets of dependencies: what the library headers depend on, what the library sources depend on, and what the library tests depend on, each a superset of the previous one. This doesn't make such a tool worthless or impossible though. And - FWIW - bridge libraries are something else, I think. The problem there is that, f.ex. a library X may not depend on the serialization library but making X's types serializable would. A bridge library XS could solve this by depending on both X and serialization and providing the necessary support. In principle, I've always argued that libraries should be designed in such a way so that adding support should not require including a header, but that's not the path of least resistance and if one doesn't specifically keep that requirement in mind, it's rare to see it satisfied. (And it's not always possible.) For example, here's how the smart pointers provide hash support without including anything: namespace boost { // hash_value template< class T > struct hash; template< class T > std::size_t hash_value( boost::intrusive_ptr<T> const & p ) { return boost::hash< T* >()( p.get() ); } } // namespace boost and this is how a type may be specified to be a (boost::bind) placeholder, again without any inclusions: namespace boost { template<class T> struct is_placeholder; template<int I> struct is_placeholder< my_placeholder<I> > { BOOST_STATIC_CONSTANT( int, value = I ); }; } // namespace boost Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2014/01/210350.php
CC-MAIN-2019-18
refinedweb
362
60.35
FileUtilFileUtil statementstatement FileUtil is a small library for Scala to provide enrichment and utility methods for java.io.File. Where possible and useful, it tries to use the same method names as sbt, e.g. base and ext to obtain base file name and extension. It is (C)opyright 2013–2020 by Hanns Holger Rutz. All rights reserved. FileUtil is released under the GNU Lesser General Public License v2.1+ and comes with absolutely no warranties. To contact the author, send an email to contact at sciss.de. requirements / installationrequirements / installation This project compiles against Scala 2.13, 2.12 using sbt. The last version to support Scala 2.11 was 1.1.3. To use the library in your project: "de.sciss" %% "fileutil" % v The current version v is "1.1.5" contributingcontributing Please see the file CONTRIBUTING.md documentationdocumentation overviewoverview Typically you will import the contents of package de.sciss.file. This includes a type alias File for java.io.File, a simple constructor file("path"), and enrichtments for File, which allow for example to construct files in the manner file("base") / "sub" / "sub". import de.sciss.file._ // import type alias File for java.io.File, and enrichments (userHome / "Desktop").isDirectory // userHome is predefined, slash operator creates sub-files file(".").absolute // file(<string>) method creates file val x = file("foo/bar.baz") val (base, ext) = x.baseAndExt // split name and extension x.replaceExt("pdf") // -> foo/bar.pdf val tmp = File.createTemp() // temporary file (by default deleted upon exit) userHome.children(_.length > 4096) // list files in directory, using filter predicate Further methods on files such as relativize are available, as well as utility methods and object in the companion object, such as NameOrdering. See the API docs for a full overview. The regular Java methods on files are still available, such as .lastModified, .isFile, .isHidden, .length etc. API docsAPI docs The API docs can be generated via sbt doc.
https://index.scala-lang.org/sciss/fileutil/fileutil/1.1.2?target=_2.10
CC-MAIN-2021-10
refinedweb
322
62.04
API Load Testing With Gatling In this article, we'll learn how to perform a load test on a REST API endpoint using Gatling and JMeter. Read on for more information! Join the DZone community and get the full member experience.Join For Free Load testing is an important practice for APIs and applications that have lots of users. For load testing their APIs, developers can choose between many popular open source load testing tools. One of these is Gatling. This blog post will explain how to execute a load test with Gatling for a REST API endpoint that uses the GET method. Usually, this blog covers load testing with Apache JMeter™.. The environment we will be using is Java and Spring Boot API (an open source API framework), together with the Gradle build tool, as usual in my articles. Don't forget to install Gatling. Let's get started. 1. First, like in any library, we need to add the dependencies to our build.gradle file. testCompile group: 'io.gatling.highcharts', name: 'gatling-charts-highcharts', version: '2.2.5' 2. As mentioned before, Gatling uses Scala for test configuration. Therefore, we have to add plugin support to build.gradle. Run the following command: apply plugin: 'scala' 3. Next, we need to add a task for Gradle, so that we can execute our load tests from the command line. To do that, add the following code to the build.gradle file:", "BlazeMeterGatlingTest", "--results-folder", "${buildDir}/gatling-results", "--binaries-folder", sourceSets.test.output.classesDir.toString(), "--bodies-folder", sourceSets.test.resources.srcDirs.toList().first().toString() + "/gatling/bodies", ] }). 4. That's all the basic configuration we have to do for executing a Gatling test. Now let's create the actual test (simulation). For that, create a BlazeMeterGatlingTest file in src/test/scala folder with the following content: import io.gatling.core.Predef._ import io.gatling.core.structure.ScenarioBuilder import io.gatling.http.Predef._ import io.gatling.http.protocol.HttpProtocolBuilder class BlazeMeterGatlingTest extends Simulation { private val baseUrl = "" private val basicAuthHeader = "Basic YmxhemU6UTF3MmUzcjQ=" private val authPass = "Q1w2e3r4" private val uri = "" private val contentType = "application/json" private val endpoint = "/api/1.0/arrival/all" private val authUser= "blaze" private val requestCount = 1000 val httpProtocol: HttpProtocolBuilder = http .baseURL(baseUrl) .inferHtmlResources() .acceptHeader("*/*") .authorizationHeader(basicAuthHeader) .contentTypeHeader(contentType) .userAgentHeader("curl/7.54.0") val headers_0 = Map("Expect" -> "100-continue") val scn: ScenarioBuilder = scenario("RecordedSimulation") .exec(http("request_0") .get(endpoint) .headers(headers_0) .basicAuth(authUser, authPass) .check(status.is(200))) setUp(scn.inject(atOnceUsers(requestCount))).protocols(httpProtocol) } This our basic load test, which will do following: It will call 1000 times and make sure that we have status 200, meaning that it is fine. You can change this to your own API config and the number of requests, i.e the load. 5. Compared to JMeter, Gatling has an advantage in reporting. After each execution, you can see the path to the latest generated report in the command line. In my case, it is the following part of the command line output: Reports generated in 0s. Please open the following file: /Users/avagyang/Projects/blazedemo/build/gatling-results/blazemetergatlingtest-1503222349931/index.html BUILD SUCCESSFUL And when I point my browser to that path I can see the report shown in the pictures below. In the reports we have lots of useful information, the most useful part is on the first page directly where we can see request count (1000), passed requests count (OK), and failed request count (KO). This is the minimum that we need, but for our API improvements, we can take a deeper look into the details. For example, in case of errors we will have this: General Report Request_0 Report That's it! You now know how to run a load test for your API endpoint with Gatling. Published at DZone with permission of , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/api-load-testing-with-gatling
CC-MAIN-2021-43
refinedweb
652
50.33
Hi All, I'm currently researching the best way to store sensitive data on the various mobile platforms. My web service implementation uses OAuth2 for security so the plan is to initially ask for a users credentials to obtain the tokens (access and refresh) and then I'm going to store these instead of the users actual username and password. iOS Obviously iOS has had the KeyChain forever so that platform is a no brainer on the approach. Android Since we are targeting Android 4.0+ (API level 14+) this platform also has a KeyChain so we are good to go here as well. Windows Phone Is there a similar approach on the WP platform? I was initially thinking about using plain encryption but this would still require some input from the user or a static password embedded in the application that would complete defeat the entire exercise and it seems a little daft when there are device enabled approaches to leverage in order to properly hand off some of the security concerns to the hardware. The problem is I cannot identify if the WP platform has a similar feature that could be used. Any info would be great. TIA, J There is ProtectedData class in WP for the encryption/decryption. You can take a look at the ISecureStorage abstraction on XLabs.Platform for a sample. What an excellent thread! Many thanks Sami. Hi @JamesGreen.8031, Personally, I've gotten a lot of mileage out of this little routine: By using it to encrypt/decrypt individual string values and storing them using the usual methods. Kevin @KMullins that's very useful class. Good alternative if you want to keep things lightweight and not include too many dependencies. For a more comprehensive crypting library there is PCLCrypto as unfortunately the System.Security.Cryptography namespace is very limited on WP. @SKall, Good catch and addition to the conversation. Thanks, Kevin I've been looking at both of these (Kevin I found this class in another thread) and also started to implement something using this but it requires a users password. To me it just seemed to be moving the issue. If I hard code a password that would be negating some of the benefits, if I use a user password where would I store this so that I didn't have to bug the user for this password. That's essentially what I'm trying to avoid doing by storing the Tokens. Or am I missing something? Thanks for all the input guys, much appreciated. Also Kevin I don't know if this is related to my relative inexperience with the Xamarin/MvvmCross/PCL way of building apps but I couldn't get your class to work. I can get it to work if I include it in the Android application directly as that has access to the Cryptography namespace but used in a pure PCL environment (using the PCLCrypto lib from Andrew Arnott) it needs a bit of refactoring but could be done. That said I feel making use of the device native secure storage feels "more right" in the context of OAuth2 tokens. If you want to add some extra security instead of storing with embedded code then you could do a "PIN" + salt. The user enters short PIN number instead of the full password and that is used together with a salt. The security risk is you would still need to hardcode or store the salt somewhere. There are many ways to make it more (or less) secure but it is always a compromise between security and convenience. Hi Sami, Indeed I did think about doing the PIN thing as well. I'm still not settled on a solution yet. My server uses randomly generated salts and, like you suggest, all passwords are hashed prior to storage. More thinking needed! (as ever!) Thanks. Wow ... going through all the various options there really are a plethora of approaches and options. Sami, I really like your approach using the ISecureStorage interface however it looks like the Android KeyVaultStorage class makes use of a password argument in the constructor (not a problem of course just something to bear in mind at implementation time). Whereas the iOS SecureStorage class does not require a password and it looks like the WP8 version uses an SecureStorage class with an entropy option. I then had a look at the way Xamarin.Auth handles this and it looks like on iOS they make use of SecRecord and use the SecKind.GenericPassword option on Andoird they actually embed a password in the source (AndroidAccountStore class) which seems a little odd. I'm think I'm going to author my own Interface based MvvmPlugin and tailor it. So many options!! Ahhh ... I've just found this ticket on GitHub talking about the hard coded Android KeyStore password. How that ever made it into any released version is beyond me. The source code is bit of a mess in general to be honest. Oh, talking to myself again ... Just found this: ChristianRuiz/MvvmCross-SecureStorage EDIT Scratch using this library, this is not storing things in a secure manner at all and should not be used. On the Android platform it simply uses a private instance of ShardPreferences which is not in any way secured in terms of encryption. You can use the WP version with or without additional entropy (I think I put in a default null in there to mark it optional). If you need a parameterless constructor for IoC (should not be the case as most IoC containers will allow Func's) then you can always inherit from them with a custom class and embed the hardcoded password there. This is how I injected it for Android on XLabs sample: I wouldn't recommend using the device Id of course as that's just a demo application... Indeed, it seems from what I've read getting a consistent unique ID from the hardware is anything but straight forward as I was going to use that as a password. That said it seems that he most reliable way is through the TelephonyManager which my app will require as a permission so ... I don't like the idea of hard coding anything I don't have to, Then again the trade off is to be considered as well. Thanks Sami. This is the thread I mentioned where I found the TelephonyManager ID information Is there a unique Android device ID? I'm considering writing a class to handle the generation of this that could be run once to perform a setup routine on the secure storage, with a catchall "fallback" value if nothing is generated from the device. Could prove more trouble than it's worth however. I am dealing with this now as well, and I believe starting with Windows Phone 8.1 you can use the "Credential Locker" API which functions like the KeyChain on the other platforms (app specific storage and retrieval). See: @JamesGreen.8031 Hi James, dealing with these issues now myself...I don't like that most Android keystore solutions use the password in code...did you come up with a better solution? I was going to use Xamarin.Auth , because they don't seem to use a password for the Android keystore.. but on reading this post, its clear that they do (hardcoded). Secure Storage Plugin saves sensitive data in platform specific secure storage. @sameerk . I want to try your Secure Storage Plugin. Right now I'm stuck at the Android require password. Can you clarify about : "In Android, it is required that the password is set by the application prior to use" ? I have set the password in Android, but the apps still require set password. What does password here means? My Mac password? My project password? This is the password app would use to protect the data. You can assign the value of your choice. But obfuscate the app, so if someone reverse engineers the app, it cannot be retrieved. The new version of the Nuget 2.0 has a built in password for Android. This is the hardware id of the device. It can be reverse engineered (unless obfuscated.). But it is unique per device and not common for all apps. Hope this+ samples on GitHub help you. Ver 2.0 of the package is now available. It supports: . net standard UWP MacOS and Tizen The blog about whats new is here: @sameerk I used your plugin yesterday or the day before and it works really nicely (macOS for now). Now the issue being on how to correctly handle passwords in memory, without risking malwares getting a hold of them. Glad that the plugin was useful to you. The best practice to store sensitive data securely in memory is to use SecureString. I would retrieve the data using Secure Storage plug-in and store it in memory in SecureString. Hope that helps.
https://forums.xamarin.com/discussion/comment/129844/
CC-MAIN-2020-05
refinedweb
1,491
64
Code. Collaborate. Organize. No Limits. Try it Today. Once upon a time, there was a project where testers and advanced users had to have a tool to watch complex data. That's why I made a tool inspired by the Visual Studio QuickWatch. It has some extra features, in addition: A few months ago, I was asked to display data which consists of over twenty classes; each class has about ten different members. It was just too complex to make a one-purpose piece of code to display it. Especially it was almost impossible to maintain it because the data structure changes. So, how to automate the process? I use attributes to tag members that users should see: TreeLeafNodeAttribute TreeInternalNode Example: public class Catalog { [TreeLeafNode] public string name; [TreeInternalNode] public Source source; [TreeInternalNode] public List<Cd> cds; } Such an object is passed to the builder which is divided into three layers: The builder walks through all tagged members of a passed object recursively. To get the structure of tagged members, the builder uses the TreeStructure class to extract the structure using System.Reflection. The result is cached in a static hash table because it does not change during the application run. It's re-used in all later builder runs. TreeStructure System.Reflection static The builder distinguishes between two types of internal nodes: collections and others. If the item tagged with the TreeInternalNode attribute implements IEnumerable interface, it's displayed as a collection (see the cds node in the picture above) otherwise it's displayed as another internal node (see the source node). If the item with the IEnumerable interface implements the ICollection interface or is an Array in addition the number of items is displayed as well. The text of every displayed internal node is obtained by calling the ToString method on the node object (the same way like in the Quick Watch in the Visual Studio). IEnumerable ICollection Array ToString The BuildTitle method formats the appearance of leaf nodes. Strings are displayed in apostrophes, numbers without, decimal numbers are displayed with a precision at two decimal places. Dates are displayed as dates. There is a special NullDateTime property and if the date has the same value like it, it's displayed as null. BuildTitle NullDateTime null Names of all members can be translated to a user-friendly format if the TranslateName method is overriden. For example the member name TrxNum can be translated as Transaction number. TranslateName TrxNum The Catalog content is deserialized from an XML data file because it's just the simplest way to populate a structure with some data. In real applications, the structure is usually populated from a database or another data source. In this sample project, there is an additional functionality in the middle layer of the builder. It sets the Tag property of the TreeNode in every internal node and list item. If the node is selected, the user can serialize its whole content to a file which can be used later for reporting bugs or similar purposes. Tag TreeNode In fact, the middle layer can have various implementations. In the sample application, I use the standard System.Windows.Forms.TreeView. But our company uses our own visual components which are based on DataSets. The middle layer does not need to have a visual output at all. The output can be saved to a database or to an XML file. System.Windows.Forms.TreeView DataSet.
http://www.codeproject.com/script/Articles/View.aspx?aid=21444
CC-MAIN-2014-23
refinedweb
573
61.77
TL;DR: In this article, we are going to learn what tools we should take advantage of when developing NPM packages. We will start from scratch and create a GitHub Repository to host our package, then we will look into interesting and important topics. For example, we will talk about IDEs, we will configure ESLint in our project, we will publish the package on NPM and into the registry, and we will even integrate a continuous integration tool. The code that gave life to this article can be found in this GitHub repository. What NPM Package Will We Build After following all the steps shown in this article, we will have our own package published in the NPM package registry. The features that this package will support (and how to build them) are not the focus of this article. There are plenty of great tutorials out there that can teach us how to develop in Node.js. The focus here are the processes and the tools that we can use to build great NPM packages. Nevertheless, to give a heads up, we are going to build and publish an NPM package that masks raw digits into US phones. For example, if we pass 1234567890 to the package, it will return (543) 126-0987. The following list gives an overview of the topics that we are going to cover in this article: Git and GitHub > Creating the GitHub Repository > Cloning the GitHub Repository > Ignoring Files with Git IDEs (Integrated Development Environments) NPM Package Development > NPM Init > Semantic Versioning > EditorConfig > ES6+: Developing with Modern JavaScript > Linting NPM Packages > Automated Tests > Coding the NPM Package > Test Coverage > Publishing the NPM Package > Continuous Integration Conclusion Installing Node.js The first two prerequisites are Node.js and NPM (but that comes with Node.js). We could use the official Node.js download webpage to install these dependencies. However, the best way to install Node.js in a development machine is not through the official URL. There is a package called NVM (Node Version Manager) that provides a simple bash script to manage multiple active node.js versions. It's the best option because, with just one command, we can switch Node.js and NPM versions. Git and GitHub Besides Node.js and NPM, we also need Git and GitHub. Why are we going to use them? Because Git is the best, most advanced, and most used version control system and GitHub is the most used Git platform. The best open source projects in the world are hosted in this platform. For example, Node.js source code is versioned with Git on GitHub. Note that this article won't lecture about Git. If you are not familiar with Git, you will still be able to follow this article. However, every developer should learn how to properly use Git and GitHub. So, if needed, stop reading and go learn Git (and install it too, of course :D). You can come back later. Creating the GitHub Repository Great, we already decided where we will keep our source code safe. It's time to create the repository to start working on it. If we head to the Create a new repository web page on GitHub, we will see a form that asks for three things: repository name, description, and visibility. As we are building a module that handles masks, let's answer these questions as follows: - Repository name: masks-js - Description: A NPM package that exports functions to mask values. - Visibility: Public After that, GitHub gives us options to initialize the repository with a README file, to add a .gitignore file, and to add a license to our module. We will use all three options as follows: - Create README: Yes, let's check this box. - Add .gitignore: Why not? Less typing later. Let's choose Nodein this combo. - Add a license: Again, less work later. Let's set this combo to MIT License. Done! We can hit the Create repository button to finish the process. Cloning the GitHub Repository After creating the repository (which should be instantaneous), GitHub will redirect us to our repository's webpage. There, we can find a button called Clone or download that gives a shortcut to the URL that we will need. Let's copy this URL and open a terminal. On this terminal, let's choose an appropriate directory to host the root directory of our project (e.g. ~/git), and then let's clone the repository. The code snippet below shows the commands that have to be used to clone the repository: # choosing a directory to clone our repo cd ~/git # using git to clone git clone git@github.com:brunokrebs/masks-js.git # moving cursor to project root cd masks-js The last command will put our terminal in the project root. There, if we list the existing content, we will see four items: - A directory called .gitthat is used by Git to control the version of our code locally. Most probably, we will never touch this directory and its content manually. - A file called .gitignorewhere we keep entries that identify items that we do not want Git to version. For example, in the near future, we will make Git ignore files generated by our IDE. - A file called LICENSE. We don't have to touch this file, it contains a predefined content granting the MIT License to our code/package. - A file called README.mdthat contains just the name of our package ( masks-js) and its description. Ignoring Files on Git and NPM During the next sections, we will create some artifacts that we don't want to send to GitHub or to NPM. For example, our IDE will add some configuration files to our project root that we want to Git to ignore. Another thing that we want Git to ignore is the ./lib directory that we will create when publishing our package. This directory will only be shared on the NPM package itself (i.e. for developers downloading the package through NPM). Therefore, let's update .gitignore as follows: # leave everything else untouched .idea/ .vscode/ lib/ As we don't want NPM to ignore ./lib, let's create the .npmignore file. In this file we will add the following configuration: .nyc_output/ coverage/ node_modules/ .idea/ .vscode/ This will make NPM ignore these five folders, but not ./lib. Note that we are just removing folders that are not important to developers that want to use our package. Let's commit and push these changes to GitHub: git add .gitignore .npmignore git commit -m 'making Git and NPM ignore some files' git push origin master IDEs (Integrated Development Environments) Developing good software, arguably, passes through a good IDE. Among other things, IDEs can help us refactor our code, be more productive (mainly if we know their shortcuts), and debug our code. They usually help us by pointing out possible problems before compiling and/or running our code either. Therefore, this is a topic that cannot be put aside. On the Node.js/NPM environment, there is a good number of IDEs available. A few of them are paid and lot are free. However, in this author's opinion, there are only two IDEs that are really relevant: WebStorm and Visual Studio Code. WebStorm: This is a full-fledged IDE that provides great tools and has great support to everything related to JavaScript (e.g. TypeScript, HTML, CSS, SCSS, Angular, Git, etc). If it does not support some feature by default, it probably does so through plugins. The biggest disadvantage of this IDE is that it's paid. However, WebStorm is so good at what it does that it's worth the price. Visual Studio Code: This is another full-fledged IDE. It also comes with great support for Node.js and related technologies, just like WebStorm does. This IDE, in contrast to WebStorm, is free and open source. If you are wondering the difference between them, there are a few resources out there that compare both. For example, there is this article on Medium and this discussing on Reddit. Other options, although famous, cannot be really considered IDEs. That is, they can be considered IDEs if they are correctly configured with a bunch of plugins. However, why waste time on these kind of configuration when we can choose a good IDE that is ready to help us? If you are still interested on seeing what other "IDEs" are available, there are resources out there that show more options and their differences. What is important in this section is that we understand that we do need an IDE and choose one. This will help us a lot during the development lifecycle of our package. NPM Package Development Now that we have chosen our IDE, let's open our project and start configuring it. Throughout the next sections, we are going to create our project structure and configure tools that will help us produce high-quality code. NPM Init First things first. As our goal is to create and publish a NPM package, we need to initialize our project as one. Luckily, this process is straightforward. NPM, through its CLI (Command Line Interface), provides two great ways to configure a project as a NPM package. The first one, triggered by npm init, will ask a bunch of questions and produce the package.json file for us. The second one, triggered by npm init -y, will not ask any question and produce the package.json file with default values. We will stick with the second option, npm init -y, to get our file as fast as possible. Then, we will edit the package.json content manually to look like this: { "name": "masks-js", "version": "0.0.1", "description": "A NPM package that exports functions to mask values.", "main": "build/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+" }, "keywords": [ "npm", "node", "masks", "javascript" ], "author": "Bruno Krebs", "license": "MIT", "bugs": { "url": "" }, "homepage": "" } Important: the JSON snippet above contains three URLs that point to. We need to replace them with the URL of our repository on GitHub. Two properties in the file above may bring our attention. The main property now points to build/index.js and the version property labels our code as being on version 0.0.1. Let's not worry about them now, we will discuss about these properties in the following sections. Let's commit and push these changes to GitHub: git add package.json git commit -m 'initializing project as a NPM package' git push origin master Semantic Versioning In this section, we are not going to change anything in our project. The focus here is to talk about how to label new releases of our package. In the NPM and Node.js landscape, the most used strategy is by far Semantic Versioning. What makes this strategy so special is that it has a well-defined schema that makes it easy to identify what versions are interoperable. Semantic Versioning, also known as SemVer, uses the following schema: MAJOR.MINOR.PATCH. As we can see, any version is divided into three parts: MAJOR: A number that we increment when we make incompatible API changes. MINOR: A number that we increment when we add features in a backwards-compatible manner. PATCH: A number that we increment when we make small bug fixes. That is, if we have a problem with our code and fix it simply by changing an if statement, we have to increment the PATCH part: 1.0.0 => 1.0.1. However, if we need to add a new function (without changing anything else) to handle this new scenario, then we increment the MINOR part: 1.0.0 => 1.1.0. Lastly, if this bug is so big that requires a whole lot of refactoring and API changes, then we increment the MAJOR part: 1.0.0 => 2.0.0. EditorConfig EditorConfig is a small configuration file that we put in the project root to define how IDEs and text editors must format our files. Many IDEs support EditorConfig out of the box (including WebStorm and Visual Studio Code). The ones that don't, usually have a plugin that can be installed. At the time of writing, EditorConfig contains only a small (but useful) set of properties. We will use most of them, but two are worth mentioning: indent_style: Through this property, we define if we want our code to be indented with tabs or spaces. charset: We use this property to state what charset (e.g. UTF-8) we want our files encoded into. To set up EditorConfig in our project, we need to create a file called .editorconfig in the project root. On it, we define how we want IDEs to handle our files: # Editor configuration, see root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true Note: EditorConfig can handle multiple configuration blocks. In the example above, we added a single block defining that all files ( [*]) must be encoded in UTF-8, indented with spaces, and so on. However, we could have defined that we wanted XML files ( [*.xml]) to be indented with tabs, for example. Although subtle, EditorConfig is an important step into producing high quality code. More often than not, more than one developer will work on a software, be it a NPM package or anything else. Having EditorConfig in place will minimize the chances of a developer messing with our code style and the encoding of our files. Let's commit and push .editorconfig to GitHub: git add .editorconfig git commit -m 'adding .editorconfig' git push origin master ES6+: Developing with Modern JavaScript JavaScript, as everybody knows, has gained mass adoption as the primary programming language over the last few years. Node.js was primarily responsible for this adoption, and brought with it many backend developers. This triggered a huge evolution of the language. These evolutions, although great, are not fully supported by every platform. There are many JavaScript engines (and many different versions of these engines) in the market ready to run code, but most of them do not support the latest JavaScript features. This rich environment created one big challenge for the community. How do we support different engines and their versions while using JavaScript most recent features? One possible answer to this question is Babel. Babel, as stated by their official website, is a JavaScript compiler that allows developers to use next generation JavaScript today. Note that Babel is one alternative. There are others, like TypeScript, for example. Using Babel is straightforward. We just have to install this library as a development dependency and create a file called .babelrc to hold its configuration: npm install --save-dev babel-cli babel-preset-env echo '{ "presets": ["env"] }' >> .babelrc With this file in place, we can configure a NPM script to make Babel convert modern JavaScript in code supported by most environments. To do that, let's open the ./package.json file and add to it a script called build: { ... "scripts": { "build": "babel ./src -d ./lib", ... } ... } When we issue npm run build, Babel will take the source code found in the ./src directory (which can be written in modern JavaScript) and transform it to ECMAScript 5 (the most supported version of JavaScript). To see this in action, let's create the aforementioned ./src directory in the project root and add a script called index.js into it. To this script, let's add the following code: function sayHiTo(name) { return `Hi, ${name}`; } const message = sayHiTo('Bruno'); console.log(message); Although short, this script contains code that is not supported by ECMAScript 5. For example, there is no const in this version, nor it accepts Hi, ${name} as a string. Trying to run this code into an old engine would result in error. Therefore, let's use Babel to compile it: npm run build After asking NPM to run the build script, we will be able to see that Babel created the ./lib directory with index.js in it. This script, instead of our code above, contains the following: 'use strict'; function sayHiTo(name) { return 'Hi, ' + name; } var message = sayHiTo('Bruno'); console.log(message); Now we do have a code that ECMAScript 5 engines can read and run. Now we can take advantage of the latest JavaScript features. Before continuing, let's commit and push the changes to GitHub: git add .babelrc package-lock.json package.json src/index.js git commit -m 'supporting ES6+ syntax' git push origin master Linting NPM Packages Another important tool to have around when developing software is a linting tool. Lint is the process of statically analyzing code for common errors. Linting tools, therefore, are libraries (tools) that are specialized in this task. In the JavaScript world, there are at least three popular choices: ESLint, JSHint, and JSLint. We can use any of these three libraries to lint our JavaScript code, but we have to choose one. There are many strategies that we can follow to decide which tool we should use: from a simple random decision to a decision based on a thorough analysis. Though, to speed things up, let's take advantage of a fast (but still good) strategy: let's base our decision into data. The following list shows how many times each package was downloaded from NPM on Nov/2017, how many stars they have on GitHub, and what are their search volume in the US: - ESLint was downloaded 10 million times from NPM, has 9.6 thousand stars on GitHub, and is searched around 1300 times per month in the US. - JSLint was downloaded 94 thousand times from NPM, has 7.5 thousand stars on GitHub, and is searched around 750 times per month in the US. - JSHint was downloaded 2 million times from NPM, has 3 thousand stars on GitHub, and is searched around 750 times per month in the US. Following the strategy to base our decision on data results, without doubt, into choosing ESLint as the winner. The numbers don't lie, ESLint is the most popular tool in the JavaScript landscape. So let's configure it in our project. Installing and configuring ESLint is easy. We have to instruct NPM to install it for us, then we can use the --init option provided by ESLint to generate a configuration file: # saving ESLint as a development dependency npm i -D eslint # initializing the configuration file ./node_modules/.bin/eslint --init The last command will trigger a series of questions. Let's answer them as follows: - How would you like to configure ESLint? Use a popular style guide - Which style guide do you want to follow? Airbnb - Do you use React? No - What format do you want your config file to be in? JSON This will generate a small file called .eslintrc.json with the following content: { "extends": "airbnb-base" } What is nice about ESLint is that it also enables us to adhere to popular style guides (in this case the Airbnb JavaScript Style Guide). There are other popular styles available to JavaScript developers and we could even create our own. However, to play safe, we will stick to an existing and popular choice. Great, sounds good to have a tool that help us avoid common mistakes and keep our code style consistent, but how do we use it? It's simple, we configure it in our build process and we make our IDE aware of it. This way we get alerts while using the IDE to develop and we guarantee that no developer, unaware of ESLint, generates a new release with inconsistencies. To add ESLint to our build process, we can create a new script that executes ESLint and make it run in the build script: { ... "scripts": { "build": "npm run lint && babel ./src -d ./lib", "lint": "eslint ./src", ... }, ... } This way, when we execute the build script, the process will abort before starting Babel if ESLint finds issues in our code or code style. Now, the steps to integrate ESLint in our IDE will depend on which one we are using. Both WebStorm and Visual Studio Code have special sections on their documentation to cover ESLint. Note: other IDEs and text editors probably provide support to ESLint as well. "Linting tools can help us identify potential errors in our code." To wrap this section, let's commit and push changes to GitHub: git add .eslintrc.json package*.json git commit -m 'configuring ESLint' git push origin master Automated Tests One of the most important topics in software development is tests. Developing high quality code without automated tests is impossible. That is, we could write code that executes flawlessly without writing a single line of automated tests. However, this code would still not be considered as having high standards. Why? Simple. Imagine a situation where we wrote a code that contains no bugs. One day, another developer decide that it's time to increment this code by adding some nice new feature. This feature, however, needs to reuse some pre-existing code and change it a little. How, without automated tests, is this developer supposed to test the new version? Manually testing is an alternative, but an arduous and error-prone one. That's why we invented automated tests. As everything in JavaScript, there are many tools that can help us automate our tests. Besides that, there are also different types of automated tests. For example, we could write end-to-end tests, integration tests, and we could write unit tests. The goal of our NPM package is to, based on an inputted string, return a masked value. This kind of package does not have external dependencies (like a RESTful API) nor it will be rendered in an interface (like a web browser). Therefore, writing only unit tests to guarantee that our functions do what they are supposed to do will be enough. Cool, we now know what type of tests we will write. What is still uncovered is what library will we use to write these tests. Since the data strategy is doing well, let's use it again. After a small research on Google, we find out that there are three great candidates: - Mocha: a test framework that supports both Node.js & the browser, has 14.1 thousand stars on GitHub, and was downloaded 64 million times during 2017; - Jasmine: a platform-agnostic test framework that has 13.1 thousand stars on GitHub and was downloaded 22 million times during 2017; - and Jest: a test utility developed by Facebook with 14 thousand stars on GitHub and that was downloaded 21 million times during 2017. In this case, the numbers were pretty similar. But Mocha, with more stars on GitHub and around three times more downloads on NPM during 2017, looks like the winner. We will probably be supported by a great community and have access to a lot of resources if we choose Mocha. So let's configure it in our project. First, we need to install Mocha as a development dependency: npm i -D mocha Then, we need to replace the test script in our package.json file by the following one: { ... "scripts": { ... "test": "mocha --require babel-core/register" }, ... } Note that, as we also want to use modern JavaScript in our tests, we used Mocha's --requireoption to make Babel compile our test code. That's it! We can now write our tests. To see Mocha in action, let's create a directory called ./test and add an index.js file to it with the following code: import assert from 'assert'; describe('Array', () => { describe('#indexOf()', () => { it('should return -1 when the value is not present', () => { assert.equal([1, 2, 3].indexOf(4), -1); }); }); }); If we issue npm test in the project root, we will see that Mocha manages to run our test properly. Even though we used modern syntax like import and arrow functions ( () => {}). If we are using a good IDE, we will probably be warned that there are no describe nor it functions available in the ./test/index.js file. This happens because ESLint is not aware of these functions. To make ESLint recognize Mocha's functions, we need to make a small change into the .eslintrc.json file. We need to add a new property called env and add mocha into it: { "extends": "airbnb-base", "env": { "mocha": true } } As usually, let's commit and push changes to GitHub: git add .eslintrc.json test/index.js package*.json git commit -m 'adding Mocha' git push origin master Coding the NPM Package Hurray! We finally got into what matters, the code. We can create NPM packages without most of the tools shown in this article, but code is just necessary. No code, no NPM package. Although code is so important, it's not the focus of this article. So, to keep things short and easy to grasp, let's create just a very small prototype. We will create and export only one function that returns a masked US phone. Even for a specific and precise functionality like this, there are many scenarios to cover. But again, we will keep our focus on the tools and techniques we can use to produce high-quality code, not in the coding and testing tasks themselves. Enough said, let's work. First, let's replace the content of the ./src/index.js file with the following: // != 10 if (digitsOnly.test(phone) === false || phone.length !== 10) { return phone; } // returning the masked value const codeArea = phone.substring(0, 3); const prefix = phone.substring(3, 6); const sufix = phone.substring(6, 10); return `(${codeArea}) ${prefix}-${sufix}`; } export default maskUSPhone; Then, let's replace ./test/index.js content with this: import * as assert from 'assert'; import maskUSPhone from '../src/index'; const testSamples = [ { input: 'abc', expectedResult: 'abc', description: 'should return pristine value when receiving "abc"' }, { input: 'abc1234567', expectedResult: 'abc1234567', description: 'should return pristine value when receiving "abc1234567"' }, { input: 'abcdefghij', expectedResult: 'abcdefghij', description: 'should return pristine value when receiving "abcdefghij"' }, { input: '1234567890', expectedResult: '(123) 456-7890', description: 'should return (123) 456-7890' }, { input: '5431260987', expectedResult: '(543) 126-0987', description: 'should return (543) 126-0987' }, ]; describe('Array', () => { testSamples.forEach((sample) => { it(sample.description, () => { assert.equal(maskUSPhone(sample.input), sample.expectedResult); }); }); }); Good. This creates a function to support the functionality mentioned, and probably covers enough tests. Issuing npm test in the project root will make Mocha execute our tests. Let's commit and push our new code to GitHub: git add src/index.js test/index.js git commit -m 'developing the maskUSPhone feature and adding unit tests' git push origin master Test Coverage Feels good to have our code in place with some tests to prove its functionality, but how confident are we of our code and our tests? Are we sure that our tests are covering all the scenarios that we thought about? It's hard to affirm that even in a small package like ours. So, what can we do? The answer is simple, we can use a test coverage tool to see how much of our code we are covering with tests. Test samples, like those showed in the previous section, exist to help us prove that our code handles all the scenarios that we thought about. Test coverage tools help the other way around. They show if we have enough test samples to cover all the scenarios that came to our mind when typing the code. Ok, we are convinced that we can take advantage of a test coverage tool, but which one? After searching for "javascript test coverage tools" on Google, we find out that Istanbul webpage appears in first place, it's NPM page appears in second, and Karma (the test runner) appears in third place saying that it can generate test coverage using the awesome Istanbul. Probably enough proof that we can trust this tool. So let's use it. Instructions to use Istanbul are simple. First, we install Istanbul as a development dependency: npm i -D nyc After that, we just update the test script (in package.json) to make nyc (Istanbul's CLI) run Mocha for us: { ... "scripts": { ... "test": "nyc mocha --require babel-core/register" } ... } Running npm test now will make Istanbul analyze how our tests are covering our source code. Cool, integrating Istanbul on our project was easy. But can Istanbul do more than just saying that we are covering X percent of our code? Sure! Istanbul can show what lines are covered, what lines are not. To get this information, we are going to configure on Istanbul a reporter called lcov. This reporter will generate test data in two formats: one that is machine readable ( lcov format), and one that is human readable (HTML in this case). To configure lcov on Istanbul, we can simply add the following property to our package.json file: { ... "nyc": { "reporter": [ "lcov", "text" ] } } Note that we configured both lcovand textbecause we still want Istanbul to keep showing that nice summary that we saw before. Running npm test now will generate, besides that colorful summary on the terminal, a directory called coverage in the project root. If we inspect this directory, we will see that it contains two things: a lcov.info file with some characters inside that look meaningless (they actually show what lines were executed and how many times); and another directory called lcov-report with an index.html file inside. This is where we will get more data about what lines our tests are covering and what lines are being ignored. To see the report contained by the lcov-report directory in a browser, let's use a tool like http-server. In our project root, we can use it as follows: # install (globally) http-server if needed npm i -g http-server http-server ./coverage/lcov-report/ Now we can browse to and analyze what lines are being covered by our tests. "Integrating test coverage tools on NPM packages is easy." With Istanbul in place, let's commit and push it to GitHub: git add package*.json git commit -m 'test coverage with Istanbul' git push origin master Publishing the NPM Package After installing and checking our code coverage with Istanbul, we figure that we forgot to cover cases where no value ( null or undefined) are passed into our function. Let's fix this by adding new test samples in the ./test/index.js file: // ... imports stay untouched const testSamples = [ { input: null, expectedResult: null, description: 'should return null when null is passed' }, { input: undefined, expectedResult: null, description: 'should return null when undefined is passed' }, // ... the initial samples stay untouched ]; // ... describe method stays untouched If we ask Istanbul now ( npm test), we will see that we managed to add enough scenarios to cover all our source lines of code. This is not a proof that our package contains no bug, but enough to make us confident to publish its initial version. So let's do it. Publishing NPM packages looks like a very simple process. As described in the official documentation, all we need is to create a user (if we still don't have one) and then issue npm publish in the project root, right? Well, not so fast. Indeed, is not hard to publish a NPM package, but we always want to distribute an ES5 version of our package for maximum compatibility. We could leave this as a manual process (that is, expect the developer to run npm run build before publishing a new version), but this is too error-prone. What we want instead is to automatically tie the build script to publish. Luckily for us, when NPM is publishing a new version of a package, it checks the package.json file to see if there is a script called prepublishOnly. If NPM finds this script, it runs whatever command is inside it. Therefore, what we have to do is to configure prepublishOnly in our package.json file as follows: { ... "scripts": { ... "prepublishOnly": "npm run build" }, ... } Hurray! Looks like we are ready to publish our package. Let's run npm publish and make it available to the world. Note that, before publishing, we might need to create a NPM user and to login to our NPM CLI ( npm login). It's important to note that the nameproperty on package.jsonis the name that our package will get after we publish it. If someone else tries to publish a package with the same name as ours, they will get an error and will have to choose another name. (Hint: I left the masks-jsnamespace available on NPM to see who will be the first one to finish this tutorial) Let's commit and push changes to GitHub: git add package.json test/index.js git commit -m 'covering 100%' git push origin master Continuous Integration Well, well. We have published the first version of our NPM package. This is amazing. Looks like all we need to do to publish a new version is to write some code, cover it with tests, and issue npm publish. But, can we do better? Of course! We can use a continuous integration tool to automate the NPM publishing process. In this case, we will use Travis CI, one of the most popular and OSS-friendly (Open Source Software friendly) continuous integration tools around. This tool is totally integrated with GitHub and, as such, configuring it in our project is straightforward. First, we need to head to our profile on Travis CI and turn on the switch shown in the left of our project's name. Then, back into our project root, we need to create a file called .travis.yml with the following properties: language: node_js node_js: - node before_deploy: - npm run build Note that, from now on, we will count on Travis to generate builds for us. This means that we have to remove the prepublishOnlyscript from the package.jsonfile. The properties in the .travis.yml file will tell Travis that our repository contains a node_js project. Besides that, Travis will also use this file to identify which Node.js versions it should use to build our package. In our case, we tell Travis to use only the latest version ( node_js: node). We could also add other Node.js versions in there, but as we are using Babel to generate ES5 compatible JavaScript, this is not necessary. Having this file in place, we can install Travis CLI to help us with the last step. After installing it, let's open a file called .npmrc from our user's home directory ( ~/.npmrc) and copy the token from it (if needed, keep in mind that there are other ways to get a token). This file will probably have a content similar to: //registry.npmjs.org/:_authToken=1a14bf9b-7c33-303c-b2f8-38e15c31dfee In this case, we are interested in copying the 1a14bf9b-7c33-303c-b2f8-38e15c31dfee value. After that, we have to issue travis setup npm --org back on our project root. This will make NPM ask six questions. The following code snippet shows these questions and possible answers: Detected repository as brunokrebs/masks-js, is this correct? |yes| # use your own email address, of course NPM email address: bruno.krebs@auth0.com NPM api key: ************************************ release only tagged commits? |yes| Release only from brunokrebs/masks-js? |yes| Encrypt API key? |yes| We also have to prevent Travis CI from deleting the ./lib directory created during the build process, otherwise it wouldn't be uploaded to NPM when publishing. In the end, our .travis.yml file will look similar to this: language: node_js node_js: - node - '6' deploy: # add this line after travis setup skip_cleanup: true provider: npm email: bruno.krebs@auth0.com api_key: secure: PjDqlAfbsL5i8... on: tags: true repo: brunokrebs/masks-js That's it, we can now count on Travis CI to release new versions of our package. So, let's test this integration. Travis will also execute npm testwhenever we push a new commit to GitHub and it won't release new versions if our tests fail. To simulate a real-world scenario, let's make a small patch to our code. Let's make it support one more fictitious digit on US phones. To do that, we will update the ./src/index.js as follows: // lower than 10 or greater than 11 if (digitsOnly.test(phone) === false || phone.length < 10 || phone.length > 11) { return phone; } // returning the masked value const codeArea = phone.substring(0, 3); const prefix = phone.substring(3, 6); const sufix = phone.substring(6, phone.length); return `(${codeArea}) ${prefix}-${sufix}`; } export default maskUSPhone; And we will also add one more test sample to ./test/index.js to cover the new scenario: // .. imports const testSamples = [ // ... other scenarios { input: '54312609876', expectedResult: '(543) 126-09876', description: 'should return (543) 126-09876' }, ]; // ... describe and it Now we just need to commit the new code, use npm to bump our package version, and push these changes to GitHub. # add and commit new code git add package.json src/ test/ .travis.yml git commit -m 'supporting one more digit and adding Travis' # bump patch to 0.0.2 (this also generates a tag called v0.0.2) npm version patch # push code and tag to GitHub git push --follow-tags origin This will make Travis CI build our project and release its second version. we have covered a good amount of topics and tools that will help us develop NPM packages. We have talked about Semantic Versioning, configured EditorConfig, set up Babel to use ES6+ syntax, used Automated Tests, and so on. Setting up these tools, and being mindful while developing code, will make us better developers. With these tools to hold our back, we will even feel more confident to release new versions of our packages. So, now that we learned about these topics, it's time to get our hands dirty and contribute back to the OSS (Open Source Software) world. Have fun!
https://auth0.com/blog/developing-npm-packages/
CC-MAIN-2020-16
refinedweb
6,315
65.22
Creates. The command line to be executed. The maximum length of this string is 32,768 terminating null character to the command-line string to separate the file name from the arguments. This divides the original string into two strings for internal/2000: The ACLs in the default security descriptor for a process come from the primary or impersonation token of the creator. This behavior changed with Windows XP with SP2 and Windows Server 2003./2000: The ACLs in the default security descriptor for a thread come from the primary or impersonation token of the creator. This behavior changed with Windows XP with SP2 and Windows Server 2003. If this parameter TRUE, each inheritable handle in the calling process is inherited by the new process. If the parameter is FALSE, the handles are not inherited. Note that inherited handles have the same value and access rights as the original handles.. GetFullPathName("X:", ...)., /*...*/); For an example, see Creating Processes. Send comments about this topic to Microsoft Build date: 7/2/2009 /* The library I used is from Dev-C++ 4.9.9.2. I haven't try the VC's. The OS is Windows XP, SP2 */ The "Parameters lpApplicationName" section above says "To run a batch file, you must start the command interpreter; set lpApplicationName to cmd.exe and set lpCommandLine to the name of the batch file." But when I did so in a console program with: CreateProcess("C:\\Windows\\system32\\cmd.exe", "runBat.bat", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); or CreateProcess(NULL, "C:\\Windows\\system32\\cmd.exe runBat.bat", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);, the cmd.exe ignored the "runBat.bat" completely, i.e. the new cmd instance was booted smoothly while my "runBat.bat" wasn't executed. Furthermore, when I specified the cmd.exe without its complete path as: CreateProcess("cmd.exe", "runBat.bat", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);CreateProcess() return with FALSE, and GetLastError() return 2. At last I found the followings work: CreateProcess(NULL, "runBat.bat file1.txt file2.txt", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); and CreateProcess("runBat.bat ", "file1.txt file2.txt", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); However, when I wanted to redirect the stdin and stdout of a called program in runBat.bat to the file1.txt and file2.txt respectively, only the former could work as expected. The latter caused such situation: file1.txt was opened with notepad and the cmd window was blocked until I closed the notepad manually. Furthermore, file2.txt had not be written in at all. THERE SHOULD BE A WAY TO LAUNCH a process with the window as "ALWAYS ON TOP" USING THIS FUNCTION. This is not a robust enough function. Note: This is not an appropriate forum for editorializing. A process that is not designed to be TOPMOST should not be created as TOPMOST. An application that is designed to be TOPMOST should be capable of making itself TOPMOST. I found that the lpEnvironment is ignored on Windows Vista for some applications, but I haven't not been able to track down when this occurs. One reproducable example occurs when I name my exe "Photoshop.exe" lpEnvironment is ignored, and when the same EXE is renamed to "p3.exe" it is no longer ignored. I don't know if this is some special case for handling compatability with photoshop or this issue affects a larger population of apps? For these applications the environment variables are inherited from the parent process rather than using the values specified in lpEnvironment. I have not run into this problem with any older platforms. how can I fetch the value returned by the called exe? Answer: Use GetExitCodeProcess() after the process has exited (you can use the wait function to make sure it did). "The command line to be executed. The maximum length of this string is 32K characters. [...] The Unicode version of this function, CreateProcessW , can modify the contents of this string." In other words, I have to allocate a buffer of 32K characters if I want to provide CreateProcessW() with the lpCommandLine argument? Answer: No; read the part that says "maximum". Questions such as that do not belong here. Answer^2: You misunderstood my intention. I think this part of the documentation is unclear and wanted to facilitate clarification. If a function modifies a string argument and that string argument has a maximum length of 32K characters, for me that means I have to provide 32K of writable memory when I call the function or risk a theoretically possible buffer overflow. This could be clarified by stating "the function can modify the contents of this string, but will not enlarge the string (eg. add additional characters to its end)". STARTUPINFO startupInfo = {0};startupInfo.cb = sizeof(startupInfo);PROCESS_INFORMATION processInformation;// Try to start the processBOOL result = ::CreateProcess( L"C:\\Windows\\NOTEPAD.exe" NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation);if(result == 0) throw std::runtime_error("Could not create process"); Answer^2: Wrong. UNICODE is defined. Besides, passing a wchar_t string where a char string is expected results in a compiler error, so there's not chance CreateProcessA() was used. Upon that, CreateProcess() works fine if I use lpCommandLine to specify the executable (also as wide char string). Answer^3: I tried that code right now and it just works; besides I've used CreateProcess that way countless times. Sorry, both the documentation and the implementation are perfect; the problem must be yours. Check GetLastError's return value. #include <windows.h>#include <stdio.h>#include <tchar.h>#include <conio.h> void _tmain( int argc, TCHAR *argv[] ){STARTUPINFO si;PROCESS_INFORMATION pi;STARTUPINFO sj;PROCESS_INFORMATION pj; ZeroMemory( &si, sizeof(si) );si.cb = sizeof(si);ZeroMemory( &pi, sizeof(pi) ); ZeroMemory( &sj, sizeof(sj) );sj.cb = sizeof(sj);ZeroMemory( &pj, sizeof(pj) );// Start the child process p1.exe. Make sure p1.exe is in the// same folder as current application. Otherwise write the full path in first argument.if(!CreateProcess(L".\\p1.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &sj, &pj)){printf( "Hello CreateProcess failed (%d)\n", GetLastError() );getch();return;} // Start child process p2.exe. Make sure p2.exe is in the// same folder as current application. Otherwise write the full path in first argument.if(!CreateProcess(L".\\p2.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)){printf( "CreateProcess2 failed (%d)\n", GetLastError() );getch();return;} // Wait until child processes exit.WaitForSingleObject( pi.hProcess, INFINITE );WaitForSingleObject( pj.hProcess, INFINITE ); // Close process and thread handles.CloseHandle( pi.hProcess );CloseHandle( pi.hThread );CloseHandle( pj.hProcess );CloseHandle( pj.hThread );getch();} For example:["C:/Program Files/MyApplication/MyApp.exe" Arg1 Arg2 Arg3]^lpApplicationName AND lpCommandLineOr can they be different?Would I get a terminating null here:["C:/Program Files/MyApplication/MyApp.exe"]0x00[Arg1 Arg2 Arg3]Is the terminating null inserted in all cases, or only if the program name is repeated? <DllImport("kernel32", CharSet:=CharSet.Auto)> _ Public Shared Function CreateProcess(ByVal lpApplicationName As String, ByVal lpCommandLine As String, ByVal lpProcessAttributes As SECURITY_ATTRIBUTES, ByVal lpThreadAttributes As SECURITY_ATTRIBUTES, <MarshalAs(UnmanagedType.Bool)> ByVal bInheritHandles As Boolean, ByVal dwCreationFlags As Integer, ByVal lpEnvironment As IntPtr, ByVal lpCurrentDirectory As String, ByVal lpStartupInfo As STARTUPINFO, ByVal lpProcessInformation As PROCESS_INFORMATION) As Integer End Function [DllImport("kernel32", CharSet=CharSet.Auto)] internal static extern int CreateProcess(string lpApplicationName, string lpCommandLine, NativeTypes.SECURITY_ATTRIBUTES lpProcessAttributes, NativeTypes.SECURITY_ATTRIBUTES lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, NativeTypes.STARTUPINFO lpStartupInfo, NativeTypes.PROCESS_INFORMATION lpProcessInformation); Instaead of using the unmanaged CreateProcess API in your managed code, use the System.Diagnosics.Process class and the Start static method. For more info on this class, see and for more information on the Start method, see:
http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx
crawl-002
refinedweb
1,282
51.24
Socrata has a page dedicated to this topic. It's the basis for this example and the next example. There's a new term involved - filtered. In the Socrata web browser interface where you are using a data portal you can create a filter by specifying which rows to include based on their values, summing values in rows, and sorting rows. It's the way to do the operations to build or find the rows that meet your needs. There's a simple way to do a complex query. Socrata calls it piggybacking on an existing filtered view. Use your web browser, go to the portal, build your query, save it as a view, and in your code you specify the viewID for that query. The result: your code calls the stored filter. That filter is just another view. The advantage: it is quick and you already know how to write the code to request a view. There are a couple of disadvantages: 1) It's fixed. Your app can't modify the query. 2) Your code is in two places. Your query is stored at the portal and your app calls that query. You might be maintaining things in two places instead of one. Create your filter We'll use the Chkregist DEC2010 data set on the Cook County Data Portal. Here's a screenshot of it. You can find the viewID in the URL in the URL bar at the top of the web browser. It is e9qr-rmq4. Let's find the checks for construction services between $1m and $10m. This screenshot shows the filter parameters on the right. I'm asking for all rows that have a product description of 912 (this means construction services) and an amount between $1m and $10m. After creating it, I saved the filtered view as Construction over 1m. You can see the viewID Socrata assigned to my filtered view in the URL in the URL bar at the top of the web browser. It is 2wek-2jap. Now that the filtered view is in place you can access it from a program. Here's the code to get all the rows from the filtered view, load the JSON into an array, and print the array. This should look familiar. from urllib2 import urlopen from json import load import pprint url = '' u = urlopen(url) response = load(u) pp = pprint.PrettyPrinter(indent=4) pp.pprint(response) You get back the data in the rows along with the metadata for columns. I ran it by typing python example15a.py > out.txt and then looked at out.txt in a text editor. The value for 'data' is a list with two elements, one for each row in our filtered view. Each of those elements, in turn, has a list for the values of the columns in the row. As you'll see next, the first eight are metadata values. There are eight hidden columns each having metadata for a row. After the 'data' list, is 'meta' which contains metadata for the view. 'view' is a dictionary and one of its keys is 'columns' with a value of a list with elements for each column. Each of those list elements has the metadata for the column. We care about a couple of those metadata elements: 1) 'id' - if it is -1 then this is a metadata column; and 2) 'name' - the name of the column. Translation: we now know the names of each column in the view. We also know which of these columns are hidden from the web browser UI. Turns out the first eight columns are hidden. Program to get filtered view column names and data We can use our understanding of the API response to create a small program, example15b.py, to load up the JSON data for the filtered view and print out the column name along with its value for each row. Here's the code: from urllib2 import urlopen from json import load url = '' u = urlopen(url) response = load(u) rowNum = 1 for rowData in response['data']: print "\n===== Row %d ====" % (rowNum) colNum = 0 for columnMeta in response['meta']['view']['columns']: if columnMeta['id'] > 0: print columnMeta['name'], ' = ', rowData[colNum] colNum += 1 rowNum += 1 The outer loop iterates through the two rows returned in 'data'. For each of those rows, the inner loop iterates through each column's metadata. If a column has a negative value for 'id', then it's metadata and we won't print it. (Note, if you want to see the hidden metadata and its value for each column, just comment out that if statement.) Otherwise, print the name of the column along with it's corresponding value from the 'data' array. Here's the output. This program lays the groundwork for you to create a program that could explore the column names and, on the fly, give the user column names and values. You have both the column metadata and the row data. Program to get just the filtered data If the above is too much bother and you just want to get your hands on the data values. You can ask the API to send back just the data. Your code would then do things like hard code that the 11th element of the 'data'list is the Company Name. By specifying meta=false parameter on your API request, the views service will return just the data. Here's the code: from urllib2 import urlopen from json import load import pprint url = '' u = urlopen(url) response = load(u) pp = pprint.PrettyPrinter(indent=4) pp.pprint(response) Here's the output of just the data. Summary This is one approach to running a complex query. You can use the web browser UI to create your filtered view and save it. You can write a simple program to get back the data. You can write a more complicated program to plow through the metadata and data to respond to the user's needs. With a filtered view, you can't change the specifics of the query. If I wanted to find construction services over $10,000 or if I wanted to find consulting services over $1m, I'd have to create a new filter, get it's viewID, and put it in the code. The next example shows how to do a query without a filtered view. It gives you the ability to create a query or change the parameters of a query in your code. Hello Dear Friends, I guess your home is not just a place where you stay or spend your time. It is your style statement and reflects your preferences and tastes. So, if in case you are looking to hire a company for Home construction in Chicago or remodeling, then it is important to do enough research before hiring any company.
http://metrochicagoopendataexamples.blogspot.com/2011/08/example-15-complex-queries.html
CC-MAIN-2018-30
refinedweb
1,141
81.53
search by and display namespace Follow David Vollandt Created August 04, 2017 13:56 With the 'search every where' (ctrl+n) popup, how can I specify namespace? Is there an option to display namespace in the results? Hello, Namespaces are meaningly omitted from "Search everywhere" results. The reason is that usually there are too many declarations of a namespace, and displaying all of them would not be helpful. I'm curious, why would you want to go to a specific namespace? Thanks! Here's the specific example. I want to look at the implementation for map in brigand library. if i just type map, get results from brigand, boost and std are mixed in my results. If I type brigand::map I don't get any results. I would expect to see results for map in brigand name space. Incidentally, clion works as I would expect. map -> shows maps in all name spaces. brigand::map only shows those in brigand. I only have this issue in resharper. Which ReSharper version are you using? I can't reproduce this specific scenario. Does ReSharper not show any results at all for the "brigand::map" query in search everywhere?
https://resharper-support.jetbrains.com/hc/en-us/community/posts/115000478924-search-by-and-display-namespace-
CC-MAIN-2019-43
refinedweb
196
68.77
table of contents NAME¶ posix_openpt - open a pseudoterminal device SYNOPSIS¶ #include <stdlib.h> #include <fcntl.h> int posix_openpt(int flags); posix_openpt(): _XOPEN_SOURCE >= 600 DESCRIPTION¶ The posix_openpt() function opens an unused pseudoterminal master device, returning a file descriptor that can be used to refer to that device. The flags argument is a bit mask that ORs together zero or more of the following flags: RETURN VALUE¶ On success, posix_openpt() returns a file descriptor (a nonnegative integer) which is the lowest numbered unused file descriptor. On failure, -1 is returned, and errno is set to indicate the error. ERRORS¶ VERSIONS¶ Glibc support for posix_openpt() has been provided since version 2.2.1. ATTRIBUTES¶ For an explanation of the terms used in this section, see attributes(7). CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008. posix_openpt() is part of the UNIX 98 pseudoterminal support (see pts(4)). NOTES¶ Some older UNIX implementations that support System V (aka UNIX 98) pseudoterminals don't have this function, but it can be easily implemented by opening the pseudoterminal multiplexor. SEE ALSO¶ open(2), getpt(3), grant.
https://manpages.debian.org/testing/manpages-dev/posix_openpt.3.en.html
CC-MAIN-2022-05
refinedweb
180
56.15
Clark C . Evans [mailto:cce@...] wrote: >. Hmmm. This is a good point. I think that in general the rule should be that as far as he YAML models are concerned, aliases to scalars are allowed but may not be preserved. I'd modify (2) above to "use aliases for scalars if their representation is longer than 31 characters". This covers the !int and !flt cases, as well as !binary etc. Have fun, Oren Ben-Kiki This seems dreadfully wrong to me: > From: "Clark C . Evans" <cce@...> > Subject: [Yaml-core] alias usage > > I was thinking about the following rules for how our > built-in family objects deal with aliases: > >. To me, the point of alias/anchors is to preserve the structure of the object being dumped. They're not just a convenience for saving storage. They're addresses (what self-important languages call references). They contain the *structure* of the data, which is more than just the leaf values. If a YAML dump doesn't preserve this, then it's much less useful. Talk about the graph model, you'd never be able to dump a graph at all, if you left out leaf addresses. Yes? Andrew | To me, the point of alias/anchors is to preserve the | structure of the object being dumped. They're not | just a convenience for saving storage. They're | addresses (what self-important languages call | references).; which hurts readability in common business cases... person: - &1 given: Clark &2 family: Evans &3 gender: &4 M - *1: Oren *2: Ben-Kiki *3: *4 - *1: Brian *2: Ingerson *3: other Examples like this one become very unreadable when you add 10's of attributes (many of them flag like fields like gender) and more data... 100's of objects. So. I was thinking that a few of our core types may represent this "normalization" equivalency. However, this equivalency would be only propery of the !str, !int, !float types. It would _not_ be a property of objects in general. An alternative, is to allow for a more flexible comment usage: - *1 # given : Oren *2 # family : Ben-Kiki *3 # gender : *4 # M This isn't quite as readable, but it does preserve the structure. But still this doesn't solve problem #1; that is, depending on the language, small scalar values are not always distinct (esp. numerical types like !int and !float). | They contain the *structure* of the data, which is | more than just the leaf values. If a YAML dump doesn't | preserve this, then it's much less useful. Oh I agree here. I wasn't proposing a general case; but just a few basic behaviors to describe for the !str, !int, and !float cases. | Talk about the graph model, you'd never be able to | dump a graph at all, if you left out leaf addresses. --- &1 [*1] # ;) Does the above sound resonable. Perhaps this doesn't go in the spec; mabye it is just eratta for the Python binding. Although, it's quite clear to me that I cannot preserve the following: --- - &1 23 - *1 So, perhaps this should be considered more of a general limitation of the "core" data types? I only say this since most languages work like Python and since i'm not proposing a general case. Best, Clark > From: "Clark C . Evans" <cce@...> > Subject: Re: [Yaml-core] Re: alias usage > > | To me, the point of alias/anchors is to preserve the > | structure of the object being dumped. They're not > | just a convenience for saving storage. > >; [ . . .] Everything you say sounds just slightly weird to me: Suppose we're talking about the dump direction. For example: (1) I say "I'm going to give you an array" (2) "Here's the first element: It has type !int and value 3" or I say (2) "It has type and value AND anchor 1004" That is, it's up to me, as I push stuff out to tell the emitter whether to use an anchor or not. He doesn't have any descretion. He just does it. This is right, of course. If I'm dumping an interned language it will take some finesse on my part to know whether the thing I'm dumping *needs* an anchor or not. But, it's not up to YAML. Same sort of thing happens in the other direction: YAML tells me whether there's an anchor or alias. Then, my loader has to do something about it. So you see, I don't see that there's any problem. What have I missed? > > | Talk about the graph model, you'd never be able to > | dump a graph at all, if you left out leaf addresses. > > --- &1 [*1] # ;) > Oh, *that* graph. I don't think gentlemen should discuss *that* sort of graph, at least not in mixed company. > Perhaps this doesn't > go in the spec; I agree, not in the spec. But somewhere.. > mabye it is just eratta for the Python > binding. ?? 'Errata' means 'errors'. 'Errors in the Python binding'? > Although, it's quite clear to me that I > cannot preserve the following: > > --- > - &1 23 > - *1 > This seems like a show-stopper to me. If that's the structure the user wants to convey, who are we to say 'no'? Again, this sort of question needs to refer to the underlying purpose of YAML, (as laid out with crystal clarity in the phil doc). Once we know what YAML is *for*, then we know what it is required to do. So here I am again, feeling that I'm not quite on the same wave-length as you 3 caballeros. Enlightenment, SVP. Andrew On Fri, May 10, 2002 at 08:19:26PM -0700, Andrew Kurn wrote: |. Would you be willing to make a first cut? Perhaps even it could be added to the beginning of the spec right after the "tutorial" and before the "model"? I'm not quite certain how this could be done... so a boostrap document would be very helpful. | ?? 'Errata' means 'errors'. 'Errors in the Python | binding'? Yes, in that it can't properly round trip particular structures. They would be permanent errors though. | > Although, it's quite clear to me that I | > cannot preserve the following: | > | > --- | > - &1 23 | > - *1 | > | | This seems like a show-stopper to me. If that's the structure | the user wants to convey, who are we to say 'no'? See my last message, that is defining the behavioral interaction with aliases at the type family level, for example, a statement in the !int type family that the above need not be preserved by all bindings. In this way we arn't saying "no" to the user; as much as we are saying that the user can't depend upon this particular type family supporting that distinction. Of course if this distinction was important, the user could make up their own type family which did. yea? Or is this just wishful thinking? | Again, this sort of question needs to refer to the underlying | purpose of YAML, (as laid out with crystal clarity in the | phil doc). Once we know what YAML is *for*, then we | know what it is required to do.a Yes... I do agree, this could help out. How about this: - to make common place serialization easy and readable - to make uncommon serialization possible. ;) Clark And On the topic of 'identity' of YAML nodes: As so often before, much of what you say sounds a little weird to me . . . Oren: > The question is, what is YAML's position on this. Are YAML nodes > identity-based (read: require aliases structure to be preserved), value > based (read: allow aliases structure to change), or what? It seems obvious to me that it's not up to YAML. If identity is allowed at all, it must be possible to make anything identical. It's the user's discretion. I think what you *must* be thinking of is the *automatic* dumper. You hand it an object and say 'Dump this' and it must figure out what to do on its own. To me, this seems obviously unreasonable in the case where the object *might* contain pointers for the purpose of creating identity. (Or, they *might* be there just to save storage for some string like "Value unknown".) I think you have to let the user decide how to treat pointers. It's true that you might offer him some policies that you think are likely to be useful most of the time, but you must allow him to choose anything at all in some cases.. ---------------------------------------------- How about this? Let's say that anything composed of purely basic data types *never* has pointers for creating identity. That's only found in user types. Then there is NO REASON to use the !ptr data type. The appearance of an alias implies the pointer. It does not appear explicitly in the dump. Also, the user knows where to expect pointers, since they're part of his user-type. If the automatic dumper runs across a pointer in a purely native structure, it simply dereferences it and forgets it ever saw it. How's that for a solution? (If the dumper encounters a circular chain of references, it simply dies. This is time-honored behavior. I have seen it in Lisp, Prolog, and one or two others.) ----------- Oren: > - We want to be able to write long scalars - specifically, strings (and > binary data) - only once in a YAML file. I don't think this is important enough to justify keeping aliases if my argument above persuades you. Thus, my vote is for Oren's #1: > 1. We just "keep it simple": > - Say that an alias means sharing, pure and simple; > - And give up on emitters being able to insert aliases for "equal scalars" > unless they are also "shared" in the graph model. > - This is elegant to specify and implement. > with the added understanding that aliases only appear inside user types. ------------- Brian: > YAML.pm currently does not preserve the relationship of scalars in the native > model, when dumping it. It does honor aliases between scalars when loading > them. This is the most useful, in the general case, IMVHO. (BTW, you *can > preserve the relationship using hard references which YAML.pm dumps as !ptr) > > However, soon I will offer the nondefault option to dump all scalars > with the same pointer value, as aliases of the first. That is, if an object contains 2 hard references to the same scalar, you will notice this and dump them as aliases. (presumably using a hash to hold all the pointers you've ever seen, so that you can find it) > > This seems like a great compromise. From Y->N we must honor the aliases. From > N->Y we should be *able* to preserve the relationships. But making it the > default is the wrong choice from where I stand. ^^^^^^^^^^^^ Why? This decision is important. What are the reasons? Anyhow, As I say above, I think it's necessary to give the user a finer choice than the proposals (Never sharing. Sharing on all except leaves. Always sharing.) Not that the proposals aren't good 99% of the time (if the user can choose between them), but *sometime* he'll need to make finer-grained choices. Andrew | I think what you *must* be thinking of is the *automatic* | dumper. You hand it an object and say 'Dump this' and | it must figure out what to do on its own. This is the common use case; preserve the in-memory structure via a native->yaml->native round-trip. | I think you have to let the user decide how to treat | pointers. It's true that you might offer him some | policies that you think are likely to be useful most | of the time, but you must allow him to choose anything | at all in some cases. Python doesn't have pointers; it only has references. Perl has both, but pointers are rarely used and need only be preserved (thus the !ptr construct). "C" only has pointers. References are implemented with pointers, but this is done via specific conventions and/or intermediate code which implements pointer integrety, etc. This pointer/reference distinction is necessary since most of the languages we work with it make the distinction. References differ from pointers in that a reference is symmetric. Once you have a refernece to an object you have no more / no less rights than any other process which has a reference. This symmetry isn't true with pointers in general, pointers can be invalid; references by definition are never invalid. |. Yes; ideally the schema language (when it gets developed) will help keep all of this stuff clear. And yes, we don't want YAML itself to make the decision, although it should, IMHO still provide a reference mechanism. So, I was proposing a limitation on a few distinct scalar types (!int, !str, !float) and their behavior. There is nothing then stopping a user from defining an equivalent type with different behavior if the default behavior here isn't acceptable. | How about this? Let's say that anything composed | of purely basic data types *never* has pointers | for creating identity. That's only found in | user types. I didn't grok this. | Then there is NO REASON to use the !ptr data type. | The appearance of an alias implies the pointer. | It does not appear explicitly in the dump. Yes; but an alias(reference) is very different from a pointer. The following are equivalent... --- one: &001 value two: *001 --- two: &001 value one: *001 Which key "value" was provided via an anchor and which key is the alias is *not* informational. The distinction between the two structures above are identical in the generic model since alias position and key order need not be preserved (i.e. a process cannot count on these two items being preserved). However, by constrast, the following are different... --- one: &001 value two: !ptr =: *001 --- two: &001 value one: !ptr =: *001 Since in the first example, "two" is a pointer to "value", while "one" is "value". In this way you can think of everything as using reference semantics; and for YAML purposes a "shared" pointer is implemented through the reference mechanism. Of course, the first one above, is equivalent to... --- two: !ptr =: &001 value one: *001 | Also, the user knows where to expect pointers, | since they're part of his user-type. In Python you don't have pointers, one only has references. In Perl, the runtime knows where the pointers ("hard references") are, beacuse it has a different syntax and stores them differently. Java is like Python, no references. "C" and a few other languages have pointers, and in this case the user would have to write their own dumper/loader pair. | If the automatic dumper runs across a pointer in a | purely native structure, it simply | dereferences it and forgets it ever saw it. | | How's that for a solution? In Perl, this solution would prevent hard references (aka pointers) from being preserved; and thus I think it is a horrible idea. A "C" language, the loader/dumper is custom anyway, so it is up to the programmer. As for C++, I doubt that the C++ reflection is strong enough to do a proper "generic" save program. Thus, this is also up to the programmer. | (If the dumper encounters a circular chain of references, | it simply dies. This is time-honored behavior. I have | seen it in Lisp, Prolog, and one or two others.) This might be a good solution for C/C++ custom YAML loader/dumper. In general, cycles occur in data, I have cycles in many of my python structures and automatically saving them is what YAML is all about. Collections have pointers to their objects, and quite often objects refer back to their collections. | > - We want to be able to write long scalars - specifically, strings (and | > binary data) - only once in a YAML file. | | I don't think this is important enough to justify keeping | aliases if my argument above persuades you. XML's lack of graph support causes it no end of grief. Each application does it their own way, and thus making generic tools that operate at the graph level are impossible. The requirement of dealing with graphs is part of YAML's core and it is one of those assumptions that is not subject to review. | As I say above, I think it's necessary to give the user a finer | choice than the proposals (Never sharing. Sharing on all except | leaves. Always sharing.) My suggestion (and I'm still thinking about it...) isn't as broad a brush. It breaks down into two categories: (a) Atomic objects, such as int and float, are often stored using a value and not using an "object" with an identity. As such, in the graph model we specify that aliases applied directly to such atomic objects may be dropped. In the YAML specification we name only two such families which have atomic behavior -- !int and !float. (b) String objects, which are often treated as an "immutable" object and frequently not compared by address. For this case we specify that strings may be treated as atomic objects, and this may gain/loose aliases in the generic model. Thus, according to the generic model, the two documents below will be considered identical, since aliases are not significant: --- - 23 - &001 23 - *001 - Hello - &002 Hello - *002 --- - &001 23 - *001 - 23 - &002 Hello - *002 - Hello The advantages of this proposal a) Part a supports native int, float types in most languages without requiring that address (a group of objects sharing the same alias) need be maintained. Otherwise, to meet the requirement of the graph model; all !int and !float types with anchors would have to be wrapped. b) Supports readability by specifying that strings can be treated as atomic values. In most languages, the specific address of a string is rarely used. Thus, this is a good 95% compromise. We loose the string's identity, but gain greater readability. For python, the rules of identity for atomic objects are more or less random. Two integer objects of less than 999 will _always_ share the same memory address, but integer objects greater than 999 may be different depending on the parser state; it may not even be deterministic. Strings are somewhat similar, most of the time identity is preserved, although there may be cases where identity isn't preserved. | Not that the proposals aren't good 99% of the time (if the | user can choose between them), but *sometime* he'll need | to make finer-grained choices. This is what we are trying to do; the above "restrictions" on the base !float, !int, and !str type are probably what we want 99% of the time. And in the cases where you don't want this property... you can make your own custom types. --- Anyway. The alternative is to be "strict" by default, and allow a "dumper" option to "de-normalize" the graph by duplicating alias values, and allowing a "loader" to "normalize" strings by interning strings. This would give the greatest readability; but would not be the default. I suppose we could keep "strict" as the default option, but let the loader/dumper use a relaxed model as a non-default option... perhaps this is the principle of least suprises? Best, Clark Thoughts on references and pointers. I think this just comes down to "implicit" vs "explicit". In the implicit case the programming system manages the pointers, in the explicit case, it is the programmer which has to do a "dereference". In YAML we must preserve both cases. For example, Perl has "three" types of references. The first type, soft references, seems to be the default, is implicit, and works exactly like Python's reference mechanism. With soft references, multiple links to an object can be made without the programmer worrying about the details or using any special operator. It is all done "automagically". Note that implicit isn't strictly true for Perl since the programmer must use $, @, %, or other type sigals. But these sigals are explained more as types and uses everywhere, so a novice user can be completely oblivious to the de-referencing aspect of these operators. I view view $x as similar in style to something like *((scalar_t*)x) and @x like *((array_t *)x) Since it is the "normal" way of doing things, let's call the perl soft references, "implicit". Perl also has hard references where you need an need to use an "address" operator (\) to get a pointer. You then use one of the sigals to dereference the address that is returned. This is the "explict" form since the user must remember that a given variable is a refernece to de-reference it. In my mind, $$x is somewhat like **((scalar_t **)x). Python does not have an explicit reference mechanism. Perls' third mechanism, "symbolic references" is just cute way to access members of the current namespace, which is an implicit hashtable. "C" on the other hand, uses an explict mechanism (&*) and lacks an implicit reference handling technique. While, for contrast, C++ seems to have a bit of both if you use classes with counted pointer wrappers. Also, I like to think of C++'s pass-by-reference function call type as more or less "implicit". Unfortunately, this distinction is very fuzzy. However, for YAML, the alias/anchor "reference" system is meant to model an native implicit reference system. The !ptr type family is meant to handle an underlying explicit system. Thus, a Perl serialization may use both alias/anchor and !ptr. If it were possible to have "reflection" for "C", then it would use primarly !ptr, with an alias as the value of the pointer for the first occurrance; luckly "C" doesn't have reflection so we don't have to worry about this and can leave it up to the application to decide. As for Python, it will only use the alias/anchor representation, but will use a list with one item to emulate !ptr constructs. From YAML's perspective, evertyhing is a link to another node, the first link in the serialization is labeled so that other links to the node can re-use the node's description. Since we must preserve the "explicit" hard references of Perl, we use the !ptr mechanism as well. The !ptr is a single-position container (emulated as a map with a single = key) which simply holds a node or an alias. In this way, the level of indirection which the user requires (to preserve the explicit nature) can be serialized and thus not break code since a perl person needs to distinguish between $x and $$x. Ok. I hope this helps to explain better. Some of this is new to me. The implicit vs explicit is a new insight for me and may not quite explain the situation well; but it is better than my previous understanding. Thank you Andrew for prodding me to come up with a better explanation... does this help? Clark
http://sourceforge.net/mailarchive/forum.php?thread_name=20020517140408.B32271%40doublegemini.com&forum_name=yaml-core
CC-MAIN-2013-48
refinedweb
3,844
73.47
Is COM interop Fundamentally Flawed? Of course, .NET COM interop has this fascinating simple story. We'll give you these wonderfull wrapper objects, that will give COM the illusion that they are interacting with other COM objects and give .NET objects the illusion that they're interacting with other .NET objects. The story is that you supply your COM Type Libraryto tlbimp.exe and it spits out this wonderfull Runtime Callable Wrapper (RCW). The counterpart on the otherside is COM-callable wrapper. Its a good story in theory. The wrappers handle all the transitions between managed and unmanaged code and all the issues between the world of COM and the world of .NET like data marshalling, exception handling, object lifetime. The issue is that to play in the .NET world, the RCW's lifetime is controlled by the CLR's garbage collector. Each RCW caches its interface pointers for the COM object that it wraps, and internally performs reference counting on these interface pointers. When an RCW is collected, it's finalizer calls IUnknown.Release on all its cached interface pointers. Thus, a COM object is guaranteed to be alive as long as its RCW is alive. Herein lies the problem for non-trivial COM components and large interacting COM components in a large COM infrastructure. The release calls are non-determinstic in the sense that they will happen when the GC gets around to killing off the RCW. Most particuarly,this plays havoc witth COM architectures that reley on Callbacks happening between COM components with their own sense of when they want to be released. The wrapped COM object doesn't get released until the RCW is collected. Oh sure, Interop has a way for you to "insist", again in theory. You can call the Marshal::ReleaseComObject method in the System::Runtime::InteropServices namespace. And you can call raw release calls that are provided. The point is that in a non-trivial COM architecture with callabacks and such, this becomes a mess and is quite problematic. In my work in this area for a certain company, we have had over a month's worth of problems with crashes and leaks and having to do countless "Tweaks" to call ReleaseComObject and raw releases. It comes down to this: It shouldn't be this dran hard! The COM Interop layer should be handling all of this INSIDEits wrapper in a determinstic way. I'm beginning to wonder if its design is flawed. Peter picks up on the discussion: Sam Gentile: "Is .NET COM Interop fundamentally flawed?" Not sure I agree that it's fundamentally flawed, but it's definitely substantially more complex than the commonly cited "just use TlbImp.exe" story. After all, how simple can it be if there's a 900 page book on the topic? Sam's been doing a lot more COM Interop work than I have, so I'm inclined to listen to him in this regard. [Peter Drayton's Radio Weblog] Ahh, but it's not a 900 page book, it's a 1608 page book-))) But that really isn't the main point I am trying to make. Certainly, one of the points to be made is that it is "definitely substantially more complex than the commonly cited "just use TlbImp.exe" story." I think we can all agree on that, right? But that is not the main point I am making. The main point is that the world of COM is determinstic, right? Interface pointers must be released at the right times or you will get memory leaks (at the least) and crashes (at the worst and more likely). My main point is all of this cruft should have been totally hidden by the tlbimp.exe/RCW/CCW mechanism and it isn't. We have had 3 very smart engineers (COM experts) on these problems for 2 months and we are facing things that Microsoft even has no idea on (i.e. things that are not even in that 1608 page book!. This leads me to think that COM Interop was designed for the "textbook" COM case and if you are doing anything else or non-trivial, you will have big, big problems. Microsoft says "You should never need to explicitly release anything unless keeping it alive would cause some sort of issue. Eventually the GC will collect the RCW and the underlying COM object will be released at that point." Wrong, oh so wrong. Major COM architectures don't work that way. There are custom marshalling schemes. There are callbacks and connection points. And on and on. By forcing us to do tons of Marshal.ReleaseComObject calls and UCOM calls, it goes away from what we think the Interop should be an do. I (and we) subscribe to this view that the RCW should do all of this. By making it act non-determinstically, it doesn't play well with others (in the COM world).
http://radio.weblogs.com/0105852/stories/2002/06/08/isComInteropFundamentallyFlawed.html
crawl-002
refinedweb
823
73.98
Processing Atom 1.0 September 14, 2005 In the fast-moving world of weblogs and Web-based marketing, the approval of the Atom Format 1.0 by the Internet Engineering Task Force (IETF) as a Proposed Standard is a significant and lasting development. Atom is a very carefully designed format for syndicating the contents of weblogs as they are updated, the usual territory of RSS, but its possible uses are far more general, as illustrated in the description on the home page:. Atom is a very important development in the XML and Web world. Atom technology is already deployed in many areas (though not all up-to-date with Atom 1.0), and parsing and processing Atom is quickly becoming an important task for web developers. In this article, I will show several approaches to reading Atom 1.0 in Python. All the code is designed to work with Python 2.3, or more recent, and is tested with Python 2.4.1. The example I'll be using of an Atom document is a modified version of the introduction to Atom on the home page, reproduced here in listing 1. Listing 1 (atomexample.xml). Atom Format 1.0 Example <?xml version="1.0" encoding="utf-8"?> <feed xml: <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <title>Example Feed</title> <updated>2005-09-02T18:30:02Z</updated> <link href=""/> <author> <name>John Doe</name> </author> <entry> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <title>Atom-Powered Robots Run Amok</title> <link href=""/> <updated>2005-09-02T18:30:02Z</updated> <summary>Some text.</summary> </entry> <entry> <id>urn:uuid:8eb00d01-d632-40d4-8861-f2ed613f2c30</id> <title type="xhtml"> <xh:div> The quick <xh:del>black</xh:del><xh:ins>brown</xh:ins> fox... </xh:div> </title> <link href=""/> <updated>2005-09-01T12:15:00Z</updated> <summary>jumps over the lazy dog</summary> </entry> </feed> Using MiniDOM If you want to process Atom with no additional dependencies besides Python, you can do so using MiniDOM. MiniDOM isn't the most efficient way to parse XML, but Atom files tend to be small, and rarely get to the megabyte range that bogs down MiniDOM. If by some chance you are dealing with very large Atom files, you can use PullDOM, which works well with Atom because of the way the format can be processed in bite-sized chunks. MiniDOM isn't the most convenient API available, either, but it is the most convenient approach in the Python standard library. Listing 2 is MiniDOM code to produce an outline of an atom feed, containing much of the information you would use if you were syndicating the feed. Listing 2. MiniDOM Code to Print a Text Outline of an Atom Feed from xml.dom import minidom from xml.dom import EMPTY_NAMESPACE ATOM_NS = '' doc = minidom.parse('atomexample.xml') #Ensure that all text nodes can be simply retrieved doc.normalize() def get_text_from_construct(element): ''' Return the content of an Atom element declared with the atomTextConstruct pattern. Handle both plain text and XHTML forms. Return a UTF-8 encoded string. ''' if element.getAttributeNS(EMPTY_NAMESPACE, u'type') == u'xhtml': #Grab the XML serialization of each child childtext = [ c.toxml('utf-8') for c in element.childNodes ] #And stitch it together content = ''.join(childtext).strip() return content else: return element.firstChild.data.encode('utf-8') #process overall feed: #First title element in doc order is the feed title feedtitle = doc.getElementsByTagNameNS(ATOM_NS, u'title')[0] #Field titles are atom text constructs: no markup #So just print the text node content print 'Feed title:', get_text_from_construct(feedtitle) feedlink = doc.getElementsByTagNameNS(ATOM_NS, u'link')[0] print 'Feed link:', feedlink.getAttributeNS(EMPTY_NAMESPACE, u'href') print print 'Entries:' for entry in doc.getElementsByTagNameNS(ATOM_NS, u'entry'): #First title element in doc order within the entry is the title entrytitle = entry.getElementsByTagNameNS(ATOM_NS, u'title')[0] entrylink = entry.getElementsByTagNameNS(ATOM_NS, u'link')[0] etitletext = get_text_from_construct(entrytitle) elinktext = entrylink.getAttributeNS(EMPTY_NAMESPACE, u'href') print etitletext, '(', elinktext, ')' The code to access XML is typical of DOM and, as such, it's rather clumsy when compared to much Python code. The normalization step near the beginning of the listing helps eliminate even more complexity when dealing with text content. Many Atom elements are defined using the atomTextConstruct pattern, which can be plain text, with no embedded markup. (HTML is allowed, if escaped, and if you flag this case in the type attribute.) Such elements can also contain well-formed XHTML fragments wrapped in a div. The get_text_from_construct function handles both cases transparently, and so it is generally a utility routine for extracting content from compliant Atom elements. In this listing, I use it to access the contents of the title element, which is in XHTML form in one of the entries in listing 1. Try running listing 2 and you should get the following output. $ python listing2.py Feed title: Example Feed Feed link: Entries: Atom-Powered Robots Run Amok ( ) <xh:div> The quick <xh:del>black</xh:del><xh:ins>brown</xh:ins> fox... </xh:div> ( ) Handling Dates Handling Atom dates in Python is a topic that deserves closer attention. Atom dates are specified in the atomDateConstruct pattern, of which the specification. The examples given are: 2003-12-13T18:30:02Z 2003-12-13T18:30:02.25Z 2003-12-13T18:30:02+01:00 2003-12-13T18:30:02.25+01:00 You may be surprised to find that Python is rather limited in the built-in means it provides for parsing such dates. There are good reasons for this: many aspects of date parsing are very hard and can depend a lot on application-specific needs. Python 2.3 introduced the handy datetime data type, which is the recommended way to store and exchange dates, but you have to do the parsing into date-time yourself, and handle the complex task of time-zone processing, as well. Or you have to use a third-party routine that does this for you. I recommend that you complement Python's built-in facilities with Gustavo Niemeyer's DateUtil. (Unfortunately that link uses HTTPS with an expired certificate, so you may have to click through a bunch of warnings, but it's worth it.) In my case I downloaded the 1.0 tar.bz2 and installed using python setup.py install. Using DateUtil, the following snippet is a function that returns a date read from an atom element: from dateutil.parser import parse feedupdated = doc.getElementsByTagNameNS(ATOM_NS, u'updated')[0] dt = parse(feedupdated.firstChild.data) And as an example of how you can work with this date-time object, you can use the following code to report how long ago an Atom feed was updated: from datetime import datetime from dateutil.tz import tzlocal #howlongago is a timedelta object from present time to target time howlongago = dt - datetime.now(tzlocal()) print "Time since feed was updated:", abs(howlongago) Using Amara Bindery Because the DOM code above is so clumsy, I shall present similar code using a friendlier Python library, Amara Bindery, which I covered in an earlier article, Introducing the Amara XML Toolkit. Listing 3 does the same thing as listing 2. Listing 3. Amara Bindery Code to Print a Text Outline of an Atom Feed from amara import binderytools doc = binderytools.bind_file('atomexample.xml') def get_text_from_construct(element): ''' Return the content of an Atom element declared with the atomTextConstruct pattern. Handle both plain text and XHTML forms. Return a UTF-8 encoded string. ''' if hasattr(element, 'type') and element.type == u'xhtml': #Grab the XML serialization of each child childtext = [ (not isinstance(c, unicode) and c.xml(encoding=u'utf-8') or c) for c in element.xml_children ] #And stitch it together content = u''.join(childtext).strip().encode('utf-8') return content else: return unicode(element).encode('utf-8') print 'Feed title:', get_text_from_construct(doc.feed.title) print 'Feed link:', doc.feed.link print print 'Entries:' for entry in doc.feed.entry: etitletext = get_text_from_construct(entry.title) print etitletext, '(', entry.link.href, ')' Using Feedparser (Atom Processing for the Desperate Hacker) A third approach to reading Atom is to let someone else handle the parsing and just deal with the resulting data structure. This might be especially convenient if you have to deal with broken feeds (and fixing the broken feeds is not an option). It does usually rob you of some flexibility of interpretation of the data, although a really good library would be flexible enough for most users. Probably the best option is Mark Pilgrim's Universal Feed Parser, which parses almost every flavor of RSS and Atom. In my case, I downloaded the 3.3 zip package and installed using python setup.py install. Listing 4 is code similar in function to that of listings 2 and 3. Listing 4. Universal Feed Parser Code to Print a Text Outline of an Atom Feed import feedparser #A hack until Feed parser supports Atom 1.0 out of the box #(Feedparser 3.3 does not) from feedparser import _FeedParserMixin _FeedParserMixin.namespaces[""] = "" feed_data = feedparser.parse('atomexample.xml') channel, entries = feed_data.feed, feed_data.entries print 'Feed title:', channel['title'] print 'Feed link:', channel['link'] print print 'Entries:' for entry in entries: print entry['title'], '(', entry['link'], ')' Overall the code is shorter because we no longer have to worry about the different forms of Atom text construct. The library takes care of that for us. Of course I'm pretty leery of how it does so, especially the fact that it strips Namespaces in XHTML content. This is an example of the flexibility you lose when using a generic parser, especially one designed to be as liberal as Universal Feed Parser. That's a trade-off from the obvious gain in simplicity. Notice the hack near the top of listing 4. These two lines should be temporary, and no longer needed, once Mark Pilgrim updates his package to support Atom 1.0. Wrapping up, on a Grand Scale Atom 1.0 is pretty easy to parse and process. I may have serious trouble with some of the design decisions for the format, but I do applaud its overall cleanliness. I've presented several approaches to processing Atom in this article. If I needed to reliably process feeds retrieved from arbitrary locations on the Web, I would definitely go for Universal Feed Parser. Mark Pilgrim has dunked himself into the rancid mess of broken Web feeds so you don't have to. In a project where I controlled the environment, and I could fix broken feeds, I would parse them myself, for the greater flexibility. One trick I've used in the past is to use Universal Feed Parser as a proxy tool to convert arbitrary feeds to a single, valid format (RSS 1.0 in my past experience), so that I could use XML (or in that case RDF) tools to parse the feeds directly. And with this month's exploration, the Python-XML column has come to an end. After discussions with my editor, I'll replace this column with one with a broader focus. It will cover the intersection of Agile Languages and Web 2.0 technologies. The primary language focus will still be Python, but there will sometimes be coverage of other languages such as Ruby and ECMAScript. I think many of the topics will continue to be of interest to readers of the present column. I look forward to continuing my relationship with the XML.com audience. This brings me to the last hurrah of the monthly round up of Python-XML community news. Firstly, given the topic of this article, I wanted to mention Sylvain Hellegouarch's atomixlib, a module providing a simple API for generation of Atom 1.0, based on Amara Bindery. See his announcement. And relevant to recent articles in this column, Andrew Kuchling wrote up a Python Unicode HOWTO. Julien Anguenot writes in XML Schema Support on Zope3: I added a demo package to illustrate the zope3/xml schema integration. [Download the code here] The goal of the demo is to get a new content object registered within Zope3, with an "add "and "edit" form driven by an XML Schema definition. The article goes on to show a bunch of Python and XML code to work a sample W3C XML schema file into a Zope component. Mark Nottingham announced sparta.py 0.8, a simple API for RDF. Sparta is databinding from RDF to Python objects. See the announcement. Guido Wesdorp announced Templess 0.1. Templess is an XML templating library for Python, which is very compact and simple, fast, and has a strict separation.
http://www.xml.com/pub/a/2005/09/14/processing-atom-in-python.html
CC-MAIN-2017-17
refinedweb
2,102
57.06
35360/write-native-windows-blackberry-android-apple-devices-python Hi all, So basically my requirement is covered in the question header. I just wanted to know if it is actually possible and plausible to develop applications for iOS and Android devices? I have started mobile app development and I was very keen to know more about how I can achieve this using Python. Appreciate all the help I can get, cheers! Hi, This is an amazing Python framework just for this purpose: Kivy I have personally developed using Kivy and I love it. It spans across multiple platforms ranging from Mac, Android, Linux etc. Note: Native iOS development is possible but it is quite cumbersome to do so because Apple doesn't allow native scripting using anything apart from their language. And, I think you will be aware of the Android Scripting Environment (ASE), right? Well, even if you don't - It is basically a tool to allow scripts to run on the Android environment. For iOS Python development, all you have to do is you need to embed a Python interpreter into the application and later distribute the script with it. Well, we do that last part so we can follow the rules/guidelines set by Apple. Hope this helps, let me know if you need anything else. Cheers! Every occurence of "foreach" I've seen (PHP, ...READ MORE can you give a few sample projects ...READ MORE Slicing is basically extracting particular set of ...READ MORE YES! An example via Matt Cutts via SL4A -- "here’s .. Hi. Nice question. Here is the simplified answer ...READ MORE class NegativeWeightFinder: def __init__(self, graph: nx.Graph): ...READ MORE OR
https://www.edureka.co/community/35360/write-native-windows-blackberry-android-apple-devices-python
CC-MAIN-2019-22
refinedweb
279
66.54
Listen to this article Back usual causes didn’t apply: CPU usage was normal, packet rates were entirely fine, memory usage was green as a summer field, request rates were low, and socket usage was well within the acceptable range. In fact, when we compared the EU nodes to their US counterparts, all metrics were at a nicer level than the US ones, except for latency. How to explain this? One of our engineers noticed that connections from the routing layer to dynos were getting the POSIX error code EADDRINUSE, which is odd. For a server socket created with listen(), EADDRINUSE indicates that the port specified is already in use. But we weren’t talking about a server socket; this was the routing layer acting as a client, connecting to dynos to forward an HTTP request to them. Why would we be seeing EADDRINUSE? TCP/IP Connections Before we get to the answer, we need a little bit of review about how TCP works. Let’s say we have a program that wants to connect to some remote host and port over TCP. It will tell the kernel to open the connection, and the kernel will choose a source port to connect from. That’s because every IP connection is uniquely specified by a set of 4 pieces of data: ( <SOURCE-IP> : <SOURCE-PORT> , <DESTINATION-IP> : <DESTINATION-PORT> ) No two connections can share this same set of 4 items (called the “4-tuple”). This means that any given host ( <SOURCE-IP>) can only connect to any given destination ( <DESTINATION-IP>: <DESTINATION-PORT>) at most 65536 times concurrently, which is the total number of possible values for <SOURCE-PORT>. Importantly, it’s okay for two connections to use the same source port, provided that they are connecting to a different destination IP and/or port. Usually a program will ask Linux (or any other OS) to automatically choose an available source port to satisfy the rules. If no port is available (because 65536 connections to the given destination ( <DESTINATION-IP>: <DESTINATION-PORT>) are already open), then the OS will respond with EADDRINUSE. This is a little complicated by a feature of TCP called “TIME_WAIT”. When a given connection is closed, the TCP specification declares that both ends should wait a certain amount of time before opening a new connection with the same 4-tuple. This is to avoid the possibility that delayed packets from the first connection might be misconstrued as belonging to the second connection. Generally this TIME_WAIT waiting period lasts for only a minute or two. In practice, this means that even if 65536 connections are not currently open to a given destination IP and port, if enough recent connections were open, there still may not be a source port available for use in a new connection. In practice even fewer concurrent connections may be possible since Linux tries to select source ports randomly until it finds an available one, and with enough source ports used up, it may not find a free one before it gives up. Port exhaustion in Heroku’s routing layer So why would we see EADDRINUSE in connections from the routing layer to dynos? According to our understanding, such an error should not happen. It would indicate that 65536 connections from a specific routing node were being made to a specific dyno. This should mean that the theoretical limit on concurrent connections should be far more than a single dyno could ever hope to handle. We could easily see from our application traffic graphs that no dyno was coming close to this theoretical limit. So we were left with a concerning mystery: how was it possible that we were seeing EADDRINUSE errors? We wanted to prevent the incident from ever happening again, and so we continued to dig - taking a dive into the internals of our systems. Our routing layer is written in Erlang, and the most likely candidate was its virtual machine’s TCP calls. Digging through the VM’s network layer we got down to the sock_connect call which is mostly a portable wrapper around the linux connect() syscall. Seeing this, it seemed that nothing in there was out of place to cause the issue. We’d have to go deeper, in the OS itself. After digging and reading many documents, one of us noticed this bit in the now well-known blog post Bind before connect: Bind is usually called for listening sockets so the kernel needs to make sure that the source address is not shared with anyone else. It's a problem. When using this techique [sic] in this form it's impossible to establish more than 64k (ephemeral port range) outgoing connections in total. After that the attempt to call bind() will fail with an EADDRINUSE error - all the source ports will be busy. [...] When we call bind() the kernel knows only the source address we're asking for. We'll inform the kernel of a destination address only when we call connect() later. This passage seems to be describing a special case where a client wants to make an outgoing connection with a specific source IP address. We weren’t doing that in our Erlang code, so this still didn’t seem to fit our situation well. But the symptoms matched so well that we decided to check for sure whether the Erlang VM was doing a bind() call without our knowledge. We used strace to determine the actual system call sequence being performed. Here’s a snippet of strace output for a connection to 10.11.12.13:80: socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 *bind*(3, {sa_family=AF_INET, sin_port=htons(0), sin_addr=inet_addr("0.0.0.0")}, 16) = 0 connect(3, {sa_family=AF_INET, sin_port=htons(80), sin_addr=inet_addr("10.11.12.13")}, 16) = 0 To our surprise, bind() was being called! The socket was being bound to a <SOURCE-IP>: <SOURCE-PORT> of 0.0.0.0:0. Why? This instructs the kernel to bind the socket to any IP and any port. This seemed a bit useless to us, as the kernel would already select an appropriate <SOURCE-IP> when connect() was called, based on the destination IP address and the routing table. This bind() call seemed like a no-op. But critically, this call required the kernel to select the <SOURCE-IP> right then and there, without having any knowledge of the other 3 parts of the 4-tuple: <SOURCE-IP>, <DESTINATION-IP>, and <DESTINATION-PORT>. The kernel would therefore have only 65536 possible choices and might return EADDRINUSE, as per the bind() manpage:). Unbeknownst to us, we had been operating for a very long time with far lower of a tolerance threshold than expected -- the ephemeral port range was effectively a limit to how much traffic we could tolerate per routing layer instance, while we thought no such limitation existed. The Fix Reading further in Bind before connect yields the fix: just set the SO_REUSEADDR socket option before the bind() call. In Erlang this is done by simply passing {reuseaddr, true}. At this point we thought we had our answer, but we had to be sure. We decided to test it. We first wrote a small C program that exercised the current limit: #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> int main(int argc, char **argv) { /* usage: ./connect_with_bind <num> <dest1> <dest2> ... <destN> * * Opens <num> connections to port 80, round-robining between the specified * destination IPs. Then it opens the same number of connections to port * 443. */ int i; int fds[131072]; struct sockaddr_in sin; struct sockaddr_in dest; memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(0); // source port 0 (kernel picks one) sin.sin_addr.s_addr = htonl(INADDR_ANY); // source IP 0.0.0.0 for (i = 0; i < atoi(argv[1]); i++) { memset(&dest, 0, sizeof(struct sockaddr_in)); dest.sin_family = AF_INET; dest.sin_port = htons(80); // round-robin between the destination IPs specified); fprintf(stderr, "GOING TO START CONNECTING TO PORT 443\n"); for (i = 0; i < atoi(argv[1]); i++) { memset(&dest, 0, sizeof(struct sockaddr_in)); dest.sin_family = AF_INET; dest.sin_port = htons(443);); } We increased our file descriptor limit and ran this program as follows: ./connect_with_bind 65536 10.11.12.13 10.11.12.14 10.11.12.15 This program attempted to open 65536 connections to port 80 on the three IPs specified. Then it attempted to open another 65536 connections to port 443 on the same IPs. If only the 4-tuple were in play, we should be able to open all of these connections without any problem. We ran the program under strace while monitoring ss -s for connection counts. As expected, we began seeing EADDRINUSE errors from bind(). In fact, we saw these errors even before we’d opened 65536 connections. The Linux kernel does source port allocation by randomly selecting a candidate port and then checking the N following ports until it finds an available port. This is an optimization to prevent it from having to scan all 65536 possible ports for each connection. Once that baseline was established, we added the SO_REUSEADDR socket option. Here are the changes we made: --- connect_with_bind.c 2016-12-22 10:29:45.916723406 -0500 +++ connect_with_bind_and_reuse.c 2016-12-22 10:31:54.452322757 -0500 @@ -17,6 +17,7 @@ int fds[131072]; struct sockaddr_in sin; struct sockaddr_in dest; + int one = 1; memset(&sin, 0, sizeof(struct sockaddr_in)); @@ -33,6 +34)); } @@ -48,6 +50)); } We ran it like this: ./connect_with_bind_and_reuse 65536 10.11.12.13 10.11.12.14 10.11.12.15 Our expectation was that bind() would stop returning EADDRINUSE. The new program confirmed this fairly rapidly, and showed us once more that what you may expect from theory and practice has quite a gap to be bridged. Knowing this, all we had to do is confirm that the {reuseaddr, true} option for the Erlang side would work, and a quick strace of a node performing the call confirmed that the appropriate setsockopt() call was being made. Giving Back It was quite an eye-opening experience to discover this unexpected connection limitation in our routing layer. The patch to Vegur, our open-sourced HTTP proxy library, was deployed a couple of days later, preventing this issue from ever biting us again. We hope that sharing our experience here, we might save you from similar bugs in your systems.
https://blog.heroku.com/sockets-in-a-bind
CC-MAIN-2020-34
refinedweb
1,744
63.39
These steps assume you are using a Mac or Linux operating system. If you are using Microsoft Windows, you need to adjust the commands. Although you can choose to use the console to manage Cloud Run for Anthos, there are some tasks that require the command-line tools. To install and configure the command-line tools for Cloud Run for Anthos: Install and initialize the Google Cloud CLI. Configure the Google Cloud CLI defaults: Set your default Google Cloud project: gcloud config set project PROJECT_ID Replace PROJECT_ID with the ID of your Cloud project. Set the target platform: gcloud config set run/platform kubernetes Set the location of your cluster: gcloud config set run/cluster_location ZONE_REGION Replace ZONE_REGION with the zone or region of your cluster. If you created and use a new namespace other than the defaultnamespace, you can set that namespace as the default in Google Cloud CLI so that it's used each time you run a command: gcloud config set run/namespace NAMESPACE Replace NAMESPACE with the name of the namespace that you want the gcloud CLI tool to use by default. Install the kubectlcommand-line tool: gcloud components install kubectl Optional: Ensure that all previously installed components are up-to-date: gcloud components update
https://cloud.google.com/anthos/run/docs/install/outside-gcp/command-line-tools
CC-MAIN-2022-33
refinedweb
209
54.56
Http and websockets logging handlers Hello, this posts will be about 3 specific logging handlers: HTTPHandler, SocketHandler and DatagramHandler. HTTPHandler Let's start with HTTPHandler: reading python docs about HTTPHandler we can see that: The HTTPHandler class, located in the logging.handlers module, supports sending logging messages to a Web server, using either GET or POST semantics. So this will be useful to have such handler in case of many different modules in different machines that sends logs to one central server. As an example, I will build simple flask application which prints out the logging message from the client. To install Flask: $ pip install Flask Then make server.py: from flask import Flask, request app = Flask(__name__) @app.route("/", methods=['POST', 'GET']) def hello(): for key, value in request.args.items(): print(key,value) return 'response' # it has to return something if __name__ == "__main__": app.run(debug=True) To send some data, create script called send_log.py: import logging import logging.handlers logger = logging.getLogger(__name__) server = '127.0.0.1:5000' path = '/' method = 'GET' sh = logging.handlers.HTTPHandler(server, path, method=method) logger.addHandler(sh) logger.setLevel(logging.DEBUG) logger.debug("Test message.") SocketHandler Now let's move to the SocketHandler: this is what python docs say about it The SocketHandler class, located in the logging.handlers module, sends logging output to a network socket. The base class uses a TCP socket. Based on this we can now guess that web socket will receive logging message.Then we can process it further. It will be useful when there is a lot of logs to be sent to the server. So opening HTTP connection every time is not a good solution. So first we need some TCP server: class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):(): tcpserver = LogRecordSocketReceiver() print('About to start TCP server...') tcpserver.serve_until_stopped() if __name__ == '__main__': main() What is going on here? In the main function we instantiate threading TCP server and we serve it until we don't hit Ctrl+C. In the serve_until_stopped method of LogRecordSocketReceiver we are waiting for the key combination to the stop server and if this not happening the we retrieve information about the socket by self.socket.fileno() which is a descriptor of a socket. Then we pass it to another function call: this time select(). Select is system call for examining the status of file descriptors of open input/output channels which in this case is information from the socket. If there is anything ready to be read we handle the request and process it. To process it we need handler: class LogRecordStreamHandler(socketserver.StreamRequestHandler): def handle(self): while True: chunk = self.connection.recv(4) if len(chunk) < 4: break slen = struct.unpack('>L', chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + self.connection.recv(slen - len(chunk)) obj = pickle.loads(chunk) print(obj) In method handle we read chunks of information from sent logging message. The chunk is byte type so then we need to translate it to python object by calling pickle.loads(). DatagramHandler Lastly, there is DatagramHandler which supports sending logging messages over UDP. The actual code is very similar to SocketHandler: class MyUDPHandler(socketserver.BaseRequestHandler): def __init__(self, request, client_address, server): socketserver.BaseRequestHandler.__init__(self, request, client_address, server) def handle(self): msg, socket = self.request print("{} wrote:".format(self.client_address[0])) print(pickle.loads(msg[4:])) socket.sendto(msg.upper(), self.client_address) Thanks to RooTer answer on stackoverflow I got this working by omitting first 4 bytes of data because they contain length of dumped object. Updates - 23.01.16 Thanks to RooTer answer I added UDP log handler
https://krzysztofzuraw.com/blog/2016/http-websockets-logging-handlers/
CC-MAIN-2022-21
refinedweb
606
60.01
Learn about compilation errors in your sketch and how to resolve them. Quick checks Make sure your error occurs during compilation by clicking Verify instead of Upload. This will compile the sketch without attempting to upload it. If your error only occurs when uploading, see Errors when uploading a sketch. A successful compilation will always finish with this message (the storage space and memory values might differ depending on the board used): Sketch uses 11604 bytes (4%) of program storage space. Maximum is 262144 bytes. Global variables use 2980 bytes (9%) of dynamic memory, leaving 29788 bytes for local variables. Maximum is 32768 bytes. A sketch always needs to include a setup()and loop()function, even if they’re not being used. You can use File > Examples > 1.Basics > BareMinimum as a template. Libraries added with #includeneed to be installed. Try searching for the library name in the Library Manager (Tools > Manage Libraries…). Interpreting the error message Arduino IDE displays compilation messages differently depending on the version: Check the IDE error message. - In IDE 1.x, it is displayed above the console window. - In IDE 2.x, it is displayed in a bottom-right pop-up. Sometimes, preceding lines can be more informative — check the console output. Check the console output. - Compilation errors will often reference the row and column where the error was triggered, i.g. Blink:29:1(line 29, 1 column). - You may have to scroll or expand the window width to see the entire message. Look for highlights in the editor: - In IDE 1.x, the line where the error occurred is highlighted in red. - In IDE 2.x, the character where the error occurred is underlined in red. - The line causing the error may be before the line where it was triggered. In the example above, line 28 is missing a semicolon ( ;), but the error will be triggered by the unexpected closing bracket ( }) in line 29. Troubleshoot a specific error Compilation error: Missing FQBN (Fully Qualified Board Name) When compiling or uploading code, this error will occur if no board is selected, or if the board core is not installed. A board needs to be selected even if you’re not uploading any code. Compilation error: Error: 2 UNKNOWN: platform not installed This error occurs when the required board core is not installed. Please ensure the core is installed using this guide. undefined reference to ‘setup’ or ‘loop’ collect2: error: ld returned 1 exit status Occurs when the setup() or loop() functions are missing. Your sketch must include these functions, even if they’re not being used. You can use File > Examples > 1.Basics > BareMinimum as a template. Note that function names are case-sensitive and that the compiler will handle something like Setup() (with a capital S) as a completely different function. fatal error: <library>: No such file or directory For example: sketch_may11a:22:10: fatal error: KeyboardController.h: No such file or directory #include <KeyboardController.h> ^~~~~~~~~~~~~~~~~~~~~~ compilation terminated. exit status 1 KeyboardController.h: No such file or directory - Check that the library name is spelled correctly and included with the proper format, e.g. #include <SPI.h>. - Make sure to import the .hfile. variable was not declared in this scope Occurs when a variable is accessed before being declared with the proper syntax, e.g. int i = 5, or if the variable is declared outside the current scope. In this exampled, the variable i is declared in the setup() function, and then accessed in the loop() function. void setup() { // put your setup code here, to run once: int i = 5; } void loop() { // put your main code here, to run repeatedly: i = i + 1; } Because the setup() function’s scope is not accessible from loop(), the compiler will return this error: sketch_may16a:3:3: error: 'i' was not declared in this scope i = 5; ^ exit status 1 'i' was not declared in this scope Instead of declaring i in setup(), it can be declared as a global variable: int i = 5; void setup() { // put your setup code here, to run once } void loop() { // put your main code here, to run repeatedly: i = i + 1; } expected unqualified-id before numeric constant Will occur if a comma ( ,) is used as a decimal separator instead of period ( .). This float is incorrectly assigned 1,1: float f = 1,1; It will trigger this error: sketch_may16a:3:15: error: expected unqualified-id before numeric constant float f = 1,1; ^ exit status 1 Instead, use a decimal point ( .): float f = 1.1; expected ‘,’ or ‘;’ before ‘:’ token sketch_may16a:3:19: error: expected ',' or ';' before ':' token int i = 1: ^ exit status 1 This error occurs because a line has been ending with a colon ( :) instead of a semicolon. ( ;). The line should look like this: int i = 1; ‘expected declaration before ‘}’ token’, or ‘expected ‘}’ at end of input’ These errors can occur when brackets ( { and } are incorrectly used. - Make sure that brackets are opened and closed in the expected order. - Use Tools > Auto Format to make your code more readable. - If you click on a bracket, the associated opening or closing bracket will be highlighted. Still need help? Arduino sketches are written in the Arduino language, which is based on standard C++ language. Most likely you will find a wealth of resources by searching C++ <error message>in your search engine. For help with functions specific to Arduino, see the Arduino functions reference. Visit the Programming Questions category in the Arduino forum. Start by reading the pinned threads which will contain useful information on how to best post a question. See Troubleshooting Guide For Arduino > Compiling.
https://support.arduino.cc/hc/en-us/articles/4402764401554-If-your-sketch-doesn-t-compile
CC-MAIN-2022-40
refinedweb
933
65.32
Estimated reading time: 3 minutes Python arrays are used to manage how data is analysed and have the data in a structured form for the data analyst or data scientist to use. What is an Array? An array has the following properties: - The data in it is of the same data type. - The data is stored as contiguous memory locations, meaning meaning the lowest value is at index 0 and the last value is at the highest index value. - Arrays assign index values to each data point contained within it. - You can append values to the array. - You can delete values from the array, that is it is mutable. What are the differences between arrays and lists? For the most part arrays and lists are the same, but with one difference: A list can store any data type you want e.g. strings, integers etc. On the other hand, arrays can only store data that is of the same data type. What are the different ways that I can create an array? import numpy as np a = np.array([1,2,3]) print(a) print(type(a)) Output: [1 2 3] <class 'numpy.ndarray'> (B) Use array import array as test_array a = test_array.array('i',[1,2,3]) print(a) Output: array('i', [1, 2, 3]) <class 'array.array'> On the Python.org website, below are the list of values that can be populated into the above program, depending on what your need is: When should I use arrays? It really depends on the nature of your python program, but below are some examples that may help you make a decision: (A) Many variables of the same type : There maybe a scenario where you have to create an array to store data that is of the same data type. For example you have a list of codes to look up against, which are all integers. (B) Faster and more efficient : If speed is what you are looking for using arrays, will help improve performance of your computer program, using lists is much slower. (C) Compactability and efficiency : If the nature of your program needs to store large amounts of data that needs to be accessed quickly , then this would be a good reason to use them. (D) Ability to retrieve data quickly through indexing: As arrays have index values associated with them, they data can be easiy retrieved. (E) Need to compute some mathematical values: Arrays are excellent for any numerical operations you need to complete, as the level of coding is minimal. import array as test_array a = test_array.array('i',[1,2,3]) mydivider = 2 mynewlist = [x / mydivider for x in a] print(mynewlist) result: [0.5, 1.0, 1.5] So in summary: Speed , efficiency and ease of use are the main reasons to use an array. We use arrays here in how to show percentage differences between files in python , why not go over and see it in action!
https://pickdigit.com/what-is-an-array-in-python/
CC-MAIN-2022-33
refinedweb
492
63.09
. Writing a test class is very straight forward. You create a class that inherits from the Test abstract base class. If you want to expose some properties to the TestConfiguration user interface, you declare them as public getter and setters. You can decorate the properties with a number of attributes like : - [MandatoryField] to declare is a mandatory (not optional) field. - [Description] to put a textual description in the user interface editor. - [DefaultValue] to give the property a default value. The diagram below gives you an idea as to the structure of a test and its base class. The Run() method is the method that gets automatically executed to run the test. You then assert whether you have achieved you pass or fail using the AssertState and AssertException classes. This is quite similar to how NUnit or MSTest works. The Test base class also contains a CreateExamples() method. In this method you create an instance of the test and populate the properties with example data. Then from the command line application or the user interface you can generate an example test script that contains examples for each test. This is a great way to create self documenting tests. So, with what we discussed above, what does a test look like. Below is a very simple test that check for the presence of a folder in the file system, Although this is a very simple test, it is also a very valuable type of test as you can use it to ensure that your installation MSI or script has created the correct folder structure. using System.Collections.Generic; using System.IO; using ConfigurationTests.Attributes; using System.ComponentModel; using Common.Boolean; namespace ConfigurationTests.Tests { public class FolderExistsTest : Test { private bool _shouldExist = true; [MandatoryField] [Description("Directory of file")] public string Path { get; set; } [DefaultValue(true)] [Description("True to check if file exist")] public bool ShouldExist { get { return _shouldExist; } set { _shouldExist = value; } } public override void Run() { if (Directory.Exists(Path) != ShouldExist) { throw new AssertionException(string.Format("Folder was {0}present", ShouldExist.IfTrue("not "))); } } public override List<Test> CreateExamples() { return new List<Test> { new FolderExistsTest{Path=@"c:\Windows\System32",TestName = "Check System32 folder"} }; } } } As you can see above, the test is called FolderExistsTest, and this inherits from Test. The base class exposes one default property. This is the TestName property. Every test has one of these. FolderExistsTest then exposes two more properties Path and ShouldExist. These will show up in the Test Configuration user interface like the screen shot below. The main test is executed in the Run() method. The code here is very straight forward. If the result of Directory.Exists() doesn’t match the ShouldExist property, then throw an AssertionException which which will fail the test. public override void Run() { if (Directory.Exists(Path) != ShouldExist) { throw new AssertionException(string.Format("Folder was {0}present", ShouldExist.IfTrue("not "))); } } The next method is CreateExamples(). This method creates an example of the test with dummy data set up in the properties and return it in a list. This is the systems way of providing some self documentation. public override List<Test> CreateExamples() { return new List<Test> { new FolderExistsTest{Path=@"c:\Windows\System32",TestName = "Check System32 folder"} }; } That is all there is to creating a test. Provided the test inherits from the Test base class, then it will be picked up by the editor or the command line test runner using reflection. I hope you can see that actually, the Post Deployment Smoke Tester, is a very simple tool in what it does, but the benefits it can give you for checking deployments is invaluable. Pingback: binary dreams | How to check the results of an XPath query against an XML document using the SmokeTester
https://stephenhaunts.com/2014/06/09/the-smoke-tester-solution-and-your-first-test/
CC-MAIN-2017-13
refinedweb
616
58.28
The X.500 directory service is a global directory service. Its components cooperate to manage information about objects such as countries, organizations, people, machines, and so on in a worldwide scope. It provides the capability to look up information by name (a white-pages service) and to browse and search for information (a yellow-pages service). The information is held in a directory information base (DIB). Entries in the DIB are arranged in a tree structure called the directory information tree (DIT). Each entry is a named object and consists of a set of attributes. Each attribute has a defined attribute type and one or more values. The directory schema defines the mandatory and optional attributes for each class of object (called the object class). Each named object may have one or more object classes associated with it. The X.500 namespace is hierarchical. An entry is unambiguously identified by a distinguished name (DN). A distinguished name is the concatenation of selected attributes from each entry, called the relative distinguished name (RDN), in the tree along a path leading from the root down to the named entry. Users of the X.500 directory may (subject to access control) interrogate and modify the entries and attributes in the DIB. For more information on the X.500, refer to the CCITT X.500 (1988/1993)/ISO Directory. Naming ConventionAlthough the concepts of distinguished names and relative distinguished names are core to the X.500 model, the X.500 standard itself does not define any string representation for names. What is communicated between the X.500 components is the structural form of names. The reasoning behind this is that the standard is sufficient to allow different implementations to interoperate. String names are never communicated between different implementations. Instead, they are necessary only for interaction with end-users. For that purpose, the standard allows any representation, not necessarily only string representations. Systems that are based on the X.500, such as the LDAP, the DCE Directory, Novell's NDS, and Microsoft's Active Directory, each define its own string representation. For example, in the LDAP, a DN's RDNs are arranged right to left, separated by the comma character (","). Here's an example of a name that starts with "c=us" at the top and leads to "cn=Rosanna Lee" at the leaf.cn=Rosanna Lee, ou=People, o=Sun, c=us Here's an example of the same name using the string representation of the DCE Directory and Microsoft's Active Directory.The convention for these systems is that RDNs are ordered left to right and separated by the forward slash character ("/").The convention for these systems is that RDNs are ordered left to right and separated by the forward slash character ("/")./c=us/o=Sun/ou=People/cn=Rosanna Lee ProtocolsThe X.500 standard defines a protocol (among others) for a client application to access the X.500 directory. Called the Directory Access Protocol (DAP), it is layered on top of the Open Systems Interconnection (OSI) protocol stack. Application Programming InterfacesThe X.500 standard itself does not define an API for accessing the directory. Again, the X.500 standard is mainly concerned with interoperability between directory clients and directory servers and between different directory servers. One standard API that has been defined for the X.500 is the X/Open Specifications API to Directory Services (XDS), a C language-based API that client programs use for accessing X.500 directories.
http://docs.oracle.com/javase/jndi/tutorial/ldap/models/x500.html
CC-MAIN-2013-48
refinedweb
578
50.12
PyF Quasiquotations for a python like interpolated string formater See all snapshots PyF appears in Module documentation for 0.9.0.0 PyF-0.9.0.0@sha256:5a53a09e390271b124b4ac366e1c28da88136bbdf605a5c0ae6be9f0fd4a123f,2567 PyF PyF is a Haskell library for string interpolation and formatting. PyF exposes a quasiquoter f which introduces string interpolation and formatting with a mini language inspired from printf and Python. Quick Start >>> import PyF >>>>> age = 54 >>> [fmt|Person's name is {name}, age is {age}|] "Person's name is Dave, age is 54". ExtendedDefaultRules and OverloadedStrings may be more convenient. Expression to be formatted are referenced by {expression:formatingOptions} where formatingOptions follows the Python format mini-language. It is recommended to read the python documentation, but the Test file as well as this readme contain many examples. More Examples Padding Left < / Right > / Around ^ padding: >>>>> [fmt|{name:<11}|] "Guillaume " >>> [fmt|{name:>11}|] " Guillaume" >>> [fmt|{name:|^13}|] "||Guillaume||" Padding inside = the sign >>> [fmt|{-3:=6}|] "- 3" Float rounding >>> [fmt|{pi:.2}|] "3.14" Binary / Octal / Hex representation (with or without prefix using #) >>> v = 31 >>> [fmt|Binary: {v:#b}|] "Binary: 0b11111" >>> [fmt|Octal: {v:#o}|] "Octal: 0o37" >>> [fmt|Octal (no prefix): {v:o}|] "Octal (no prefix): 37" >>> [fmt|Hexa (caps and prefix): {v:#X}|] "Hexa (caps and prefix): 0x1F" Grouping Using , or _. >>> [fmt|{10 ^ 9 - 1:,}|] "999,999,999" >>> [fmt|{2 ^ 32 -1:_b}|] "1111_1111_1111_1111_1111_1111_1111_1111" Sign handling Using + to display the positive sign (if any) or to display a space instead:to display a space instead: >>> [fmt|{pi:+.3}|] "+3.142" >>> [fmt|{-pi:+.3} (Negative number)|] "-3.142 (Negative number)" >>> [fmt|{pi: .3}|] " 3.142" >>> [fmt|{-pi: .3} (Negative number)|] "-3.142 (Negative number)" 0 Preceding the width with a 0 enables sign-aware zero-padding, this is equivalent to inside = padding with a fill char of 0. >>> [f{10:010}|] 0000000010 >>> [f{-10:010}|] -000000010 Sub-expressions First argument inside the curly braces can be a valid Haskell expression, for example: >>> [fmt|2pi = {2* pi:.2}|] 2pi = 6.28 >>> [fmt|tail "hello" = {tail "hello":->6}|] "tail \"hello\" = --ello" However the expression must not contain } or : characters. Combined Most options can be combined. This generally leads to totally unreadable format string ;) >>> [fmt|{pi:~>5.2}|] "~~3.14" Multi-line strings You can ignore a line break with \ if needed. For example: [fmt|\ - a - b\ |] Will returns -a\n-b. Note how the first and last line breaks are ignored. Arbitrary value for precision The precision field can be any haskell expression instead of a fixed number: >>> [fmt|{pi:.{1+2}}|] 3.142 Output type PyF aims at extending the string literal syntax. As such, it default to String type. However, if the OverloadedString is enabled, PyF will happilly generate IsString t => t instead. This means that you can use PyF to generate String, but also Text and why not ByteString, with all the caveats known to this extension. >>> [fmt|hello {pi.2}|] :: String "hello 3.14" Custom types PyF can format three categories of input types: - Floating. Using the f, g, e, … type specifiers. Any type instance of RealFloatcan be formated as such. - Integral. Using the d, b, x, o, … type specifiers. Any type instance of Integralcan be formated as such. - String. Using the stype specifier. Any type instance of PyFToStringcan be formated as such. See PyF.Class if you want to create new instances for the PyFToString class. By default, if you do not provide any type specifier, PyF uses the PyFClassify type class to decide if your type must be formated as a Floating, Integral or String. Caveats Type inference Type inference with numeric literals can be unreliable if your variables are too polymorphic. A type annotation or the extension ExtendedDefaultRules will help. >>> v = 10 :: Double >>> [fmt: >>> [fmt|{age:.3d}|] <interactive>:77:4: error: • <interactive>:1:8: | 1 | {age:.3d} | ^ Type incompatible with precision (.3), use any of {'e', 'E', 'f', 'F', 'g', 'G', 'n', 's', '%'} or remove the precision field. - Error in variable name are also readable: >>> [fmt|{toto}|] <interactive>:78:4: error: Variable not in scope: toto - However, if the interpolated name is not of a compatible type (or too polymorphic), you will get an awful error: >>*> [fmt|: *PyF PyF.Internal.QQ> [fmt|{"hello":=10}|] <interactive>:89:10: error: • String Cannot be aligned with the inside `=` mode ... - Finally, if you make any type error inside the expression field, you are on your own: >>> [fmt|mtWithDelimiters ('@','!') Later, in another module: import MyCustomQQ -- ... [myCustomFormatter|pi = @pi:2.f!|] Escaping still works by doubling the delimiters, @@!!@@!! will be formatted as @!@!. in every places, such as {expression:.{precision}}. We only support it for precision. This is more complexe to setup for others fields. - Python literal integers accepts binary/octal/hexa/decimal literals, PyF only accept decimal ones, I don’t have a plan to support that, if you really need to format a float with a number of digit provided as a binary constant, open an issue. - Python support adding custom formatters for new types, such as date. This may be really cool, for example [fmt| ,. - Custom delimiters Build / test Should work with stack build; stack test, and with cabal and (optionally) nix: nix-shell # Optional, if you use nix cabal new-build cabal new-test. Changes Revision history for PyF 0.9.0.0 – 2019-12-29 - Any type with Showinstance can be formatted using :sformatter. For example, [fmt|hello {(True, 10):s}|]. This breaks compatibility because previous version of PyF was generating an error when try to format to string anything which was not a string, now it accepts roughly anything (with a Showinstance). 0.8.1.2 – 2019-11-08 - Bump megaparsec bounds 0.8.1.1 – 2019-10-13 - Compatibility with GHC 8.8 0.8.1.0 – 2019-09-03 - Precision can now be any arbitrary haskell expression, such as [fmt|hello pi = {pi:.{1 + 3}}|]. 0.8.0.2 – 2019-08-27 - (minor bugfix in tests): Use python3 instead of “python” to help build on environment with both python2 and python3 0.8.0.1 – 2019-08-27 - Stack support.
https://www.stackage.org/lts-15.3/package/PyF-0.9.0.0
CC-MAIN-2020-16
refinedweb
1,005
57.98
Thank you for the feedback. We have improved the performance of the Single.IsNaN and Double.IsNaN routines for a future release of the .NET Framework. Sincerely, Josh Free Base Class Library Development If you do math on arrays of double that contain large numbers of NaN's or Infinities, there is an order of magnitude performance penalty. I first noticed the NaN problem when I had a large array of doubles, most of which were NaN, and I had a loop that was searching for the maximum value. With the array filled with NaNs, it took around 10s to search instead of ~300 ms. When I looked at the disassembly, it was using the FCOMIP instruction rather than FUCOMIP. The first raises the floating point exception for any type of NaN, while the second only raises the exception for signaling NaNs. I’m not sure why this is done, as so far as I know .Net never throws floating point exceptions. I’m not sure that FUCOMIP would fix the problem, but it seems likely. As a workaround, I added a test for NaN to the search. However, this does not solve the problem as the .NET implementation of Double.IsNaN seems to be something like: bool IsNaN(y) { return y != y } This ends up using the same FCOMIP comparison instruction, thus even trying to check for NaN causes a major slowdown if lots of NaNs are present! I ended up writing my own check for NaN: static public unsafe bool IsNaN(this double value) { // Exponent of all ones, mantissa non-zero return ((*(ulong*)&value) & 0x7fffffffffffffffL) > 0x7ff0000000000000L; } It's not just the comparisons that have the performance problem. I've also seen it with other array operations, such as multiplying by a scalar. Requests: 1) Make IsNaN() fast, like the one I suggest. 2) Don't use the instructions that raise floating point exceptions. Please wait... Thanks again. Regards, Kevin Frei CLR Codegen Team
https://connect.microsoft.com/VisualStudio/feedback/details/498934/big-performance-penalty-for-checking-for-nans-or-infinity
CC-MAIN-2015-48
refinedweb
325
73.98
How the dependency property is used to load the register it is associated with depends on its type and WPF currently support the following dependency property types: In each case the C# data type is packed into the four elements of the HLSL float4 register. In our example the register is going to be used as a color so it makes sense to define a Color dependency property and allow the system to perform the mapping to the float4 register. Defining the dependency property follows the usual course. First we create a standard set/get property that used the dependency property: public Color PixelColor{ get { return (Color)GetValue( PixelColorProperty); } set { SetValue(PixelColorProperty, value); }} Then we create the dependency property adding "Property" to the end of the name: public static readonly DependencyProperty PixelColorProperty = DependencyProperty.Register( "PixelColor",typeof(Color), typeof(BlankEffect), new UIPropertyMetadata(Colors.White, PixelShaderConstantCallback(0))); Notice that this is a perfectly normal dependency property apart from the use of the PixelShaderConstantCallback(0) which connects the property to the c0 register. Now we can create an effect object, set the dependency property and use it to modify the way a button displays. For example: BlankEffect BE = new BlankEffect();BE.PixelColor = Color.FromArgb(255, 0, 255, 0);button1.Effect = BE; We have set the color to full green. Finally for it all to work we need to modify the shader code: float4 pixelcolor:register(c0);float4 main(float2 uv:TEXCOORD):COLOR{ return pixelcolor;} Remember to save and compile the shader .fx file to create an up-dated .ps file. If you now run the program you will see a green block appear in place of the button's usual rendering. So far all we have managed to do is pass a constant value to the shader and return it as the color of the pixel. We obviously need to gain access to and process the pixels that rendering the control actually produces. The key to this, and generally with working with bitmaps in shaders is, the sampler. A sampler is a, usually small, bitmap that is stored in video memory. A sampler can be used in many different ways. For example, if you have a small bitmap of a section of texture, fur say, you can use it to map onto another object as it renders to the screen. This is the original and most common use of the sampler and it is the reason a sampler is called a sampler - i.e. it allows you to sample a texture. However, it is also possible to use samplers for many other purposes including just rendering an image to the screen. Samplers are passed to an HLSL program using registers. In pixel shader 2.0 you can use up to 16 shaders specified in S0 to S15 but WPF limits you to using a maximum of four. Using a shader follows the same steps as using a constant. In the HLSL program you first declare a variable and associate it with a shader register. For example: sampler2D bitmap1:register(s1); sets up the variable bitmap1 as a sampler2D data type and associates it with register s1. Following this declaration you can work with bitmap1 as if it was a 2D bitmap sampler. In the C# program you have to create a dependency property of type Brush and associate it with the shader register using the special RegisterPixelShaderSamplerProperty static method which is supplied by the ShaderEffect class. That is, to make the connection between the bitmap that is represented byt the Brush and the sampler register you have to register the dependency property in a special way. Once you have the dependency property and the sampler setup you can set the dependency property to a suitable bitmap within your C# program and work with it as the sampler in you HLSL program. Let's see each step in action by using a sampler to define what is rendered for a button object. First let's create the shader program: sampler2D bitmap1:register(s1);float4 main(float2 uv:TEXCOORD):COLOR{ float4 color=tex2D(bitmap1,uv); return color;} This associates the variable bitmap1 with sampler register s1. In the body of the function we make use of the function tex2D which takes a sampler as its first parameter and a texture coordinate as its second parameter. The function returns the color of the pixel at the coordinate specified by uv and this is returned as the colour of the rendered pixel. Hence we are simply transferring the image in the sampler to the output target. At this point we need to understand texture coordinates a little better. Texture co-ordinates always work in the same way. The top left-hand corner is (0.0) and the bottom-right is (1,1) - irrespective of the number of pixels in the graphic. What this means is that texture co-ordinates always specify a point within the graphic and graphics are automatically scaled to fit the area they are being mapped to. In this case the input texture co-ordinate uv which is passed into the shader is a point in the area to be rendered i.e. in this example the button's render area. The same (0,0) to (1,1) co-ordinates are mapped to the sampler's entire area with the result that the entire sampler is mapped to the entire button render area. <ASIN:143022455X> <ASIN:0596800959> <ASIN:143022519X> <ASIN:1430272910>
http://www.i-programmer.info/programming/wpf-workings/892-custom-bitmap-effects-hlsl.html?start=1
CC-MAIN-2016-50
refinedweb
907
52.7
I love dependency injection frameworks ever since I started using them. Specifically, I’m obsessed with using Autofac and I have a hard time developing applications unless I can use a solid DI framework like Autofac! I’ve recently been working with Xamarin and found that I wanted to use dependency injection, but some of the framework doesn’t support this well out of the box. I’ was adamant to get something going though, so I wanted to show you my way to make this work. Disclaimer: In its current state, this is certainly a bit of a hack. I’ll explain why I’ve taken this approach though! In your Android projects for Xamarin, any class that inherits from Activity is responsible for being created by the framework. This means where we’d usually have the luxury of passing in dependencies via a constructor and then having Autofac magically wire them up for us isn’t possible. Your constructors for these classes need to remain parameterless, and your OnCreate method is usually where your initialization for your activity will happen. We can work around that though. My solution to this is to use a bit of a reflection hack coupled with Autofac to allow Autofac resolutions in the constructor as close as possible as to how they would normally work. A solution I wanted to avoid was a globally accessible reference to our application’s lifetime scope. I wanted to make sure that I limited the “leakage” of this not-so-great pattern to as few places as possible. With that said, I wanted to introduce a lifetime scope as a reference only to the classes that were interested in using Autofac where they’d otherwise be unable to. - Make a static readonly variable in your classes that care about doing Autofac with a particular name that we can lookup via reflection. (An alternative is using an attribute to mark a static variable) - After building your Autofac container and getting your scope (but prior to using it for anything), use reflection to check all types that have this static scope variable. - Assign your scope to these static variables on the types that support it. - In the constructors of these classes (keeping them parameterless so the framework can still do its job!), access your static scope variable and resolve the services you need Here’s what that looks like in code! MainActivity.cs public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { var builder = new ContainerBuilder(); // TODO: add your registrations in! var container = builder.Build(); var scope = container.BeginLifetimeScope(); // the static variable i decided to use is called "_autofacHack" // so that it deters people from using it unless they know // what it's for! you could use reflection to find similar // fields with something like an attribute if you wanted. foreach (var field in GetType() .Assembly .GetTypes() .Select(x => x.GetField("_autofacHack", BindingFlags.NonPublic | BindingFlags.Static)) .Where(x => x != null)) { field.SetValue(null, scope); } LoadApplication(scope.Resolve<App>()); } The class that can take advantage of this would look like the following: public sealed class MyActivityThatNeedsDependencyInjection : Activity { private static readonly ILifetimeScope _autofacHack; private readonly IMyService _theServiceWeWant; // NOTE: we kept the constructor PARAMETERLESS because we need to public MyActivityThatNeedsDependencyInjection () { _theServiceWeWant= _autofacHack.Resolve<IMyService>(); } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // now we can use this service that we "injected" _theServiceWeWant.DoTheCoolStuff(); } } Summary Reading this you might think “well I don’t want to pollute my Xamarin code with variables that say _autofacHack, that’s gross”. And I don’t blame you! So this is to serve as a starting point for a greater solution, which I think is something I’ll evolve out for myself and I encourage you to do the same. Things I’m focused on: - Minimize where “ugly” code is. A globally accessible scope on a static class seems like it can spread the “ugly” code to too many spots. This approach is intended to help minimize that. What are some next steps to make that EVEN better? Maybe an attribute so we can call it something nicer? - Write code that feels as close as possible to the “real” thing. Autofac usually allows us to specify services in the constructor and then automatically allows us to get the instances we need. This code is structured to be very similar, but since we’re NOT allowed to change the parameterless constructors, we resolve our services off the container there instead. And because it’s in the constructor, we can assign things to readonly variables as well which is a nice bonus. The more implementations of this I go to use, the more I plan to refine it! How have you leveraged Autofac in your Xamarin projects?
http://devleader.ca/tag/dependency-injection/
CC-MAIN-2022-05
refinedweb
794
54.22
14 posts in this topic You need to be a member in order to leave a comment Sign up for a new account in our community. It's easy! Register a new account Already have an account? Sign in here. Similar Content - GUICtrlSetResizing and hidden window By TommyDDR Hi, I have to set a resizing mode to differents controls in a hidden gui, that gui is initialised (hidden) and resized by a WinMove. But when i show it, control are not resized where thez should. There is a simple code that reproduce the problem. Same gui, same content, one displayed then moved, the other moved then displayed : #include <GUIConstantsEx.au3> Opt("GUIOnEventMode", 1) Opt("MustDeclareVars", 1) Global $gui[2] Global $labels[2] Global $taille[2] = [200, 100] For $i = 0 To UBound($gui, 1) - 1 $gui[$i] = GUICreate($i, $taille[0], $taille[1], $i * ($taille[0]+100) + 500, (@DesktopHeight-$taille[1])/2) GUISetOnEvent($GUI_EVENT_CLOSE, "quit", $gui) $labels[$i] = GUICtrlCreateLabel("Test resizing...", $taille[0]-105, $taille[1]-25, 100, 20) GUICtrlSetBkColor($labels[$i], 0xE0E0E0) GUICtrlSetResizing($labels[$i], BitOR($GUI_DOCKRIGHT, $GUI_DOCKBOTTOM, $GUI_DOCKWIDTH, $GUI_DOCKHEIGHT)) Next GUISetState(@SW_SHOW, $gui[0]) For $i = 0 To UBound($gui, 1) - 1 WinMove($gui[$i], "", Default, Default, $taille[0]+100, $taille[1]+100) Next GUISetState(@SW_SHOW, $gui[1]) While(True) Sleep(10) WEnd Func quit() Exit EndFunc Is that a bug or do miss i something ? EDIT : This bug disapear if gui is shown at lease one time (even if hide then) - Looped Array Out of Range (_Excel_RangeFind output)) - [Solved] SciTE no functions working - Again WinHTTP and Proxy By Simpel Hi - [SOLVED]Count duplicates in an array By yhu420 Hello everyone, I just have a beginner question: is there a way to count duplicates in an array? If you don't see what I mean, here is an example of what I mean: $arr[5] = ['a', 'a', 'b', 'b', 'c'] ; the array countDuplicates($arr); Representing the data in a bidimensionnal array, this would return: #cs ['a'][2] ['b'][2] ['c'][1] Of course this is a bit messy, but that's just for you to get the idea #ce I'm trying to achieve this to check whether yes or no an array has more or same amount of occurrences of a character than another array. Am I doing this the right way? Does such a function exist? Thanks for everything
https://www.autoitscript.com/forum/topic/184891-solved-file-downloading-through-browser-but-not-script/
CC-MAIN-2016-44
refinedweb
393
55.17
Aligned CR14 chamber back to 3" disks.. Turbo pump off and spinning down at 9:37am LT. Pumo completely stopped at 11:15am LT Openend the chamber and removed the sample at ~11:20am LT I modified four more QPD boards to implement the new whitening filters detailed in elog 207. Ordered the clean room (hardware+hepa filters) and vacuum gauges. The clean room frame is built and secured to the floor and wall. Panels are being installed on the ceiling and back. Also, the optical table has been leveled. Ceiling, back and side panels are installed. The air filters have been cabled and connected to the power supply.. Some progress on the cleam room: bar fixed to the wall, some more structure built, filters in place. We had to (literally) work around a corner of the low ceiling that we haven't noticed before. More contruction will follow tomorrow. We also had to order some additional parts (more extrusions, brackets, screws, etc...) The plot below compares the measured Q values of S1600433 right after annealing, and after GariLynn cleaned it. Q values are in general improved a bit after cleaning. Samples #433 (annealed and cleaned) and #438 (as received from Mark Optics) are now with GariLynn for deep cleaning. Sample #438 was broken during annealing. The plot below compares a sample from the first batch and two samples from the second batch. All samples are as received from Mark Optics, no annealing or any other treatment. Both samples in the second batch show consistently and significantly lower Q values. GariLynn and I inspected the two samples under the microscope. Surprisingly, the edges and the flats look much better than the samples from the first batch. See elog 148 for an image of a sample from the first batch Link to IMG_3158.JPG Link to IMG_3157.JPG Link to IMG_3156.JPG Link to IMG_3155.JPG The PCBs for the QPD circuit and ADC interface are here and look ok. All electronics components are also here (except for the ADC connector which should be ordered separately from Mouser, after confirming that the ADC we're going to use have the same cable as the one we use in the Crackling Noise experiment). The QPD will be shipped on 06/17. got two new ADC and DAC boards from Rolf, with the correct PCIe interface. I installed them into the cymac and checked that the system could boot. The cymac is now sitting in the rack. As requested by Jamie I installed Debian 8.5: MO03 - edge polished: Turbo off, QPD centered, before excitation (60 seconds) PDT: 2016-08-23 08:42:54.514987 PDT UTC: 2016-08-23 15:42:54.514987 UTC GPS: 1156002191.514987 Excitation (white uniform noise, amplitude 5 V) PDT: 2016-08-23 08:45:01.007626 PDT UTC: 2016-08-23 15:45:01.007626 UTC GPS: 1156002318.007626 Clean data for ring-down PDT: 2016-08-23 08:45:46.448949 PDT UTC: 2016-08-23 15:45:46.448949 UTC GPS: 1156002363.448949 Restarted roughing pump, QPD got misaligned PDT: 2016-08-23 10:00:29.259345 PDT UTC: 2016-08-23 17:00:29.259345 UTC GPS: 1156006846.259345 Band-limited noise, +-10Hz around eahc nominal frequency, amplitude scaled based on the inverse of the peak height obtained with white noise. See attached code and plot from numpy import * from noise import * x = loadtxt('/home/controls/Measurements/2016_08_23/mo_02_laserpolished_frequencies.txt') freqs = x[:,0] ampl = x[:,1] bw = 10 bands = map(lambda x: [x - bw, x + bw], freqs) a = 1 / (ampl/max(ampl)) a[a>50] = 50. x = multi_band_noise(bands, a, 10, fs=65536) x = x / 30 Ring down after: PDT: 2016-08-23 11:07:02.661145 PDT UTC: 2016-08-23 18:07:02.661145 UTC GPS: 1156010839.661145. For the optical levers we are going to use the same QPD that are used in aLIGO optical levers (see T1600085 and D1100290): Hamamatsu S5981 Based on the aLIGO design, I put together a design fof the QPD boards, see the first attached PDF file. Some comments: The stable power supply will be provided by an additional board, which will also interface 8 QPD boards to the ADC connector, see the second attached PDF. The ADC signal grounds can be connected directly to the power supply ground, left floating, or connected with a RC filter, depending on what we find to be the best solution. Total cost estimated for PCB manufacturing and components, including the QPDs is less than 3k$, for a total of 12 boards (we need 8, plus some spares). After a very useful discussion with Rich this morning, I think the circuit based on aLIGO optical levers design should be good for our applications. It uses a LT1125 as input stage, which has We expect to send about 5 mW into the disk, getting back a 4% reflection, which would correspond to 200 uW on the QPD. Let's say we lose half of this power in reflections through viewports and such, so we have a total of 100 uW on the QPD, or 25 uW on each quadrant. From the QPD datasheet the repsonse is about 0.4 A/W, so we have a photocurrent of 10 uA. The corresponding shot noise limit is about 1.8e-12 A/rHz. Using a transimpendace of 200k, the noise at the output of the transimpendance is So in the worst case the current noise will be about half of the shot noise. This seems good enough. Disk excited with white uniform noise, amplitude 5 V, for some tens of seconds. Excitation off at PDT: 2016-09-13 10:32:23.887615 PDT UTC: 2016-09-13 17:32:23.887615 UTC GPS: 1157823160.887615. It's possible to build an analytical model of the resonant frequencies of a simple thin disk. For example, see J. Sound and Vibrations 188, 685 (1995), section 2 The solutions are given in term of Bessel functions: where J is a Bessel function of the first kind, and I a modified Bessel function of the first kind, a is the disk radius. The coefficient Cmn and the eigenvalue can be found as solution of the following two equations Then the eigenfrequencies are given by where rho is the material density, h the disk thickness and D the flexural rigidity where E is the material Young's modulus and nu the Poisson's ratio. From all those results we can conclude that the frequency scaling with respect to disk radius and thickness are very simple: Also, the frequencies scales as sqrt(E/rho) The dependency on the Poisson's ratio is more complex since nu is involved in the eigenfrequency equation shown above. Unfortunately the thin disk model does not exactly match the COMSOL results: deviations of few tens of Hz are present, probaly due to the thin disk approximation. The COMSOL model is more accurate to match the experimental frequencies. However, I checked that the eigenfrequencies predicted by COMSOL also scales as predicted with thickness and radius. Using the measurements on the six samplex we got from Mark Optics, after annealing, I was able to tune the COMSOL model to fit all measured frequencies within 6 Hz. I chose to change the disk thickness (since diameter and Young'r modulus are degenerate) and the Poisson's ratio. Here is an example of the difference between the measured and modeled frequencies: The table below summarizes the best fit for each of the disks Since the material is the same, I would expect the Poisson's ratio to be constant. So for future modeling I'm using the average of the values above: 0.166 A preliminary design of the ESD board is available on the DCC: D1600214 We first measured the distance of the ESD from the disk in the test chamber (CR0). We had to remove the retaining ring to have reliable measurements So initially the distance between disk and ESD is 1.22 mm We re-aligned the optical setup to a horizontal reference, and moved down the ESD as much as we could. It's not completely clear if the ESD is touching the disk. We'll see after pump down. The new distance from the top of the ESD to the mounting plate is about 11.80 mm, so we should have moved the ESD 0.5mm closer to the disk. Pump down started at ~1:30pm The plots below compare the SNR and peak amplitude of all excited modes, in the new and old configuration. The new confgiuration is worse than the old one. This is unexpected, since the distance between ESD and disk is smaller. However, yesterday we found out that setting the ESD so close to the disk is very tricky, and we might have some touching. Additionally, the measured Q values of all modes are signfiicantly lower (by factors of >3), so it seems there is some additional friction. The mode frequencies are still compatible with the expected values, so it's unlikely that the ESD is touching the disk. One possible explanation for the worse Q can be residual gas damping in the area between the ESD and the disk: basically the gas moelcules that are left in the enclosed region between disk and ESD can create a viscous damping, which gets larger when the distance gets smaller [PhysRevLett.103.140601, arxiv:0907.5375]. I'll try to do some computations later today. I made a COMSOL model that can compute the distribution of elastic energy for each mode, dividing it into: Then I used the measured Q values for the MO_101 disk and tried to see if I could reproduce it with the energy distribution. The first plot here shows that the loss angle of the disk (inverse of the Q) has a trend that is already quite well reproduced by the ratio on edge energy over total energy: In particular the edge energy distribution is enough to explain the splitting of the modes in families. This fit is obtained assuming that the edge losses are uniform along the entire edge, and frequency independent. If we assume a "thickness" of the edge of the order of 1 micron, the loss angle is about 3.5e-3, which seems resonable to me since the edge is not polished. Then I tried to improve the fit by adding also bulk, shear and surface losses. It turns out that shear is not very important, while bulk and surface are almost degenerate. The following plot shows a fit using only edge and surface losses: The result is improved, expecially for the modes with lower loss angle. Again, assuming a surface thickness of 1 micron, the main surfaces have a loss angle of 1.3e-5, while the edge is 2.3e-3. Including all possible losses gives a fit which is basically as good as the one above: However, the parameters I got are a bit differentL: the surface losses are reduced to zero, while bulk dominates with a loss angle of 1.4e-4, and shear is not relevant. In conclusion, I think the only clear message is that the Q of our disks are indeed limited by the edge. The remaining differences are difficult to ascribe to a paritcular source. Since th disks are thin, I tend to ascribe them to the surface, which would imply that we are far from being able to see the bulk/shear losses. If I use only edge and surface losses, I found as expected that the polished main surfaces have much lower loss angle by a factor 200 or so. S1600439 has been measured as received (before annealing, elog 137) and after annealing (elog 144). Q values are significantly increased for almost all modes, see the plot below for a comparison. Only modes with low Q are not improved. The same set of samples described in the previous entry have been annealed at 500C for 9 hours. Then the loss angles have been measured again. The plot below shows the measured loss angle for all modes and all samples. After annealing all loss angles are significantly decreased, and they also show an increasing trend with frequency. As before, the blue points are the measurement points (averages of 8 ring-downs each) and the error bars are computed from the statistical error of the measurments. The red line shows the average of the loss angles for frequencies below 15 kHz, weigthed with the data points uncertainties. The red shaded area shows the 95% confidence interval of the mean. If we plot the frequency-averaged loss angle as a function of the serial number, we see that there isn't much of a spread in the values: We can again plot the loss angle as a function of the process variables.: This time I can't see much of a trend anywhere in those plots. Since the loss angles show a clear increasing trend with frequency, instead of computing the mean value, I fit each dataset with a linear dependency on the frequency. To improve the fit I restricted the computations only to frequencies below 12 kHz. The results are shown below The following plot shows the fitted loss angle at 1 kHz, as a function of the serial number. There is more spread in the results than when using the simple average: And again, the dependency of the loss angle at 1 kHz on the process parameters: The lowest loss angle is obtaine on sample S1600525, which was deposited without oxygen, low current and low voltage. But it's also the one sample that was deposited in a precedent separate run, and annealed twice at 500C. A set of substrates have been coated by the Colorado State University Fort Collins group, with ~500 nm tantala and various ion assist beam parameters. Here's a table summarizing the depositions parameter, by Le Yang substrate main ion source voltage / V main ion source current / mA main ion source Ar flow / sccm target oxygen flow / sccm assist ion source voltage / V assist ion source current / mA assist ion source gas/sccm thickness / nm abs / ppm notes Ar O2 s1600535 1250 600 18 49 100 12.5 0 541 7.2 s1600536 3.5 9 532 20.2 s1600537 6.5 6 534 damaged by holder s1600538 524 scratch s1600547 528 15.4 s1600532 200 518 17.8 s1600539 17.7 s1600533 539 11.6 s1600530 537 10.3 s1600550 519 19.9 s1600548 17.2 The plot below shows the measured loss angle for all modes of all samples, before annealing. The error bars for the datapoints are from the 95% confidence intervals computed from 8 measurements each. The red line is the average value over frequencies, and the shaded red area gives the 95% confidence interval of the mean value. The loss angle seems reasonably indipendent of frequency. The following pot then shows the averaged loss angle as a function of the serial number, for reference: Quoting Le Yang and Carmen Menoni The disks coated at Montreal are hold with three small clips. Therefore there are three small regions close to the edge that are not coated. See the picture below to see one of the samples with the clips. To check the effect of the clip fingerprints on the dilution factor, I set up a COMSOL simulation. For simplicity, I started with only two small clips as shown below: The result is that they have a very small effect. The first plot below compares the dilution factor (energy in the coating over total energy) with and without the fingerprints: Another way to look at it is given below: the plot shows the percentage difference in the computed dilution factor. It's always smaller than 1%, so completely neglegible. In conclusion: we don't need to model the clips. I ran a series of COMSOL simulations to compute the dilution factors of a coated disk with the dimensions we are currently using (75mm diameter, 1mm thick, 1um of coating). The mesh is generated as follows: The plots below shows the effect on the dilution factor convergence of the three parameters above. It turns out that the size of the surface trinagular mesh is the most relevant parameter, followed by hte number of layers in the coating. Instead, the number of layers in the substrate is not particularly relevant. Using the already installed high voltage feedthrough, I cabled one of the electrostatic actuators (1mm gap between electrodes) and installed it into the chamber. One of the electrodes is connected to the feedthrough cenral pin, the other is grounded on the bottom of the chamber. The electrostatic actuator is mounted at about 1 mm above the disk, see pictures. As a preliminary test, I checked that switching the HV amplifier on and off with about 1.5kV produces a visible motion (~2-3 mm) of the optical lever beam. So the actuator is working.. Installed the etched disk: using manually the centering ring allowed me to get the beam on the QPD. A couple of taps to the disk were enough to get the beam centered. Pump down started at 8:52am The pressure is at abour 3e-6 Torr. I centered the QPD and started an excitation. The HV amplifier manual states that the driver can source both positive and negative voltage, so this time I didn't add any offset, but simply drove with 1000 V peak to peak. After the excitation the QPD was slightly miscentered in X and I had to manually recenter it. Good data starting from PDT: 2016-09-20 16:38:09.330642 PDT UTC: 2016-09-20 23:38:09.330642 UTC GPS: 1158449906.330642 NOTE: it's a good idea to take a look at both the X and Y signals for each mode. Some of them look stronger in Y than in X. So far I only used X. New excitation (2000V) at about 8:06am. Had to recenter the QPD again after the excitation. Engaged the 500Hz high pass filter on the ESD filter bank. New excitation ended at 8:11am. Amplitude 1000 V. Recentered the QPD at 8:11:35am
https://nodus.ligo.caltech.edu:8081/CRIME_Lab/page2?sort=Subject&attach=0
CC-MAIN-2022-40
refinedweb
3,045
72.26
SpringSource Tool Suite 2.6.0 Released PLUS, Griffon 0.9.2 and a new, OSGi-based tutorial app. New OSGi-based Eclipse Tutorial App Bryan Hunt has announced plans for a new tutorial application to demonstrate the use of several Eclipse technologies, and current best practices for design, development, testing, deployment and more. The eTrack app will be based on OSGi, and will use HTTP for communication between client and server. The initial implementation will use EMF as a domain model, Restlet for the RESTful web services, and Jetty for the web container. There are also plans to use Gerrit for source control, and Tycho and Jenkins for build. Trinidad 1.1.0 Released Trinidad 1.1.0 has been released. With this release, hot deployment is now integrated in the core gem, and the JRuby runtime is shared with Jruby-Rack. Trinidad provides a library for running Rails and Rackup applications into an embedded Apache Tomcat. Vex 1.0.0 M6 Removes Experimental Multi-Page Editor The sixth milestone of Vex 1.0.0 has been released. Vex stands for Visual Editor for XML, and hides raw XML tags from the user, presenting them instead in a word processor-like interface. This release removes the experimental multi-page editor. “We have decided to remove it for now because we prefer quality to half finished features,” reads the announcement. Currently planned for future releases, are support for namespaces and XML schema. Sequoyah Moves to Tools Project As part of the previously-announced DSDP Restructuring process, the Sequoyah project for mobile developers has moved to the Tools project. This will affect and update the SVN repository, Bugzilla, IPLogs and general web resources. This should not affect Sequoyah users, beyond reconfiguring SVN access and using new download pages. STS 2.6.0 Adds 2.5.2.SR1 Updates Version 2.6.0 of the SpringSource Tool Suite has been announced. This release adds a new graphical editor for Spring Web Flow, and a Roo Plugin Manager. It also incorporates all the updates from 2.5.2.SR1, including Grails 1.3.7, Groovy 1.7.8 and Spring Roo 1.1.2. Griffon 0.9.2 Moves Build to Gradle Version 0.9.2 of Griffon has been announced. This is a maintenance release of Griffon 0.9, which moves the Griffon build from Ant to Gradle and updates the integration files for Eclipse and IDEA, so they conform to their latest conventions. Plugin dependencies that are declared with the Dependency DSL should now be fully honoured, and the logging DSL for execution during runtime is available during buildtime. Apache Jackrabbit 2.2.5 Released Apache Jackrabbit 2.2.5 has been released. Jackrabbit 2.2 is a fully compliant implementation of the Content Repository for Java Technology API 2.0, specified by JSR 283. This is a bug fix release for previous 2.2.x releases, and addresses namespace comparison and some JCA test failures. More information on the fixes, is available at the JIRA. Eclipse Juno? The votes are in for the name of the next Eclipse Simultaneous Release. Pending final approval, the name of the 2012 release will be Juno. Be the First to Comment!
https://jaxenter.com/springsource-tool-suite-2-6-0-released-103021.html
CC-MAIN-2018-17
refinedweb
537
60.21
GameFromScratch.com LibGDX has just added preliminary support for RoboVM, which is essentially a Java runtime for iOS among other things. Previously LibGDX required a Xamrin (300$) license if you wanted to target iOS, so this is a nice step. In their words::.: What’s currently missing in RoboVM: You can read the entire post here. It’s still pretty early, and as you can see there are still some issues, but its certainly a step in the right direction. News Java So, some time back I took a look at all the various different Lua game engines and at the time one of the biggest strikes against Corona compared to it's competition was it's price. However, about a month ago, Corona announced Starter Edition, a completely free ( non-trial ) version! So I decided to give Corona a closer look today and my god is it annoying the hell out of me! I am using Zero Brain studio and Sublime Text for development and both result in a simulator reload when you run your code, which in turn results in: Worse, the window doesn't even draw focus, so you have to tab over to it and click Continue before it will run the simulator. It may seem like a minor annoyance, but trust me, within about 10 minutes I was ready to smash my computer. The first time I thought, oh… that's why my app didn't load. The second I got a little annoyed… after the 10th time seeing that message… well, I wrote this post. Of course, I could just keep the simulator running, and instead of running from the editor, do a CMD+R to reload the app but this has a couple downsides. First, this means I need to keep the simulator running and it's a battery sucking application and I'm on an unplugged laptop ( and normally this is the case ). Second, well, it's an annoying process. Fortunately I found this thread: So they appear to be aware of the problem. That said, that post was dated April 19th, so I'm guessing this fix fell off the radar. Just a heads up if anyone at Corona Labs is listening, this may seem like a minor point, but its annoying enough for me to stop using your product! Little things that directly impact workflow… especially for no particularly good reason, they just have a way of getting under your skin! LUA In this day and age almost all graphics engines are behind the curtain based on 3D. It's just the way graphics hardware works, so we now deal with textures instead of pixels and sprites. At the end of the day, almost every single 3D game engine get a 2D sprite engine created on top off it, and now jMonkeyEngine is no exception with the release of The Sprite Project. In case you have never heard of it, jMonkeyEngine is a complete Java based 3D engine, that is quite mature ( version 3+, over a decade old! ) and completely open source. The Sprite Project is a 2D sprite engine built over top of it. Here is a sample application taken from the documentation(pdf link). package mygame; import com.jme3.app.SimpleApplication; public class Main extends SimpleApplication { static Main app; public static void main(String[] args) { app = new Main(); app.start(); } static SpriteEngine engine = new SpriteEngine(); @Override public void simpleInitApp() { Sprite sprite = new Sprite(“Textures / Sprite.png”, “Sprite 1”, assetManager, true, true, 9, 1, 0.15f, “Loop”, “Start”); SpriteLibrary.l_guiNode = guiNode; SpriteLibrary library = new SpriteLibrary(“Library 1”, false); library.addSprite(sprite); engine.addLibrary(library); } @Override public void simpleUpdate(float tpf) { engine.update(tpf); }} Pretty simple looking eh? So if you are looking for a 2D sprite library built on top of a great Java 3D engine, you need look no further. Engine 2D Java So a couple weeks back there was an announcement that the Turbulenz HTML5 game engine was being open sourced. It was one of those projects I had intended to check out when I got the time…. which I finally did. Turbulenz is an HTML5 game engine and platform. You can create and publish your game on Turbulenz and they take a 30% cut of sales ( this of course is their business model, and 30% is fast becoming the digital norm ). You can also publish to other sites ( your own, Facebook, Kongregate ) completely free. The most recent version of Turbulenz now offers TypeScript support. You need to sign up and verify your email then log in to the developer portal. There are downloads available for Windows, MacOS and LInux. Windows ships as a exe installer, while the other two ship as .run files. On Mac or Linux simply open a terminal window and chmod +x the file you downloaded, then execute it. Before you install you need to install the CG Toolkit! It is available from nVidia right here. With that done, the install is simply a series of yes/no questions. The script will however prompt for your admin password. I was running Snitch ( packet detector ) during the install and no outbound requests were made, so you should be safe entering it. Now that it is installed, you should see a file hierarchy like this: Samples are pretty impressive, there are dozens of them covering topics from physics, to video, particles, model loading and more. In the assets folder, there are a fair number of resources to get you started. They include models, shaders, materials, fonts, video etc. Perhaps most impressive though is the documentation. In the docs folder there is a pdf and html… now get this... That's the end of the table of contents, and yes… that is 949 pages! So, lets just say Turbulenze is well documented! You should be able to access the documentation online by clicking here. Open a Terminal and change directory to the SDK install location. In my case, installed using the defauls the directory is /Users/Mike/Turbulenz/SDK/0.25.1 Then type source env/bin/activate Now finally run it by typing ./start_local.sh Here is one of the samples, a 3D model sample, running in the browser. Please not, the choppiness is the results of the gif framerate, not the demo. It runs at least 30fps on my Macbook Air. We are going to create a "simple application" that displays a Hello World graphics on scene. We may be redefining the word "simple" in the process! First you start off creating a new project using the Turbulenz web interface ( ). Full instructions are in the documentation. Creating a new application Once your project is made you need to run a build process. makehtml --mode canvas-debug -t templates -t . -o HelloTurbulenz.html HelloTurbulenz.js This generates the HTML file ( HelloTurbulenz.html in this case ) for your project. Each time you change your source, you need to run this process again. I have to admit I found this annoying, as the lack of a build cycle is exactly what I like about HTML5 development in the first place! Anyways, next up we need to create a resource mapping file. You can't simply access files like "myImage.png", you need to create a mapping. Create a new file named mapping_table.json and add the following contents: { "version": 1.0, "urnmapping": { "textures/helloWorld.jpg": "helloWorld.jpg" }} This file basically says The file at "/textures/helloWorld.jpg" actually resides in the file "helloWorld.jpg". Once you have defined your mapping table, you need to add it to your application configuration in the Turbulenz web app! Configuring the mapping table You need to create a folder in your application directory named staticmax ( no idea why that name btw… ) and put your image there, I used the following image: Textures in Turbulenz need to be power of 2. This particular image is 512x256 and named helloWorld.jpg. Now let's take a look at the code: /*{{ javascript("jslib/draw2d.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("jslib/canvas.js") }}*/ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global RequestHandler: false */ /*global Canvas: false */ TurbulenzEngine.onload = function onloadFn() { var intervalID; var gd = TurbulenzEngine.createGraphicsDevice({}); var draw2D = Draw2D.create({graphicsDevice: gd}); var requestHandlerParameters = { }; var requestHandler = RequestHandler.create(requestHandlerParameters); var helloTextureLoading, helloTexture = null; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { helloTextureLoading = gd.createTexture({ src:mappingTable.getURL("textures/helloWorld.jpg"), mipmaps:true, onload: function(texture){ helloTexture = texture; } }); var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated); function tick() { gd.beginFrame(); draw2D.begin(); if(helloTexture !== null) draw2D.draw({ texture: helloTexture, sourceRectangle:[0,0,512,256], destinationRectangle:[0,0,512,256], origin:[0,0] }); draw2D.end(); gd.endFrame(); } intervalID = TurbulenzEngine.setInterval(tick, 1000/60); }; If you run that code, you see: One thing that needs to be looked at right away is the comments at the top of your code: These are build instructions for Turbulenz and are processed when you run makehtml. These are the dependencies of your application. You will spend some time adding and removing libraries to resolve various build snafus. The rest of the code is fairly straight forward, if a bit more involved than you would normally expect. If you are new to JavaScript asynchronous programming, following the programs execution might be a bit confusing. We start off creating a number of required Turbulenz subsystems. Then we define a method that will be called once the mapping table is loaded. Inside we create our texture, then when it's unload function is fired, we assign the results to our variable helloTexture. Next we create our game Session, this is where createMappingTable is actually called, leading to the above callback being fired. Next we create a function tick(), which is essentially our game loop. Each "loop" through the game loop ( or each time tick is called ) we call beginFrame() on the GraphicsDevice and begin() on our Draw2D object. If you have done any OpenGL programming, this will look immediately familiar. If our texture is loaded ( the joys of async processing… ) we draw our texture on screen. After we define our tick() function, we then set Turbulenz to call it every 60th of a second by calling setInterval. Of course, this is a very simple example, it doesn't use 95% of what Turbulenz has to offer, but does show you the workflow of working an Turbulenz, as well as what a simple application looks like. The framework itself is amazingly comprehensive and performs quite well on every browser I tested. On the other hand, it's complicated… sometimes needlessly so. This simple sample took me FARRRRRRRR too much time to figure out all the various hurdles ( adding assets, project layout, running and hosting applications, the compilation process, etc… ), but you only have to do that once. In all honesty, I spent about 3x longer on this than I expected to! Turbulenz has very good documentation, but you need to know what you are looking for and that is often the most difficult process. What I haven't shown today are the supporting tools that ship with Turbulenz, like the Collada -> JSON converters, nor the platform services that the Turbulenz server offers. If ease of use or simplicity is a priority for you, I highly suggest you look elsewhere ( three.js perhaps ). If you want to bundle your application for portables using PhoneGap, CocoonJS, etc… I think you are out of luck with Turbulenz. However if you want a complete and capable 3D HTML engine, with a complete asset pipeline and backend services and are willing to put up with the build process and the occasional bout of head scratching, Turbulenz is certainly worth checking out. Just advanced warning… it aint easy! Edit there is a nearly 2 hour getting started webcast I've embedded below Earlier this week Unity announced iOS, Android, WP8 and BB10 targeting will now be included in the base package. There was another small change that wasn't given the same exposure. You can now purchase Unity pro on a subscription basis. So, what does it cost and what do you get? In Unity's own words: Our new limited-time offer brings the power of Unity Pro to even more developers! It's too bad there is a 12 month minimum, as there would have been a heck of an opportunity here. Another thing to keep in mind, you need to get pro for each supported platform, so for example if you wanted to target iOS, Android and PC/Web at pro level that would cost $225/month. In the end I suppose it comes down to how often Unity release new versions. By their prior release schedule, if you purchased early in 3.x's life cycle, these prices would be worse. Right now for example, PRO + iOS + Android would cost $4,500 to buy. Via subscription it would be 2700$ a year. So basically, if a new version ( Unity 5 ) is released within 2 years, subscription is a good deal or break even at worse, otherwise outright purchase is your better road. Do I expect to see Unity 5 within 2 years? My crystal ball says yes. What exactly do you get with pro over basic anyways? I suppose that is the ultimate question, now that Basic is free, what do you get for going pro anyways? Well the full feature matrix is available here. The key advantages ( at least imho ) are: So, if you are creating a cutting edge FPS, pro is almost a must, at least if you want post DX9 fidelity graphics. If you are creating a puzzle game or less graphically intensive game, almost none of these features is going to be important to you, except perhaps the exe stripping. Anyways, you can purchase Unity via subscription right here. Unity
http://www.gamefromscratch.com/2013/05/default.aspx
CC-MAIN-2018-43
refinedweb
2,322
64.41
NEED_function NEED_function_GLOBAL NEED_variable NEED_variable_GLOBAL DPPP_NAMESPACE ppport.h - Perl/Pollution/Portability version __VERSION__ This version of ppport.h is designed to support operation with Perl installations back to __MIN_PERL__, and has been tested up to __MAX_PERL__. Display a brief usage summary. Display the version of ppport.h. If this option is given, a single patch file will be created if any changes are suggested. This requires a working diff program to be installed on your system.. Manually set the diff program and options to use. The default is to use Text::Diff, when installed, and output unified context diffs. Tell ppport.h to check for compatibility with the given Perl version. The default is to check for compatibility with Perl version __MIN_PERL__. You can use this option to reduce the output of ppport.h if you intend to be backward compatible only down to a certain Perl version. Usually, ppport.h will detect C++ style comments and replace them with C style comments for portability reasons. Using this option instructs ppport.h to leave C++ comments untouched. Be quiet. Don't print anything except fatal errors. Don't output any diagnostic messages. Only portability alerts will be printed. Don't output any hints. Hints often contain useful portability notes. Warnings will still be displayed. Don't suggest any changes. Only give diagnostic output and hints unless these are also deactivated. Don't filter the list of input files. By default, files not looking like source code (i.e. not *.xs, *.c, *.cc, *.cpp or *.h) are skipped.. Lists the API elements for which compatibility is provided by ppport.h. Also lists if it must be explicitly requested, if it has dependencies, and if there are hints or warnings for it. Lists the API elements that are known not to be supported by ppport.h and below which version of Perl they probably won't be available or work. Show portability information for API elements matching name. If name is surrounded by slashes, it is interpreted as a regular expression. In order for a Perl extension (XS) module to be as portable as possible across differing versions of Perl itself, certain steps need to be taken. perl ppport.h --list-provided to see which API elements are provided by ppport.h. PL_prefix is deprecated. Also, some API functions used to have a perl_prefix. Using this form is also deprecated. You can safely use the supported API, as ppport.h will provide wrappers for older Perl versions. #defines in your source code before the inclusion of ppport.h. These functions or variables will be marked explicit in the list shown by --list-provided. Depending on whether you module has a single or multiple files that use such functions or variables, you want either static or global variants. For a static function. __EXPLICIT_API__ To avoid namespace conflicts, you can change the namespace of the explicitly exported functions / variables using the DPPP_NAMESPACE macro. Just #define the: For the latest version of this code, please get the Devel::PPPort module from CPAN. Version 3.x, Copyright (c) 2004-2009,.
http://search.cpan.org/~mhx/Devel-PPPort-3.19/parts/inc/ppphdoc
crawl-002
refinedweb
513
61.02
. Kotlin to support package protected. I want to state that it provides one level of protection within the same package. Internal is broader above the package visibility. Hi, Is there any chance to rethink this decision and, hopefully, have package visibility in kt 1.2.x? Frankly whenever I have to isolate some classes internals in the same package I really misses the way scala does this (private[model] def doX {}). Of course scala is more powerful in this matter, but for me, package visibility would be a nice addition to kotlin. Apart from this, I really enjoy developing with kotlin. Thank you. Hi, I created account only to comment and say: You are wrong. Guys who developed JAVA language has great Idea to make package scope as a default scope (without keyword). Some devs has hard time to understand of true potential of Package scope and even if I explain to You you will probably not get it. But I will try I have one small application with rules: - app has 3 modules/packages: user management, product management, shop - user module does not see any class of product module because it doesn’t need to. - product module does not see any interiors of user module because doesn’t need to. - shop module use published iterfaces/facades (public class (only one per module and dtos) ) of user and product module and do not see their interiors because it doesn’t need to. the whole code is encapsulated on each package levels. If my junior dev colleague will change something in product module/package I’m sure that he will not break whole application and what’s more important I have better control of dependencies between modules. It’s architected that way because each module can be moved to micro-services in future or moved “somewhere” (we do not know that yet) and it is easy because they all has only one point of access for each module (even Controller class is package scope). Using “internal” I would have to create always 2 modules for dto’s and for service for each module/package and there would be additional configuration on my head. It would be great assets to developers if it would be default scope. There is great presentation of this and package scope: Hi, I was discussing about this architectural decision on slack channel, and I was told this package visibility is going to be discussed again in one of the coming, say, kotlin architecture meetings. Probably they will be reconsider their initial decision and add package as a visibility modifier. The Jetbrains Team has the excellent reputation to listen to their users, and if our request seems to make sense to their architects and decision makers they will certainly implement this. This responsiveness to the user requests makes, after all, their products top-notch ones. Kind regards. Some good arguments have been made for package level encapsulation however, my issue with having only the package keyword and no internal keyword is, package often leads to cluttered packages because a library or application needs/wants to have an internal object shared across packages without exposing it to an outside developer. An example would sharing a bearer token in a client side library for Android, outside developers shouldn’t see it but if the library supported different feature sets that used that token object then why should the developer be forced to put those different feature sets into a single package and/or expose that token outside of the library? I wish Oracle would enforce internal encapsulation but I’m actually encouraged that Kotlin added it, so much so I started looking at doing backend development with it and I am watching Kotlin Native closely. If internal went way I would probably start to lose interest in Kotlin because moving on from some common Java pitfalls is important and seeing Kotlin cave to the Java community would signal to me that we will just end up with a slightly less verbose Java without any of the benefits from using a modern language. I’m not saying don’t add package and it doesn’t have a place. What I’m saying is whatever is decided, the internal keyword should stay. I agree with you. And also removing the internal keyword would be a breaking change and therefor I am pretty sure that it wont happen. Still I would love to see a package private access modifier added. A common Dependency Injection pattern is to have a package-private class injected into a public class. The Kotlin file-private option doesn’t work in that case because the DI framework can’t construct the file-private class. I know about the common construct, that doesn’t mean it is a good idea. The main reason for the package private is to allow access to the test suite. It is a test suite, there is nothing against using a little reflection (and setaccessible) to solve the test suite problem. In the production code you then have holes you don’t need. From my perspective an internal declaration is not really any bigger a hole than a package private declaration, except perhaps slightly in JDK9+ with modules where packages are sealed so clients cannot extend packages (to circumvent package private) and internal does the same thing at earlier api levels. If you want to do dependency injection, you have something that does the “creation” of the objects. This thing can provide anonymous classes or anything (as long as they implement the correct API) - and perhaps the classes should be private to the injector to prevent clients from using hidden API. and perhaps the classes should be private to the injector That would be a radical change and would defeat the purpose of having “friend declaration” code organized together. This continues to be my main frustration with Kotlin, they took away a simple encapsulation tool and didn’t give us a replacement besides telling us either that encapsulation is useless if it’s not 100% foolproof, or that we need to break everything up into countless, much heavier weight, acyclic-ly dependent little “modules”.
https://discuss.kotlinlang.org/t/kotlin-to-support-package-protected-visibility/1544?page=2
CC-MAIN-2018-34
refinedweb
1,030
55.88
On Wed, Jun 25, 2003 at 03:08:00PM +0000, Hedr at intarweb.us wrote: > Hi Pythonians, > > The underlying snippet is copied from minidom.py which is in the XML > package which I am currently using. Cloning nodes seem to take a > considerable amount of time, hence I went looking in the code whether > optimizations could be made. The following snippet contains a for > loop: > > def cloneNode(self, deep): > clone = Node.cloneNode(self, deep) > clone._attrs = {} > clone._attrsNS = {} > for attr in self._attrs.values(): > node = attr.cloneNode(1) > clone._attrs[node.name] = node > clone._attrsNS[(node.namespaceURI, node.localName)] = node > node.ownerElement = clone > return clone Using "itervalues" instead of "values" may produce some minor improvement. values() creates a new list object containing references to all the values in the dictionary, while itervalues() only creates a very light-weight iterator. Jp -- Seduced, shaggy Samson snored. She scissored short. Sorely shorn, Soon shackled slave, Samson sighed, Silently scheming, Sightlessly seeking Some savage, spectacular suicide. -- Stanislaw Lem, "Cyberiad"
https://mail.python.org/pipermail/python-list/2003-June/219213.html
CC-MAIN-2017-04
refinedweb
165
53.98
14,77 Related Items Succeeded by: Nassau County star Full Text .."'. .L' .. ,. .... ., .g" -, i' ) '. .,. . .1 1LF I 1 ( 5Itidb d Ilirrior. ' ., VOL. ir. FERN ANDlN A FLA. SATURDAY, AUGUST U, 1880. NO. i;>(G.: : l _ . IMl'OllT.IXT TO 1.'LOll11J.I I work on ..Iu1t I, ISMI.( I is $;.IICKI.( '. and, for the 'I 'Ihe thairman! now looked around I I.'ar that Major \\ 1 Turner, of We are indebteil to our enterprising cottimponuy Ibl'lll"l'1I1' ending j I June :'lo. Iss: 111I appropiiafiou for Colonel lli'sbee. who had taken) a'1\-III1.1 IMS rented !'\nly 1'l'l'S of the of ZIi',(N0' is a kcd l to 1 be- applied\ (to Mr. Ledwith's I plantation on Manatee of the length of t\'rHt ( the Savannah tVoM, for the fo ii- age ! of the should that I is the completion jellies J'ottoti( (' ' I to parlies1io: going lowing cop of(;ell. (i11ntorl8rei'ent report plan finally\I \\'I1ll1plt'I., otherwise to the ex- to seek the( relit a WIIl.ll1IIlrlll.tI.. I. Alttr: the Iolar.! HIIII'!" ( the subject: of the harbor and I rinrill1l'roVl'lll'lItllll l''Utillll'such: plan as the :Seenttary: of H short hunt 11 r. 11i..1( 51'1' \\1I"lr'l'l'ttll'l, whodesiied I ors npoit) ) he xcgetahle hushus,*.-TJio l 1lIU' upon : Florida., Our readc will War authori/cs or directs : 1 topxttise: himself: as it walate andvery I'' \ears. The (' : \ county ul\cs a poplliatol of fi/MiO; , < , j observe. that the Kn-jineer lcpaitment) :lI..k'l I wand but waited l for some/ one to ay not in (' ,' !' of fifty per 1''It on (lie ei; !us lor liberal appropriation to continue I i the t ; Tin: Jrli'UIIl.111l:1'1.\'(;. "C(:ioon," whidi, alter pause, produced, (the ; low has reei : i in. The 1"llutali"l( of Til in pa 1 bwf-fo, work at this point : I Pursuant to call as announced< \ a Republican mass nievtiug; assembled than lieu, Lcdwith's, vvas a .IIIIh <-f his ntl'ndt',185 a 1 I ( -The colored free sdmol, .I..1, W, l ,',.' IMUKOMMt sor.M THE, FLOBIa1.tYn.,6nUUL KNTKVMK: TO (T\lutltl.\-rJI:\. at Lyceum Hall Dr !Pope, pusideiit of the I' weak arguments, though 1Ia114''pv'l'iallt awl :I aic- anxious ( teacher, lo c'll1a'ot! Monday. with an ) ( ;arlh.I.I-1 ( 'lub\ with otlleers and can be kept in ( \\lticli we learn Judge 'OIlIlWI' , alluding, to the eiiminal farm 11'01 issii( tlieMir. cmphatiiIn fly\ the act approved June 14, : I , . appropriation, fur this work, amounting t t0ooo 10r tll'III"'I'* of (the "duh. ueeupie'l\ the rosttum, ing plan he opened the \ ial* of his wrath : will 1'1' ";:\ : I Crane, umnty :supe-iintciidcnt, who r, f :;{ ), was made. while the 1""ly..f the hall w;a-tilled with anauiliemi1 I upon the l(\"slush and I acknowledged;: that I us we have !('( : was alike ere-difahlo to teacher Dining; the present! fiscal year it i is 1'1'0- fiftciii-MXttcuth l ..whom wereeoloied "WP all are liable to be c'oiivu'tc'd of dime," se'nte-d Us bj Ir-Ielt, especially in the elementary posed, (to heiiiii! woikontheprojet' : \ uhiiiittci a statement\ whidi M'tmcd to nnct\ with the. eoitnty. 'Fhicy , l fIr the emiineer' in th.irgc1' June :'Jn. l It-jll.! people". u])pio\al of his, hearer lie next: devoted : 1' he-s.TrHinnc., , l consisting of two low jettiesbuilt: mainly 01'( Dr. I'upeintrii'lnievlku! LcHhvith. Itc)1uh- ome time to mathematical ('alllll:1llol1'1.! of ( "/ mr Jinn for. ,'4 tip-rap stone, renting I i on a foundation III' limn candidate, for !Lieutenant-Jovernor* ; which his au'lilurcI8s\ piofoundly' i ignorant i i 'Ihe( tint. tigt 'I ) months the merchants . mattress of logs, or logs; and,l biiish, :tal'lillg' who cntcitaiucd audience for more (than Then on the heresy of Mate: !m hl. lit }!9,;0 PIT: I : )th.IIti lrc>m the shores on opposite !sides of (thEntrance I and! the glory; of the Nation (big NI) and IIot' Jacksonville West have paid out $111."I> t.1: for : and, extending seaward across the an l hour and I a half; with a desultory! harangue denunciation the !Democrats gmeralh.Hidiiuled '.-The fay says that ',' Mllla,1 of, bar, so that:( the outer ends will be parallel lie began' by exposing his !soirow ( the 1 liar of bajonet: rule at the i 1'1'11' wi"- ( ( the mainland<<1 are :liippei i | to tach other, and :aoou to .'{.."lOO( lect apart at the ahseme of Dr.) Ceniover, but st.fte-d: polls; only flee\ and fair election' wanttd. I ddic-atc and I 11'01 lli f The two jetties are expe-cte-d to mainta.n: i II and the 1'. :S. !soldier I is thyre to teach the beating I there every ten days.-Km of! .: low watcrdepth of :Lti to :21 I lett where tie that the Doctor was North on a mission! in people, what Republican: Construction 01| I : :Il.tllaillaillrul .depthari: Irom 111 1 } to 1:1 1: which his audience was elccply interested! : ;e're' amt lair: I is. Claimed th.tk the I'i\'(-..i111nt can bee'urtd 1'titnain. lect. Their estimated cost N :j.j.n7IOJ.J.:: : ;\ I If as he was then Irving to procure money and) 'i ft compelled I to cnl'tret'thrhit's t a 11<11'\ :WIII'I1 HI'"I our thh' ( ) future of this along the 'St. only a !span\ jetty he const rue ted on the men to pu-h the Rcpuhliean, canvass in Florida. to do !so With all thl'III'\Iill1t'I': \ ( within his to( I tI he wealth mid the"l.'tOI counties in ' south side, a ili.mnel (10 to 17 let would he< \ leach ; for example, should a vessel( from \n'r adjacent p maintained, and the coat of the work woultbe He s.iid many questions: had, been an illfft.lport attempt to forte theqtiaian- : ( 'i'lor can hardly be e..tlltl.1 'l'l i be about*I.OOO.lKio.) ) naked'ho and what was Dr. ('<>novcr, anyway title of our port, the 1'resiulentsliunld enforce i'nl't'L1'I'I'IX : ( make n wondeifnl, I dlall; '. During The amount available l for this work is It i istitlietoeeast'thesetuestiousaut11{ I the national I quarantine) law at all hazards ( ( ,' de-cade the cropill he 1m- -.)II.I"MI), and an appropriation of $100,0005( ) ) ) ill for, our protection (did not know the tI.'II-' luh.hlt',111 I' ollgl' asked for the fiscal: \ year'l'arl'IIIiIl'III1l'IIIls) : ) : hieketujgs, and )know t that Dr. Conover was genius "1'111111.1111' was trespassing( upon, nor :lanil tor; -e, and the countryill b'otll'ri'h. lo he npblied to the prosecution of the leasemtlyol t an ardent Republican\ and! iMiididatc forlovcrnor whose' tlll'lI'I'e being pinched by his parallel t'I,1 by (them !: '" and conditional I interests i will keep the projects named leaving tin ( ; on the Republican til'kl'tllIIl, for !). In alluding to ctntrali/ation one oldinured t the nice. of I i: : with the inrrea(' of the land uiid the 'question lit'a further extension( open li,1' thought it was :somethingto him he expccte-devery\ \otl.11I that audience gentleman Total white \ ( ( ( ( : 1'lt of rutnnu'rce. The young 1'1 consideration.IMI'IIOVINO . future 1 and! ) Jl'l. lie arrajeti (the Democraticparty for the beopposed\ 1'1'111111'1:1"11,111 Tit II I.o1',1\ | !) of (he presentill'' in and reap : I "Yes. Restoring: the : ! Tin i'"'II.: ',\sstol: )IErtvIIS!: I HtHVU. : : tl'\ N t.XPINVTor .\-in I"T. .loIIS'" 1 peace and prosperity of the1 State "inee that) power, xv ill l hiring hack: the tnuntry I to (the .it 1 I ( of the lul'lIllIof the past. Palace a. continuing this improv emeiit; the ,111approved )arty has be-c-u in power. Riduulcd: [1"(' I pristine purity of (the days Washington Majority grt'gatr of I I I t icsidcne-es will hs l, 1111'01101 on the St.I , in Theio is not Republican \ June If", HHI( appropriated I I the idea of rc-diutioii of taxation ; states (that it and ,1lk.OII.: N whit( ; military ) eo.l.i, .1 I'l Afore.Isetunbua ':- River as they now an on (the Hud (the whole Nation (big; ) want" Mini of $7'XMJ.' The sums previously I appropriatcd 'uicd ,by, ledueing the ilifni of I is 1 i I was juoe per illt'r'Itl'l at (the1 polls but dt'maudstha't I sixty millions of our home raceill lor this work tomprise :tj: ,IIOO) hctween - 18'S: and lSJ: expended! mostly' III poor but honest! jurors and\ witnesses from .: they !'houlll be* lucre to eiitoiie\ (the freedom be largely! ( ih an immigration and muteiial. fur the opening KingsleyNCut and (1111I111:<011'11 Cut; :$|I.I:! to l.onptrday) \ and, aliolition of mileage of th hllllt Pronounced 1 fulsome ilic-ation "a t \! development of the :-itlll'. (ienend the the1 pceilesshe ( spotless -liHH( ( by: act approved June :i'l:I, ls,74, of /( to thi-m. Hold* up to public scorn nu.1iguumittytheicgihiitnrs i eulogy the on scholar, claim few while / :-IIllhut (the possibilities' thiStute: ; whlJiVi.7.'iO: ;: '; 1 were ele\oted to a !'oUI''l'r,11I,1 1ll'1alrlot .illIlt ot the balance: dredging; ; aiiel.7,000( bact > i : l'"rIIl1lIn"1I1'hII I far him. lowc\'I (' as a t the1 c-\i-c-s-t e if ( I ) ; p1'I'Jt, 111,1 (that the futll'! WOIII bring t of Mare.lt.a, Is70! also devoted to dredging. law, and make1 their own fur itttm $(500( bur," II', 'OIO\'l'l' lame in for no flattery; to, gIn :: ( ( :U.lllkt' Florida one of the( ; he needednone ; !During the last fiscal year dieelgimiwas ,,! and mile-age. Next assaults the present administration I fl"1 CI! liishee.Ce Colonel's suppose bauds I Ucneral ''a lair. ('oUllt' I :States: III the Ititiu t. (' ' done .at the contluencc ;of this: insidipassage : for increasing the representation fJI the 1 both No likely (to I eoi 1 ,I : cvcrjthlng( hut llllrut\'I.\. Arthur( was: ignoicel by speakers. IJn WIIII tIl' (:'sister's; ( !'l'ek) with the :-\t\ John'sMiser : 1 of certain Democraticcounties andicducing allusion to the ( 1H'<<1 gut nent was ideas.TIMIIHI. will eomewhen will have 'Ili1I ( we a wealthy at (Cow Rank, in sister i (Creek, nearIv \ , 1. two miles! fiom the St. John's River; tilOeiuulgee ; that of one Republican ('1111 Illy. i dl'IIHIIH''I':,: t,. I !: point illawl'lt:: Creek, nine mile-: (''laimed i I that I )p ipular clamor 'fon-e-el I the Democrats I spc'i'c'lies weak were and I \ (1 Il'\olaltlt's. 'Theywere .of, 1I'li in the world-The ('('11"11 : ('routtit.John'sRiver. : : Illm'I (i'1111' : at Ieci\\'aterPuiut;; t ; to restore to witnesses and I (iiinni- I : mileage : Being iltr(>d 1 out alter readinu :31st:| I, we of informs us that a near the last point named I, and at 11.11'1 +' .111> Ialalkl PI'lIl ; 'IIII'!! Cut in :Saw pit Creek. The total quantity j jurors. I let d barges: I the l DC) 'moc'rats v\'ith taking I ,1 some re'' l>y )tlr. Kallard I, eulnrtrl'the e-erning! the t h is within, her ('olortlll 1,:">0 in- j dredged: at all the leK.dities fumed l undue advantage of those! in their pern er and nnv1ingadjourued without motionlielol.TKK.] : The arrivals : \ : I As this "llltl'r has wlll'Ii'll amounts to I :'W,7'i.'J';: cubic yards, uud tie-a for this out the vials of his horror less jMuirs I ,' of a larger to distant ble ehanneN; were establisheil 1 not than brigs: 1111.11 !'- : dcpaittirc 1111111".1' live feet at mean low water jit any point, and upon the Demoe-iats'heads. Dwells) extensively 7'11 SOUTH ,AMKUIC.IX WAn the same! ; "than ever pefore, we take it that our I varying in width from twenty-live to sixtyfeet. on the farming-out I'lallofl'rllllinal:, ; 1'A:.\MA, July :!-TII Chilian tratispott schooners\, I : (' population would amount to I.I'M, ,.A the vocabulary, of the English: : language fails: \urlla".llt\ II' illl\of the pe't's.J inn port h'" last (-('11"1' put Pa'-ilka'! .I'IWI at .irtl p, The previous' depths were less than font (to give words Mittlcient force by which ('lt war i tlll1t'r Wili IIIIWI UI fV-e-t. by tornado in (,'ullac; Hay July :'J. The were as l li.l"w: : !1 slmwsan lncroi.se about seven him- fiscal It is the speaker could t'xprst his ju-t horror fair 1 caused excitement; in Lima null The late rii started the During the present year pro- great feet ; sawn,. : ; : : us. growth 'J! nil either to( the existing and indignation at such a plan but offers much glorification the( Peruvians enlarge |l' passage ; IIIIII (KN) supiTlicial I !; orange (' proven. I: is astonishing law or to begin opening: a less crooked passage lilt l'eml'lr for what he claims as an unmitigated The plan adoptee I was the flluwllg'IIoI: related . elsewhere, as shall be thought best after full j : by : cnrrrsisnulclit II 11' mm distributed Tribune'e fend out young shoots, 111! I is fo en- I evil leaves the inipie-s .ion his " e-xamination has been" made, and the appropriation ; upon\ 11,,nd. Ing' to the hopeful A'rl\'r whose of $10,000( asked will I be, applied to I! hearersthat criminals should,I be turned see .\ Peruvian; ofllter took an ollhwj.v fruit JcIII, now Is always iitdiant with'the prospect of the execution of the plan that maybe adopted. I II to prey upon society, rather than made to boat, put a torpolo in the bottom, ;. over ( for all his toil and, patient ., I \. It is understood that arrangeincnts work be'cause of their evil deeds ; dte-d great this lie plat-eel a lill-l' I",ttutit testing on 11.1Ih'l.thll; r'\\'II,1 making to place Savannah rernandiiia I springs kept down bv the w'iglt of (the cargo art ruling at !> .; .-'t' I'al that the farmers in in greatly: improved rnilrOllh'OUllIl\lIIi1'atill1l I ilifK'rcncc mortality under the Republicanthan He then loaded{ it a very choiceassortments i Yolk and I ) I !( ( tl'.tollave( put in large sweet potato with Jacksonville\ the centre of trade and the lease: plan' ; turns upon{ his: audience ( of eainotei, vuciis thiriiuovns, I Itoston! coast: 1 This N I sensible idea and that travel o'i! the tit John's' !River so that alter now and tires this assertion at them : Any I, granadill.is! fovv'l.s, rl'l'l vrgctahlcsete.clc.: ( ; I 'll' the has been and tuwill ; the Furtlyii-: t II'I(' to man that will ( I bar at the mouth of that river Republican whootcs (the Democratic) ticket! ; blotkadingsquadron : C Ih'llIj any I i improved,I alter the plan mently approved, Ceture.1arlight, set it atlrlft AH standard ; Ile : <> < Wo always .fed relieved when we ,. .. .IIg".r.lInl between these cities in this canvass, I is retrcant to his trust and day long the 1 I'lunch floated the | I. freight alllnt, Illt lings.: that there is to( he u goodly jiotnto, will have t'llOirc. 1 between transit by rail on I u traitor to his party' ; makes a bid for ignorant (Chilians could{ not see it, until about 3 Iul.al I .t i moderately quick schedule! and transit bvea votes by pandering to leniency, tocriminals. it'tlok in the evening. fcariiiL' it would fiI. present from : ( I -The Had 11101It'I'lt.f the death and, river on coasting steamers. Until Dwells the of the Into neutral hands illl. J' hunt I was t'lIt in I'niteil / ) I n.: I Hart, of this place, east C VIOOII I he :St. John's'' bar is greatly improved this IIMIII iniquity out to 1'1'1111 it 11I1'k. Tln Lm vns'loiug purnttst' ( ) .lr quiet dty. She was member of C inland diannel should, in the opinion of the proposition' \ before the last legislature to ujfjHiiiit duty, from .111' making in the timber Chiirdi, nail was ever t e'liginner; becarefully kept open. After that electors! for !President and Vi'e-Pre i- toward the l'ntll11,1:, caught: Ipl"'OI'11 Ltlt'1I1 its comparative\ imj>ortanee will perhaps be dent fails to cite, however that other Mate*! 1 sight of the launch, and at once turned! to wi no doubt ( calls of dIIl)'. The needy W.f' illl'ollitll'rable.1IIflUlit available for this ; it. Seeing this, the boat from shore j'I'I I"I., .' sent away 11'01 her door unprovided} wart ' work. ..rulI, 11'1110. $7n07.ii2.( ) : .\I'proprIu.lifl1llLkl whole Legislatures proposed' 1 filename thing.Works hasty l'lrt, The IAHI lowered two 1 She was cultivated lady, and was the t" for the ti'al"l'ar. ending June ] UJMIII the prejudicwand, feelings: ol boats to 1''cl i il the l prize) ,and( it i was brought of 1 the domestic t tirde. She will be ;!O. IS.NI. $10.000.. the disc of the 11t The his audience on the H'hool question; append) ) ulul.II', barge ( 11110 orange the in the I Her life was always bright weight Jolix'h \1 promising. fl"I'11 UU'ILI\"XlIIT. RIVER, EL\ to them to know if they are willing to allow lallll1 rr"\ Its net approved June 30, 18fsrt! the first I their ddldren debarred tin blessing of tine was w dfoluuiievlthe ith the torjieslo wasse machinery't in in 1..II.t'a ino- growing I smiles of joy. Tlie old and tlU .for the fn'I'III.1 felt the her affable appropriation permanent improvement I a few '' dUHI Ir ilisposl. education as under Ut'III'l'ralic udmini- meutG11Jh pounds of dynamite were exploded, II 'a" of the liar at thc mouth of this river and the L almost lifted 1 out of the of Florida :trl'k,1 with the most pain- :: .I..I \\': made, amounting to 12: >,(>oo. There I t rat ion they have little hope) of help.) J'a'i crop water. Thc described 1 t those I vvhcivveie was taken to ll. ,toii, where (the 1t ton of ( J".tt had{ been previously ex|>ciidtd here during I Claims that he has tried to falily I t'1..t.I"( bruit bleMs I crop I I + the tm fiscal yiars: preceiling June :JiO, 1$7U I. the I ; Ids antic' aid wus had, hut all proved of no , : state hi* arguments; before uudieiue. interest 1'1'01 Ihe shore, WUN awful in the ex.I - I the sum of i'oi7,4i' 3S |u dredging un the '" ", r .' i ixcuss! ; Radical eorruiton' by I I treme. Hvery; house in ('ulhU vvasbhaktn come : ( 1tfM liar and $:?.).: :! 75 in urveying the bar and , to its foundations, and in the every ship bay Jie- richest ( I nuking the requisite oUservulioiis for U newprojitt stating that ill nil enterprises) errors an,1i hivere I II'i though an earthquake had sj-e-nt statehaving se. : (ky\1 IiORKOR.-l..indun.Vuig, s. i mistake occur and that the corruption! and its fury beneath them. The fates J t During the present fiscal year it is proHistnl ship Hi"| 1 Renter's : from Aden, rejxirts{ , (ve rythiiig t.Ir:1 larecnies of the early must !IIC chifxeil 1 under jieartil II" if envelu'.t'd' in one 11.\0.. of I ;; the l to begin work on new plan of improvement ; ( which rcsol ve-cl 1 itself in to dense black nioke.Whjn the from Sinyujiore, I described in a letter of the engineer head of tni tnkti and fimrt. Democratic unspention use n saw- tlC "t"II'r.i"I. this she xccmiHl to oil' (iu.irdanl the Sth with ftW( dl'Hr"l away hit ions growth (:( on -- \ in charge, dated June :-\0\ 1S79! con- of)part of the taxes sat only a ruse | t : 'i..ting of two low jetties, built of riprap have suffered, but suddenly I ) she wa. 11- I ( 'fur Je bid 11llfaCtllrt'l to cutch the unwary Makes' a for the certed to sink at the sti-in'while her bow I j stare, resting on U foundation platform of the his wife, lh chief 1 1L Captain, v\\- I'' logs, and the improvemeut under certain patronage of the k fny-hiinUl sons of toil ; went high in the air, and the hfi disappear I' We are 1 chief and sixteen : i.onditions of the river between the \bar and carefully kept his own tender, JitsiUe )palms ed I forever. of Punta Rassu 11.t'r. an engineer While all this going on, the MUHCH who uml brought tu r w. were J.k".1 Jacksonville. The extimatetl frost of the from the gaze of his audit'me. Luysat Democratic Kuatliulti and the llmucar in their i"iHt\ II' for the ul project for a low water channel depth of 15 << were act I by the Ih'umcr11" .\ to door! the liuk of emigration and 'union us 1 No-itioii.s, eight miles distant tie shipments .l"lttcI I.) 111 feet on the bar is $1,43>,4OU, and for "tIC .. " .u channel depth of l.lto) 13 feet at low capital flowing into our Mate" ; were lUpublicans too far. tiff to render any assistance to 'I I 1st day of April | 1 | ( ) front mid A.ll'l crew tuiyn were: ilrowneil Kpwunls by of their touch of them water, $NX,0, <)). in power emigrants would cn>wd in a unhappy t'lUIIC or as head ; of tlll' I l'U.IIJt'N of the on tln- 1 The amount available for this were left struggling in the water. The Units Ih'uulrJIllA. work JulyI "erfctt flmMi-tide and calitul'uul,1 l> cattle suit off ( was I I, iryuj, is $125,000, and for the tiMial year j go t-g- of the Thetu, J'C"t.Utll. Drrrn ali .js (uur.llla. vll ending June :iU, 18 (2.: an appropriation of ging for investments, HO great would |he the (iriLaldi were and proceedeil my books by from. il IIMlre the Jedduh TIle Jnl l i to Steum < >liij> *4oo,000 >* asked, which will he applied to influx of money. Fill lies Momeuf(rarneld'a to the ncene of tlc (the 1st of '. She luJalllr ( the of the work the least The two tnot.lultllhll'I ( urrll.lu't'II'1! I) was UUILrm. on jirosttntion! thunder about the "|Kjwer of an i Ilea. Denies bug .' tfit *hipi>ed ( was a screw steamer , ,' .etly of the foretfoing 1'"ljel1..lea\'InJ{ the tl'] ISTH..IIS! tl. 2.t " ,fitension of the plan beyond that point a that Jk-inocraU tolerate free nxxxh in IffCfte t.I' or C.ur. and the (lan'viUi six, these there \\' net t/unat. of tJJ and grow 1/Hl./ iiutiun fur future consideration.IMPROVEMENT Boiue part of the t'ilukawl d.tlarwl) that IrtIn in all, of wlll it is l shipped' I <(, .Augunt It, A litpatcli from | to Kcutcr'n Telegram ' probable . At IIP would not dare his in many t 1')) 11'n ree-eivcd 1 1 (01111) nay t-jn-eth OF VOLl'll8, ft*, repeat Home The' only ufllu-rs sitveil are the f"11 I, J.t ih, wliiih aban- lIrillu'tJ j Hy act approved June 14, l&so, the first sections of the State, but failed to mention ,' (wounded I), the doctor 1.nIt last diJ. not founder as lie n''frh'tl| She .I',4 i appropriation of $.1ouO, was made fur this where these heinous localities are. Ljud and one engine which he > up and towed 1 IIIl .Aden lust Iwork. The net athorizen the Stt-retary of (the 1'arty of moral ideas and enveytthe The explosion oc'urrcd very deme to the quality He. I by Ioh'lwr ,'inltiuir. (War to make budi cjxt-ial toiitract for thepro anehorageof lt'utralllualnu{ and (bedisaNter , idea to Ids audience that restoration of Radical I t.. and juicy, and | >>c I ( j ', I uncut best promote the illtt'rt'lotli of the govfrrnment. << I rule in Florida foreshadow* the milieuium. of the-mv The IMlt n-x'inl.Ie.1' the ur.l. IUIlI not (' H.-Ir The hUII.\-\tllltu.: nt'lria. t I lIe then reads in a moot expressivemanlier I nary frulttf.whidi ml ht accidentally' I market*. 14uii' I i niDrning, iHMuiiiatetl (' o'IV'I-An- The normal dtpth ('PC water ut Vuluxia Bart adrift and to . the quotations f from (iarticld'a. New I.rlktn not flIt wa. allowed lo rin i I u( Itibb' nuinty. for . l y-H. variation | \turf [in about live feet, fiibjitt to j.ntduitdby The condition of thing* in Lima is ,Lilly , I York *'('('h about the ).lMiMatk I J). .V. SiH.tr, of Troup Miunty, for [ the wind and by dt-pofcit of wand 4.fM >>. to btacxjijiing worsetiederree followx the when they are j I Iroom br..uhl; down 1Crt'.lu.t... .\ depth of lob: r how the deep interest of (iencral fiarfid.1ill other in rapid .uti'J and the I fora '( I, -r: WillUtu .\ll. Wright,ur IUdlufl.1 4 Ifett i* luiiltsl\ It is l lrlll".o>l to advertise | their future. of limn nine-tenths lhi 'lurJu"4 I for Ciiiiiptn. (rAiul N. C. Kinirtt. Eulogizing the IU>li<'Alnominee 1're | treated the title f \ county, fur Seerttury of !Mate. [ Mtsals to cstalili-h and maintain arhauueJ ; l lie to divert (he attention fr tbujHil i , thirty feet wide and six fret die fur l.n..iIt'lIt, he Itouxtfully tt-lls the' the actual lainditionof atfliirs., Intbenuaiitiuiethf | fr"l- which ha been ': lullrWllrial convention. ( adjourned IACHAS this bar, and if no bi U detiucd a,/. k, audience that"IJartU-ldbegan; life asa l-.y.' Chilian* are r |nuWOtolUJi to the I'liite! Srj.u are retire; (tirarivu ywduttt! we verily believe that! \by the first of (A'Uber exiKtct to 11011 theicge di.tin"uUhwl l ( nut-ting addreiw fj the to-ulght and they [then to begin tIe plan of {improvement byI tl edeepest' research of the iit'M-t ,found of Uma. Ily that time f.n.Il" whose 1..lle of eta trutl. i fly pn mean of two jetties, n* nubiiiiitcil in the re- fle-nifiit remaining' will l be greatly r( |, sUlu| Uepubliean lO.I.ih' of the t-nj-Mtitt-r tliarge uudtr tte of antiquarian of thi Nation (big: SJ) will not and) few will "left u* .pecUt ,r of tl.t finul be-in gathered! | .1 a State convention (Sa i DMoaly 0. 1"f! The amount available for this controvert this statement). grit Lt'.rt" .true'fc'l*. 'w.-Tuwyxt tro ..sum elt tlot&1.tfnl t-kt.t r 7th,; lu nominate ,A. l 'k a ---. ----_ .. -....... .....- . --- - -- -- ..T'i .' y , -- ._ , -nt. "h.I a. I ).,,If 4 _t- rfi Iu . - ? * .. !....- - .,.,-- -n< -.,............ 'J i - .w-_.......,..._._ ...... -,------.- .-- - .)J' . 4f' & . !iII .. '!'!IE FLORIDA< MIRROR,: AUGUST U.oy \ _. _. _. -: ., :, -- ---- ------ -- '- -- --------- ' : -- --------- -- ' Tin i'UlilJIi ot r, *. k duad l bone* to cur!r u,.,with unpleasant I'------u\ turned around-, and then hi, e\e "."Annie! trkIDickstartingupfrotilhis? "Don't) you feel quite the thilg.o" lie t " dust Ditk felt till. this? but Aunle's! fdlul'1 Adelaide Urn ml, who was l'a. >i troubled !sleep, and dismayed, on seeing his k'f1 ; + m They had been ;married; three weeks? andwere influence uvcrcametcverytliing, and, he' told him at that instant She' saw and recog' young wife in teats i What on earth is the' XI If you don't mind I I think Il tie go '; lt', ? now in London\ making I't4l'nratioll8fur herb' i; *>.1 : nixed liini: An t'111ite smile, (' lmI4of : matterVhi) arc you (crying ? This is un', below fur a little and IIIC low'u.t' It I. 1 a long voyage out to India via the Cape.: "Well and what \\11" she like, Dick I both joy and thtlIl kind" hot weathcrwe lime that I makes 11x'feel ' j We are speaking of tWPllt "''yours ago/ must know. beautiful' face as I'll ex< ottering him :11 suffered the reproach rather than dis, lnuguid." down 11 when the overland route to 1I India I was anoipemive ":'ihe was u beautiful tture-tllll. thin; her hand to I'lwk trll' hil by telling him what she had seen. I.Ill right dear.I 1 Let me help you 1" F : luxury not always: within the with glorious! eyes! and dark hair." You kil'\ that I was: coming ?" So fOhl feigned l that she hud been thinkingof the companion. .\ III Itlll set you I ;: means of a young Indian, civilian, who had, "And how was it you did not marry her?" No," ami-+ ", Dick, gravely, his: fare as home, and looking at England: fir the last I I was not to he d.n\ Annie W, : I'lh'l1 i1' r, come home on a year's s'uk leave, and had came more faintly from Annie, a* :she eon- white as tpul h, I Xo, I did lot." Then, time.! She was so' devoted to that she .\ her Ill'lirt''a!' t,, be: near the poor: grieving t "t fallen in love, three 1Illlllh'l'tire\ its: expiration tra..tl'llu'r own fancied. homeliness with the taking .\ '" band, in his, he said, Allow would have: said! anythlng-ratherthan grieve '-irlln the next cabin. Shecuuld think - with Annie Moreton, whom he married picture, he had, drawn.Dirk me (to introduce you to niv wife" 111, or let him suppose she wasdwellingonthe of nothmgelse I I and it was from Illre11' T i '' 1' on the shortest!' wooing ami wedding putting away lit his! cigarette, his A faint 0 !" escnj.ed from Adelaide as trouble l that had( befallen them. paththat she often came to be near h'l'r the unseen ' that a man in his senses: could well risk. mind )busy: raking up the ashes! of a Ih'II,1In'C the two ladies bowed to each other, and then And indeed with all truth, had he touched unknown l'ullnlll of lonelyl , ); Hut he had( no misgivings! for love is proverbially 1 to aii'mio: the I living, did l nut mark t the Miss I Jiraiid passed! 1 on to her cabin, leaving rill the, Subject 1 she could have told him that 'uiturs. 4 so full of faith that at no time of bis, : rapid changes: on his wife's face, nor diiHie Dick looking into Annie's eves with intense her jealousy: : was swallowed up by l'irI111 Suddenly. while indulging 1 1 in these a; ''fi life is a man such' n true believer! as: when he we how every word.I he let fall win! being mI1Iinpll'fl)feeling. .\lllllltll their hearts her one desire was, short of giving ul ) thoughts!, as she sat by the open port: 'I sluesaw 1'11 flings himself into" 11I1111'1111011ulluTl'.1 thither gathered' and, garnered: !in her heart amimemory. a sense of 1111l1HIllrpu.1. to make the poor girl .the next cabin hap- something move not very 'far from ner. I by his affections. AnI'thi:1: bud been, They were silent for I'n' ; py. ill! these! latitudes the twilight was! short I and flue case: with Dick and Annie, who loved at "Why didn't I marry her?" answeredDUk. amid, then Dick whicpcivd huskily: : For many\. successive: days. Miss Hrand bad 11 but faded, and the moon had: not butt yet t 1 Just sight, and pursued their impressionswith : ) "For very gisslreusuuIcunhlu't.: : : (Come into the cabin. never appeared either at or on deck. :' "It was too dark to see distinctly I , such hot haste that they found themselves ".Why, hadn't you money enough ?" Annie followed him \11(1 they were She refused: to leave her ( in. The Doctor it was some one in the direction ot I' Miss( ; married before they had quite realized "It was not a question of money at all (thl'f' he exclaimed in I'oh'c fiI of IlItl'l' was eull'1111. and came out looking grave. Hnmd's cabin. Soon ulllolMa8.: at ri""i " ra 4t' that they had met (Of course, in his! wife's \\\, were engaged! for a year, and then-" idly, You believe me, don't 'Ol knew The 'urltlll'l, the, Hlundells, all besoughther as the long white ue (' \ /; ,.TCS, Hick11 the finest! handsomest, noblest "And then-?'1 asked Annie eagerly, lo'thllJ of this: -of her being a passenger., II vain, to make an ctt'ort, but she through the port into the main challis : creature the universe could: produce, "It was! broken oil'," said Dick :slowly!, ('OIMlIot answer him for passionate was! resolute She pleaded Il'lIickn'II.! Without another thought Alle divined, I ,; He was !something of all these! but not to with face averted, nl\ll/lll abstracted air that Ifohblll languor, and finally grcwexllahle. her intention, and rushed on deck.: I name e.1 tile extent of his young wile's! imaginings.) appeared, to watch the career of each puff' of "Say vuu believe mite," cried Hick, kneeling Nothing w"UI.ltl'lpt. hlr UJI\'C." she to distinguish her husband in t the darkness ' Dick, on the other' hand, was not quite so stroke beside her in !'erplexlty Olt cbtf'I'!. 'said. she screamed his name. ' .tarried away by Ills ideas! about his! wife, for "Were yon sorrv ? Did, you part' loving "YCol"! .h5I! ,ill,c'1l-" 0 t'. (Blltl lick, Another week passed' : milCli Miss Brand .Dick Dick save her I ' he knew that the world contained far prettier her, loving each other) ? Answer me, J Dick- I eami't illr tie feeling uf ), Furgn'c mite. never appeared. :tl'\\'lrI: to grumble In a l'olent Dick Munro wasatlus: wife l women ; but none, he fllt.'ere kinder ",,,Ullif( hick I" but I shall( -to see her. ; they thought she might crime to meals, ""I,', ttr f truer than she. .\1\I1l0! this reckless: pairt "Yes, Annie, it was an awful time There, And she flung her arms around her husband's hit the boy who was told oil' to wait upon "What is it? he (' 'I. What has hap t bad better I grounds than the majority for' I don't want to fl'lIIl'llIht'rllIytlaill more neck, as: she, confessed! this: to lim. her shrugged, his: shoulders, as though he petrel' . taking the future: on trust, and chancinghappiness. ; about it. It is all over now. und I am married Look here, Annie," he cried, starting up. knew more than he chose: to say. Mrs.!! Ca- "Hush Punt let her hear you, Mil : )' to the best little woman in the world "There is: yet half an hour ; say the word ruthcrs became nervous: and confided, to Annie passionately: ( ; and pulling f him, ttll\\ I Jhllllcr11" laid, and Annie was watching and, Annie, I wouldn't change her if I and I'll have everything up from the hold{ Annie, one day on (Il'lk. that she feared Jl'ussliraull : chili side, she pointed to the white figure for her husband's!) return from the window could.1 nnd forfeit our passages' : 'Sou shall not go was: very i-peculur. in fact. Indeed about to take the fatal leap. I "f a first! floor apartment in a street oil' Haker With this assurance! Dick flung away the if ,'ollllon't like" she dared ) say !she thought. There was no time to be lost. She I had I street She had, not long to wait; \presentlyA end, of his: cigarette\ and, put his arum round :"Xo.no | I won't hear of your making 'U was too bad of her 'friends: to send a made the spring, and with u shriek, was fine manly fellow, with open countenance Annie, who' nestled! ilose to his side., such a sacrifice. : I'll bear it. I know I am girl like that out without special attendant: gone. and soft, expressive: eyes, came bounding\ up I ".\1111 where is: she, (Dick ?" !she' continued, fool:< hut i is" a feeling I have. I shall or relatives! of her own, to look after her. Dick !nIt all. In a flash: of thought I I I I I he ' the stairs: at the top of which he was met by by no means, satisfied!! 1 until she had heardeverything. Jl'wr be able to"see or think of her withoutremembering She' had been recommended the long sea tore oaf all superfluous tothlg, saying he t. :i very adoring) little wife. that once I she \\11 as near to voyage, but she was: evidentlyunfit to travel. did so: ? "It\ all square, little woman" he exclaimed "In. England.: ); I believe She' came home you as! -I am." :So; obstinate. She' had taken a fit-a mania "It is: Miss: Hrand. She I hits fallen overboard. . " p 't: kissing! : ) her "I 1 have secured a. for her health" "Nonsense: : Annie Listen: to reason.: !into her head that she would not leave her For Ood's! !sake, stop the ship. ,i? capital cabin) on the upper deck, off the cudly. "Had she a pretty name?" YOllre wife, darling! ," he I'ail. h'wlcr'11 cabin all t voyage, and she supposed: no Being 1 splendid, swimmer he flung 11111I'r J D ; There nre very few 11:1I11C1l',1I/wn as: yet, "Now, now, \Irol! Inquisitive: -you are ly I ; then he heaped reproaches !! on his one could prevent her from doing as she self in utter her 1 .! "'IJ I bad my hick-Xo. 10. .\IIIII"W, let me wanting to know too' mutts" foolishness! for having told her anything liked" A cry of Man overboard I"! Lower the I t 'half something to eat, for 1 am as hungry!: "Hut you will tell me, darling Dick," she about Adelaide Hrand. That evening Annie! confided what Mew boats !f" :111 rang through the I ship ; orlll'r . a* a bunter" criisl, bribing( him with several kisses.: Forgive me, Dick darling, and don't be t'luth1: had told her to Dick. He was were given to slacken sail, ali volunteers Saying this he disappeared to prepare/ for ""'('II. I suppose there I is no great harm angry with yourself. I was my f/ul for bcing nut sorry to find his wife open the !subjectof were at hand! to rescue both dinner, while his wife rang to have it served in your knowing her name," he said, carelessly. : so) \,. 1 prolbe\"I. from her own accord, as it fhO\"l'l him her Annie stood on the deck in mute agony. tquicklye : this: moment, that I will never allude to the mind was in I healthier Moments were like eternity How would "It is one of(Ireen's best ships," said Dick, "then tell it me." subject again. "Do 'OI know Dick," she continued, all end? Was it thus she must! give up her after they had )been seated table) I some little "You darling inquisitive little torment And, with an lmrtlhe dried her tears "poor Miss I Hrand is: in a bad way, and 1 life's joy ? Where these two to pass' into the o I time: and his hunger allowed, him lo It i is: too bad: of you to rifle!: a man of all his! and smiled. wonder, dear, if-if-" other world together and forever? (Jod's :\, talk. "I wish could have tllk"1111 over- /i1''rellOln tills undefended, way. Her name, (Dick looked at her with I puzzled air, and "If what ? Speak Annie, and don't be wi be done was: her brave and only t::. laud ; )but I never bargained for getting; married then, if you must: know it, was Adelaide, then was: fain to take her at her word, and I 1 afraid" ) prayer, as with her hands pressed on her when 1 came home; so the first!! t fewmonths I Hrand ; and, she was: the daughter of thejudge they went on deck together They I sat in : "Wl.l, if I might ) and wait on her and temples and her eyes: firmly closed, she ." : I went ahead extravagantly, and my chief.. one of the I't'r I sheets: and watched) the : of her 1 :houllike to if I might ; awaited that awful crisis.: I! ; n i lent such n lot of money that ills I just: a shore recede from l their view. How long I for t O Dick," seizing hil 1111, ,, by what 1 The excitement on board was oaten. t. t i chance I had funds enough! to carry us back, A fortnight later Dick and his wife had. would it be before they should see it a.mil) ? : feel{ ,for you I know what she has lost and HOle of the ladies: wl'fln hysterics ; everyone ",: : around the Capo even" wished: their friends' good-bye, and were onboard The thought was not without its: vein of sail-, I must now be !sulftring, and I am so-so- was anxious ; bravest of all was . t't "1 am content," said Annie.! "::01); long as! the Miiymjlln[ whose blue-peter was ness, and they were silent Other passengers : I sorry for h<." the one that su Ill-red 10:1t: Toor Annie :; 1 r.2 ram with you I don't care where I am ;" for flying to announce that :she was getting soon followed 1 l them upon deck and were Dick f'lIullIl'tllilllt. First of all he was Amid the din and confusion: she looked up I .:, the good little soul was full of admiration, under way to !sail that evening. sitting or walking as their inclinations: dictated. thill kill 1 -heurtedlittlc woman and whispered to the H""tur.: a: ; Mild gratitude to Dick for the happiness ho Annie was pleased: with her ,'ahlllllllli its: he had for 1 wife, and how despite everything .'Tell me the worst!! when it comes." i bud bestowed upon her, a penniless girl, by arrangements/ ,, which were all that an outfiller's Presently the Caruthers l'nllIC"Olpa. he preferred, her before all the worl The, crowd moved aside: to let her pa's.t"! , tailing In love and marrying her. (ingenuity could devise: to promote nied! by )11:41: Hrund. \on : wer me, PickS'uli't youlet the opposite! side of the vessel, where, Wltl . "I should like to have taken you overland slnu'eund comfort, under extreme difficul Dick was holding his wife's hand which me? she asked. her hands still pressed on her temples ," reiterated Hick : "the trip i is so much ties. trl'lhlelll.1 turned cold within his own "I was: thinking, dear" he said, quietly, paced' up all down the deck in the restlessness . .jollier, so much life going on and places to On deck all was confusion! (Jroups: of when Miss BranlllPlenf't1 I greatly: distressed "that I love you for your request but'l of her anguish. be seen. Hut th'res no use! regretting; and friends: gathered here and thereto see the him hi, wife should would rather you did not offer It {is kind One or two ladies came up to her, but she f, r u voyage round, the ('ap| m is not III) bad after last of each other for many years!!, were slitter, and he determined to let Miss! Urand of you-and like 'ou-hut you could never motioned them away. Only alone could. all, ft you have a good ship and nice people talking eagerly The Doctor of; the ship understand that their-i>OMtion toward each do her any good poor girl. she live through these moments un banal" came up to Annie and Dick introduced other must be that of total strangers throughout .S1'lyu"llccuuse.Ill At the end of half an hour the Doctor ( "Of course! It isn't," said Annie, prepared himself by ottering! her his .field glasses. Dick the voyage.It : don't ask me Annie Now came to her, saying : to find everything delightful. und the Doctor entered Into conversation! was: a painful situation for all parties, that the subject is not tabooed between us: Hoth bodies, have been found , I 1 "The cabin Is. only ten feet square. I say, while Annie amused!' herself watching the but there was only one course for \hint to let me tel you that I would rather we kept Drownl't,.sl 1M ICrCllIIl'. I little woman, it will bo a good test of affection novel scene before her. Passengers coming take quite a from her. I!it i is not well fur know )'et. There is still )hope to live together in such close quarters some being hoisted up on board from the He prevailed on Annie to go to her cabin her to f>e in her cabin, would be worse for as every restorative is hand 5'." tilt four months," remarked Dick, with a boats in barrel which hud been converted early ; and under the plea. of smoking a cigarette her, believe me, to see me always with :you. "It's with the ladv, She's gone," \> Hinlle.! Into a chair, while others made use of the he returned to the deck where Miss: Now do you understand!! ? said the sailor, who carried her on board 4. i r':: Annie smiled! l back saying: "I think we ladder at the ship's side. The vessel I was to Hrand{ and the Caruthers still were. "Just us )'u\ please Hut 1 fee as If I but there's life in the gl'ntlelan.' f o shall stand it," sail at 7 o'clock that evening. The captain Adelaide Brand was sitting in her chair, owed her some reparation, for Dick, And the speech : on from \', "There's only u plank between and the and pilot were both on board. The chief officer silent, and a little apart from the others, darling, I have seen her anguish. I is too mouth to mouth. j t 1- next cabin ; we :.lml1ll11.\'e to remember this, I II was Irylng the wind 'by means: of a when Dick passed her dreadful, and sometimes in the nigh when Dick was carried to the Doctors cabin, and und keep our voices down to a whispering! further ]>cniiant. The second otticer was )Ir. Munro, he heard her call ; and he the ship is: quiet, and there i is stirring '' restored to consciousness: Health and I pitch 1 giving orders about ropes here and sails : turned round to reply ; for this was the opportunity but the trl'llllf the officer of the watl'hl strength were in his favor, and his recovery "The better to hear what OUT neighbors there. Every one seemed alive with inter ho was watching for. I dilnut then I lie awake and! hear her moan and was not protracted under the good care of are saying," cried Annie making light of est. The afternoon wore on, and the ship lessen! the trying nature of lie sigh, and I can't sleep." I his wife and the Doctor. . the hist disadvantage! that her husband had was to !'Iuilln an hour's tilll('. he hJOlketl1 ant saw that her eyes were Pour girl !I" sighed Dick, sadly "I has 1'oor Ailcliade, Brand was buried u few , to offer. Dick and Annie had gone down to the full been awfully unfortunate. I never cease to days after. Great were the speculations As soon as dinner was over, smoking began cuddy, where most of the 111I.\'IenI'f.lIlImc) !! \h. Dick) I" she exclaimed. regret this trouble to her, and to us all. I among the passengers! to account for her fall ; ; for Annie, like Sarah of old, called her with friends had assembled! ) for u cup of tea ]lush, for Jod's sake !I" he whipcret1 would rather havs: lost hundreds of pounds overboard h :" husband: ) lord, and forbade him nothing. The Doctor had. attached himself to them, Listen we must be as strangers than it should have happened. I am so ,des "I think I'll tell the Captain' the whole I i In fact, If ever u man was in danger of becoming and was amusing Annie by telling her the you-front my soul I do ; and had I knownyou peratel'afraid that it will end in the old story, when I am well again," said Dick to spoiled it was Dick Munro. Only names of those fellow passengers! whom he were (Ouinl I would have forfeited my misery.:" Annie one day, during his: convalescence. be WIn good fellow and knew when he knew. passage subjected you or my \\hatoldmisery ?" "I don t know whether I ought not to have i was well off. lie felt supremely so at that That's Mrs. HlumU-11.. wife of Colonel wife to this ordeal. I leave myself out of Nothing to do with me, dear, don't fear done so from the commencement. Hut 1 moment, sitting in u l'AJmfortabl"'I'IY chair, Hlundell! and her two girls, and the other the question. J have but one duty, and that I But say no more, fur 1 can't bear to revive was afraid of doing her on injury. smoking an unlimited number of cigarettes! lady is: Mrs Macphcrson' -and her two you must see and know, For the future we :, old sorrows." "Was there anything besides her love for J r ,r with a dear little wife sitting on a low stool daughters," said the Din-tor, in u whisper must be as strangers : it cannot be otherwise: Days all week passed. The Doctor sti you? " very near chatting and laughing in her Indeed," said Annie, who finding her after all that has (happenet1 Forgive and went in lUt of Miss Brand's "Yes, there was this," answered Dick, I t' IlriJ.hte"t'elll to amuse him tea flavorless, was glad to take u survey of pity me ; lot : fl'c for you. Ood I growing more and more serious as time touching his: forehead significantly "That i'resentlythotalk grew confidential. They the six human beings seated opposite.: bless you !I" went on. The ship was sailing into warm Is why it was broken off. between us. We '1 t. l&:1Il111arril'l\ such a hurry that they hud In the meantime u commotion was going He sHke| in I low hurried voice In a latitudes, having cOle safe through u belt of (hail been engaged for a year. A week beforewe i $ everything to learn of each other except the on outside More pusscngcrs were evidently few minutes all was said, and he went for: squalls: ; each day the equator was gettngnl'url'r were to have been marie she went out v I t-ardmal fact of their mutual fondness.! : Hut expected' und coming on board. war to smoke his: cigarette, leaving her in of her mind. I can't tel you any more. The r now they could take matters easily, und tell It'su.. 0 und Xo. U cabins at last," suid, { Annie had often seen ls Brand as she blow nearly killed ; fur the doctors all tt ;i each: other interesting reminiscences of their the IIteW1l1't1.h She had seen and read his face and knew had found her on that frt morning. Hut said that, although she might and did get past: live.a Each !side of ours," whiipt'fl'tlnnie tl but to wt'l how determined he was. Ant lately her grief hud new turn At \\'I. she was likely to have u recurrence at :' "And tell me, Dick," Annie began, lowering hick I'm interested l to see who thev are.: he was ; she knew that From frt tl night, when' Dick was smoking in the forepart time. Any strong excitement was sure , f' : her voice and drawing nearer as shenpuke She wuullke to have risen, but she) was hist the misfortune: Wf the f tit of the resell: Annie would come down tope, f.tal It is: three years now since weparted. . I > tell mime;were you ever in love before silling Ilr back to the cuddy door, and I his. She was the prey of the gods, and must: to her cabin and in the stillness she could hOlldhe: wa thoroughly cured. 4 t .von saw me?" did not feel sufficiently at home among so submit ; that is, if !she could without breaking hear the poor girl murmur audibly : Xo doubt all would have gone well hud we 't . I Dick took the cigarette from his: lips und many' strangers to leave Dick's side ;rum sheHanel I down utterly."Strangers "He might have waited he migh have never met again ; but as it has turned out,old (Z puffed aside a d.mti smoke without replying l, keeping her attention alive until !"That wn what he had lal1 waited ; and then she would lutl'r incoherently memories were revived(l. and proved too 't though he wanted to evade! the inmiry. they should 'pass' into their cabin There was only one way of obeying I like one distraught. much far her. Poor Adelaide?' Hut Annie was persistent, und demanded I expect; (those are the Caruthl'rslt last," ; might kill her, perhaps, but she would What poor Annie felt at such moment- "IW Adelaide echoed Annie with a t an answer. said one of the Miss lilundells."Ineveryetknewtiurah it-she would never !see him again can never be fully described. She was uI prot untligh! Do you know, Dick I am 1 "What do you want to know for? You I t'nrthefln!! time It was far into the dawn when Annie pious I : little soul, and used to found a great glad 1 you tried to have her It must have t should not be inquisitive:! Mrs. Annie," was I for In\.thhit" said Mrs. Buntdl "You awoke The shin had made some way during deal that some way might be out of been a happiness to her at the last. And 'hum reply, as he smiled."Inquisilive 1. ( upon it the wi have to the ni ht,and they were now out at sea; the trouble u "- her voice to a whis \ ? Why, Dick, I feel as: If I'd Ili without her." the morning was glorious: and the sun It became an accepted fact at last that "and if she can see us now, Dick, she r "1 like to know every day of your life since Hut you forget, mamma, she told us about to rise, Tempted by the novelty of Miss Brand was an invalid that kept to her Ier- that we mean to love and you were bora. That's: because love you." they were telegraphed' lo at the last IIJICllttt the sighnnle got up and sat beside her cabin tier her always-you and I together rtem. 1 She It''lk.eJ1. in his face with such ten- take charge of some one going out Very square, open j spurt She enjoyed watchingthe "To bad," the Captain)' \a overheard to "My generous-hearted little wife" cried tier "pleading. that Dick-softest:! hearted oft likely, that has delayed them" said the blue-green sea throwing up its crests of say, to send a girl on board in that state of Dick) ; dod bless: you for this" t men where a woman was in gtLe.tiont'uult'I daughter white foam. Here and there were other health, ant without an attendant, too. Hut His eyes are full of tears as he kisses: her, not resist her, You are altogether wrong, IIUIIIIIII\I this ships, some IIHU'wul'tl, others outward since i! here, you must look after her, and thinks,truly lovegains by giving-7ynr- "Wh)', Annie\ Sampson, must have. givenin time, for there are Mrs. Curuthers Ill{ her bound, and beyond, the long line of English: IVx-tor. with the ladies, and we must make try'i Map unit, to you, you know MI well how to coax.Wbat :. husband," cried the other daughter. .Do let cliffs rose from the sea and seemed to care the; best of it. They will have to send her , is: it, then, you want to Had out?" I us go out and! meet t11N u 1," not for the love they inspired( in the hearts hume again, I expect, a soon as she get Ot.a IE'I fnR'i'-TllirenerY.lu: the "If you were ever in love you know before They went t, leaving Ukk.lIlIit', and /the of those approaching them, or those who out." LllQI.ltct"ttr. I, as that l you knew mile" I DiH-tor talking about some t'dl'rtl..ll'l "\es, cores of times-with every pretty I. going on al that time, the end "hidl )' She was about *fo n'tuf to her l berth The weathergrew "l'r)refused) I"I 1I.': the meru'uf! *generation '. we have seen j girl I met," cannot learn for many months. when her attention was arn'ho by a !sigh of calm, when the bll\ to move, but ll'tky lghty.thl conquer 11e moat, "That i is not what I mean I know you I Hut .\nllit"1 illtl'rc't went with the Hlun that came, us she thought, from withoutthe laid like a lug in u t. molten glass.. a !! eighty-one dictator of are a flirt you need"" not tell me that ; but I ,dells, and her ear caught all they said ship la the cabins it was stilling; and Adelaide Knglaud; and Earl Mussel at fifty-nineexi ! were you ever engaged/ ; !-to he married ; so After they had exchanged,>l greeting, she Dending forward through the open port, Hrand. was buffering intensely. The other l>lnier ton. and Lyndlwrst at eighty-eight* that-O DUk, might have ln...t you? Answer I heard Mrs. Caruthers say, l1ttr\.IIIp someone she swtlelIJt Brand, who was leaning lady is Lengtr hail grown tired of the refractory discomfit opponents hy his oratory (on the 1 me beriou>ly, ye! or no?" I who had evidently)' rCIin to in fl'tll hlr | UUl weeping bitterly. There invalulamid left her very much to pair' duty). and Kilg'mam of Prussia "Seriously: then= \"t'llh ." the ;. was no thought, us there was: no fear, of her"ailing herself, She board puzzle to them all and I lit seventy-three'' invade and " ".\ who to?" she cried, u pang of jealousy This Is the young lady under my charge. overlnKird, for her cabin was opimsito only one on knew the truth, that, and Plo; }1>nJ> at venty-Ight conquer council'rnct :. ., hliootin< through her heart, und tin- Allow me to introduce you to Mil. 'lhulh'l to. the main chains, that hung before her dared not be revealed. uf l'hr.teltlol tu change (al 1 ttrtholkI ' i'oneealcd, showing itself in her t'nos. and her daughters-very!! old friends window or i p,urt. Poor .-nnil. from her i>ort, still kept I silent i. 1 arishot' "There now, 1 am a fool. I ought,; not to I Mrs. Hlundell. iS .tltuitBruld.." Her attitude was: evidently one of despair, watch and yearned with all her soul to a monarchy t'u"Itr.t\l" at seven tVfou'r have: told you," cried Dick who had I'\'ohlln As though she had. a blow, as if calling upon sea and sky to help and comjiussioiiate the sufferer.At I I stand forward the one man with ' her face what !she was ft*I ing."Indeed j Annie heard the name, and shivered with pity her. length a breeze sprang up. How grate I "Utkll'lt to control the { and en'f' you ought. I want to hear; tell ''pain. Hut khe kept' t-ilence. Hynowonlorook At UlIl'l'nnlo divined the l'aU"of 1 her. ful Wl'1 all on board to feel I the ship going !: fc'T50; uf a defeatist Ilrlt . me nil about it. It will be like reading a wUItII., l hetr.what .ht frit. Dick i sorrow. To her I was no 1t'rl The situation I even live knots, an hour After the three }- rICt Ln'' Heacoiulield dMieartened to dU- novel, with my husband fur tho hero." I had ; lie was. ton much engrossed' ww pitiable In the ( for 'both o'clock dinner was over, all hurried on deck the at seventy, and at pick thought that he would rather say in his discussion! with the Doctor. (Hut what I women. At glut moment. Dick, who was to welcome the breath of air that was waiting hU fPI I'lt. by frau of pOJular l\cnt' nothing more, but she kept pleading; und I would he say ? Did he know ? dreaming,.gave a troubled sigh in his sleep."And to n'fn'h them.As wuluut11.Ic\ in : history. or.tur i. whatever he may have felt for another wo- The |>artyouUidc lIIu\'el forward toward this i is to last for four U'ltIS." the evening wore on, the ladies hail .1 IngU"h against the: disturber luau, he was married huts and Ids affection their cabin, Mrs. l'arthl'f leading the way thought Annie, with a sob. It is h1I'} i. their tea brought to them on deck. Every tlllol )Ir. Gladstone wholly given to the little wife at his They had to ISe.:{ his wife. .\nllt=I bio It cannot he! How hall we all live one ui board "'W I good spirits, all exceptour ; the seventy"I'l'l"thl which might haw promnuuv - aide. It wa this certainly himself that heart beat und all but stool still us Ikk, through it? And' Dick Poor Dick friemid.lnnie, who felt wci/hed down bysad bvva made. by a whole cabinet, and the made: him yield at last to her entreaties, having finished his argument, turned to her She longed, if .ht might to comfort the presentiment and the l'll'tltn of anoth. I, objection raised. against tichuf them i is, tnt although JiU winuioa 'iie told !him such and sail : p H>r creature in the next cabin{ but l..m"lla. err borrow. I II,is too vehemeiity.. marks old stories are better left unditurl in "I i is hot and stuffy here : let us go on tion from her Annie thought, would be Dick noticed that the was looking lol\ : thplltl! to rlelurt to enclctlc.wildly (rout the t\ their gr.1Wi111 drugging up of the old irony. Well, (nd! knew she pitied her. and .,1 I. al''I.tOue1 gru\'C, t _. . - --- r A H _ i -- . __'_ _ . .... .. _. __ ,,,, ... .... n'w' '' .... .. ,, .," ,:" ...1, : "-,' '. J jrn ,:. ...,'''' .''''' 'r q -w',, "" ,., ..,.." ',"d'1. ,. 1; .. ., ; \ Vo'1'. ; '_ 'II!' J.ir'I!' \ f."""s THE FLORIDA MIRROR : AUGUST U.' .... .. ._. .... -- --'--- .- ._-. _. ._- -. ..--- ---- .-.------- --- .. __. .. .- .. -- -- -- ---- -.---.-. -'-- ' -- --- ----- - -------- ---- -- : Tn.\11 P.AlLltOAD .1 t T RI'BXlxa.ttpon not think the Tanner experiment'wonderful. J. & T. KYDB Fr.onrn.m Then she went on to tell of n eae of JACK-ONVIU.E }Fi.\ March li ' the bills thc wind t U: !hurp} and cold, : ; I Iso.! 1 '1'11 wither on tin w old" fasting in ,,,tln\lli. The river Clyde one On 11I\,11If'tl'f thaw date Traiii tin thus: 1:1\,1: : And( sweet w,01.m'\I.III\\"c young grasses wandered from thy fold! ; day broke through its bed and the waterrushed ('01'. C'rnlrr mind Third M*., rr.KXAXIMXA, ri.Ollll, will run as folio** : into the mines below. .\ number of Hut evening brings us home. miner"' were drowned, the suddenness of the Are constantly adding to their stock of Staple and FancyDDDD DAY PASSENGKH: : : (Kxnrr: ?'r-'SI'\\) the mists stumbled and the rock, flood cutting I otr nil escape. One miner pot DDDD) ) } SSSSSDDDDD :: : \A'A\V Jneksonvllle rul.t.:: ., we OOO Among : OOO I ) RHRR YY YY C<!C<;<} the into an old shaft that bad been abandoned, : \ IA-UVC llaldwin .. ;nm>:;! .\. MIxave , whiten and fox SSSSSSSDD : : : : : Where the brown : I OOOOO }DDDDD) ) RRRRR: YY YY tiC; ; and here he found himself safe )from : \ IxikeCity .HM::\:\ .\. '. from the scattered DDSS)) : : Watches the straggler wlllt'r'l OO OO OO DD) } ) DDHR) HH'Y YY (i HI 8 lill! OO t 1 l stared 1-1 flocks A worse fate, however, now t ooH) DD) SSSSSSDD : :: Leave Live :' ir. II. j YYY t(5! ; OO 0000 the face. It was impossible for him to limb DD) DDRRRR Arrive Savannah:: sA: r.i. . Hut evening bring* in home. OO OO DD 11):4) : : ) )DDHR) HH YY ( Ill CHili( OO OO make himself heard There Savannah) S.IHI: . out 1I0tl'olllIIi : : : \ Iicavo : \ :1.1.1'II'l' + DDDDD\)\) :SSSSSSSDDDD : : : .1. 100000 iCil! OOO( DDDDD RR RR\ YY lie't; ( { The sharp thorn prick U*. and our tender seemed no puMsiblenlcanMof communu'atiim I OOO OOO UHHH:4:4\) : : :;: \Live Oak.; r. M YY RR RR; ; fcet with the world ulllln't the cud ot sixty In-axi like Pity :.nn' r. 't. Arc_cut and bleeding, and the !lamb repeat days some slow-going,) person of enquiring ('Ioahln Hut!*. ('lIlt!'!. Hoot*. Shoo! C'CC'. 1"111I111lwlll'. 7:0": :> t'. 'f Their pitiful complaints\ : rest i io: !swat turn took it into his head to exnuiiuctlit' old .Arrive lackonvllle: oIII.i: :i r. 't. When evening brings us home. shaft' as: be felt a little curiosity know ---- MAIL AXD) l'XI'H--I: !::: (Dutv.) I whether the water: of the ('i\'llc'ha,] "found " We have been wounded hI. I the hllllh'r':4Iart : their wav there. Tying a pier of lead] to a DRY GOODS AT xgYOnK RETAIL I Pill CIS..t 1\\0 hcane.hu'ksum'ills White: House..".. .>J:1.:.:>":; r.f. M.Leave ( !!, rope, this'investgating: { person: let it down hail i --- --- --. Rddvvin................. ...... 7Oi: \>. .t. (Our) ('\'I'oIlIrl'1': \' 11l'1LValld our heartsSearch into this shaft, and he t thought, after he . : for thy coming':" when the light departs lowered it, that he could hear a human I tt- \II-lIt for DKM.IN. Orders: promptly\' attended to."ft-V I l.1./\\.I.lIl1t'1'\\"ilh.Sanderson: .. :;s.07:2.I': ; I'. M.Uave M.Leave . voice, but the tllUl'O1111': faintly, mini he - -. H-III': '. Olnstce : At evening, bring us home might hauled have tip the lIIioIIl'III'I1.f1'r lead: and wa: surprised awhile\, l he to SANJJOUN: & HOYT Ix-ave Mt. Carrie! ........ v.:.. !0'0:5: : \: 'i. I\I! : . Arrive bike City f. R.l The darkness: : gather Through the gloom liula piece: of clothing attached to it. 'l'imepoor Live Oak. '.!:I.. .\. 't.Arrive'l'itllahasste . no star wretch belowya* still Illin'.III1,1 bail :-::1:1'0TH1I.T.: : \) :: : : :XEAR: CEXTRE: :, "eaivi' 7.;"" .\. M. Rises to guide u". We have wandered far. managed to make this sign. Ai>tance vi"' : /.i Without thy lamp we know not where we hIl1l'llintl'l'alh'I, men were lowered into Arrive Albany.KI5); ,\. 't. VI KM II lil'TVII.GllOCEHS VV Hot IV Arrive Savannah. !MHt; ,\. M.Leave . the shaft, and tlicstar\ing man \\a broughtto areAt evening bring us home! the surface: nearly dead!I. lie III111IJI'I'1I1111thl' Savannah -L4."o::" v. u. SHIP CIIANDLEH8) Ix-avo Albany\ 1:1\\: \ r. M.Leave . withinreach time \\ithout food, but had been , The cloud: are round u*: and the snow-drift* of water, and. had tenaciously ilung Tallahassee: ... o:4" I'. ii.Lease . ) :!:t":; .\. M.Leave . ) hits . thicken.O to the huge that he would bo rescued.' The vxn ivl.nt. IN Like ( o:;dl'> .\. M.Leave . thus -'hl'\llll.tI.1t'II\'I': \ u* not to sickenIn greatest interesta CAcited in the case. It City the 'wa*tl' night-our tardy footsteps: wa thought: that the unfortunate 111.11 \\ould I .. ____'" ..,_____'"' '1'___._" '" "' -- ).lt. Carrie:. 4:1: :*1 .t. 11. quicken.' lose his life: but with careful nursing: he tit HAY ,1 I t'OKX OATS ititll'1{ i I i/nTi: I-t I I '/'. Ix-nveOlustee\ t: 10 A. M.. At evening 1 bring u:* home length recovered to tell his: icmarkablostory w'a! j a"-.a Leave Sanderson:: ,VJO; A.M. O'ltricr-; U-ave Darbyville. r::;..i .. w. and to be the wonder of his: day.: - Jotirunl.THK --- 1..II\lB.II.t\\'lI1.\ ............................ (00.)1.: . M1SCLLL.IXKA. [Leave White House: Titi: A. M. astronomer of the Providence Journal, A 1.WIEI'K: \ OK) l't'Itxl'r'uul.1L11,1VS: : OX HAXD.: Arrive .Jacksonville.................... T:M .t. M.On . FUOM I Ella TO RnflllCTKIl: OX A BlC\Ct.K.; says in reference to the heaven during! ; August :1lillllltI : Train Slci-ping ''U1tllll * 2-1!> Express' : A bicycle and I its rider swept\ tli rough West : .111titer,, will be a superb object to lily through to and 'from 1 ..111l.k"OIl'illll11,1/ West Main and East; Main( the evening. beholder during August avenue, every \ Cars'run( Savannah:: ; also, Lucas Sleeping : street yesterday morning at 1raphl a" he I, comes beaming; above the Imri/on likea ARLINGTON NURSERIES. through to and 1 from. Jacksonville) and Tal rate. (jo people \\'IIllIll.t\.1 why the young brilliant moon. He rise: "'11I""t, 10, at ; . nun devoted, the :Sabbath morning to such the end of the mouth, about .s. :Saturn: iv i lahassee.FEHXAXDIXA: .; sport, and a small boy on the four corner morning star and, follows. i'losfly In the wakeof ----. : : )( ]::X l'mIhtl.: ( .\ .) :screamed, "He'011 the homestretch !" The the more brilliant Jupiter lie i is, however I IM'-IIVO Jaekvonvllle..ttH.H.\ . rider dismounted in front of the WhitcombHoue no mean object for observation, as he 'I'IUU-J\I and sr..iii-Tuoi'ic'Ai, I'ltltl'1''I'R1ES.; I4)SIS,1)1(1: : n. Arrive llaldvviu\ .PJt: ::;n i'. M.Arrive . placed leis machine in the hallway, rises to the northwest of his rival and about Fcrnandina.......... ...... ...... 3:111: v. \1. and without noticing the l'UI'lnu.taZl'! of the! a half-hour: (later J lie is increasing! in si/.e rorsniui \'I.ucan\: :: Kiiiiritsinui ri.on IKIn.vrs.: Leave Fcrnandina..................... ..10'M:: ) \. M. people, walked to the desk and 1 registered and clearness' : tint and i is: well WIII'IIIIIf Leave Baldwin.................... ........ I;::*) r. >r. 11. B. Thompson, bicycler' on the road." attention in his: present }phase. On the 'joth .--- Arrive Jacksonville: 2:1:G;, r. tT.1'a.s'ngerv . Mr.I Thompson resides III Erie, where he thereill I'l'I close conjunction, between! for Fcrnandinn and Cedar "I'.v' teaches: the art of bicycling, to a large; l'1a"o: l'tlllIlI:4111111: Venn, those planet: being then XF.W: VMI 1'i01.InTn\ (( : : : :: ItmldtMl Orungc'I'i'ces :'1.111'l'Ec'1.1.TY.: :: ( take) tld* train No train! from I P..ildwin tt. of pupils: lie left there on Friday last at 2 forty-live minutes of a ..h.gn'l'1,111'1.\ 'Ihi. Cedar( Key on\ Sunday.CoNxnVioN . .. m., and alighted; III front of the Mansion( phenomenon will nllord a tine opportunity' --- : *.-At 'Baldwin with .\., U. .\; \(House( Buffalo at 11 p. m. that night having to the telescopic\ student for a tll,1\.f. the \V. I. T. U. H., for Cedar Key, CialnesvilU" i pased over the ninety-three miles: between contrast in planetary: colors: the delicate tint J:' :Bud: for i10s0rip11.o{ Catalogue.! mind FI'I'IIIIIIlllIa.1111 all points North toolVest the two cities in eight hours: an hour of t'tlIIII"111,1: the inimitable soil golden Ai.iir.itT i. nIU\\I..I.: \ ; at Like City for Tallahassee, Albany.Savannah . having been lost upon the road. .\t ;a t p. in. hue of Venn being beautifully\ illustrated.Trami JACKSOXVII.l.K.: : FLA.K. : and all\ \points North and 11'Kt : Saturday: he left Bullalo, and arrived at Batavia [ :* set" now'at about St::! >, at the end IIf 1II' at .IIH'k""IIVI1l1' with St.:: Johns Hivor: Steam at N:2I:: 1'. m. having I kept, in motion the the month about sunset 'l'he.lugnst: t moon ers J. :S.: McELHOY: , entire timl'1 11:30: yesterday:. \ morning. i Ill'Il'I't full on thel Uh. The new moon of time .rith >.. 1I1.Xlunsox.T.I"ITIIl: Tin FLORIDA "'. Dvvinsox( ) '' :Master; Transp'n.! Batavia and arrived 11l.ftIt! &: (.*>. At pays her respects in quick succession to four :Silperillteinleiit.JACKSONVILLE. 1:30: this: morning he will start for Syracuse, IIf the planet, to Mercury on the f>tli, tin A [\ \ li AM 11 Fl"HXISHIX;: ( IMPUOVIMKXT:: : COMPANY! _._ where he expects' to take supper.: From the day\ of her birth, to \1'1111:011111: the (lib mtndlo t rl'o\\'s (: :: ) :, PEXSACOLA: :: ) ANJ City of Salt he proceeds: to then ; thence to \1.111111"/11\11 Mars( : on the Nth. On the 2.V:\ iT.\i> iitTAur.it: : ( ': HAILHOAD.: ) ::41'111'1'1Falls, where he will remain a few the moon i i" near' .Jupitermimid on the'JItli: ----- M.1sTEa'rn1Ksl'otmTtTmil\'s OKFK:, [ .1.\\:01,1\1\11: return to Erie by another route. she i I" near Saturn. FIFTH :ST., FF.UXAXDIXA) FLA. Tvt.i.\iiA8.rE, )Fi.\., February ;3!, 1'1'11I.> > f what others l-Vriiiiiulliiii. am merely doing many areemijnyinguplemt"uretour through the coun ]h\I.TII IN sir.M.MKK.-rToo II" p("\tee I On ami after( Monday, February '-', !$>/''.',. , I find) it pleasant shootlugalong observe: the same rules: of living in the ". TOM its" HI It. It. I.Iiio, passenger' trains of this snail will run as follows try. very I days that thevdo in the bracing atmosphenof'fall I : viz: the hills: and through valley.: There'sa : , over and winter, and, as a rule, they pay I .mud ('<' !ar Ii.c')'. goid deal ut'pnrt about it, too. People PASSEXOEH: : : 'I'l\IX-Jo\HT: HOUXILeave : /. the country don't exactly understand: what dearly for t their imi\>nidence. Eve i in tin' (' Chathllmus nhec.daity at. 2110 J'. u. I fut little i i" taken tll one is doing; when he whirls by the farmhouse matter of clothing l care I taliiiTh Leave ( IIt\l'Y! :'e.i M.U'tive . and before they can hind out you are I'rllvilh'lgaill"t sudden changes: of temperature \ Tallahassee.? ntHir.( 1<<. down\ the tad. Sometimes they see or during period of intense (beat to reduce Monticcllo ., 7111] ', way r. the of the I body. Man( I OlFers to Lessees: and] Purchasers a large! Leave M. you coming/ and then the whole house and temperature I sui) Leave (;ircenvllle... H :.IS i: MLeave its\ V'bitlll':4"lItl': called out to witness "the jiersons often reckless thcniselvcs! : : to the number of the most eligible! and desirable! Madison..........'.. t U *'tll'. M. while olll'nfl' .. .. strange sjiectacle. Th1pm pas. a wagon in the most Imprudent, manner m to ,the kind and I it.s: suitable for lliisiness: Purposes or feu Leave Live Oak.............o.. 2 !la: .\. M. and the horses' shy" little, and you hear the equally,r' ) II'.II.IJl.4:' ) :: WOODEN: COFFINSAXD ) Arrive :Savannah.: : ......... !H (II) ,\. 11. The latter Is their food. exclamation of !surprise mingled;, occasionally quality. ( th'rntloll. The a lIIo"tillll'.rtullt ) CASKETS: City or Suburban' Ui'sidcnre: Arrive Tlioinustlllc: .......... tl.5.A.1.': withIn oath as the farmer rein III hi* l'IIII lnl'lerLIlli .\ rrl\' .(! Albany. .ii:3.t.'i.) : I'l.tll'r'l.t the food the team and wonders! what passed him. }Do more how few nourishing restrict I themselvcsorshow the ;least: WHITE: METAL AND. Si SILVER PLATED) UPON KASY: TKH.MS.: :; Airive Likeity; ............... :I t.:5.1 .\. ;\1- tliednbwbutbvCmczVell.lautuuch: Yousee Arrive Baldwin; ........:. II! 25: .\. w, in the for discrimination: selecting supplies: TRIMMINGS( the curs! don't very often know that onei their tables!I during the summer months : Liberal Discounts) : on Values: allowed tojuirtieH Arrive Jacksonville.......... 7.r>() .\. sr.Arrive - i I" coming mttll'yuu'urt/ near enough to soon moderate exenisc abstention CONSTANTLY OX Ji.SU.61 $ 1..flllllllllllll..r....... 34tH'. Sf.Arrh'l' , Frequent bathing, : . get out of the way. In the villages,; they are far from all excitement ; engaged in mnnufui luring or industrial <! ,,\ ...... .Sot: r. M. a:* as possible!I , much surprised.: The bicycle i i" almost unknown of drainage cleanliness \ --- who will the Arrive ('e imtr Key.......,..... ...... !.l.TOr. si and the111'01' tire of asking \ rigid supervision cntcrprii.es, erect on property queMtinny in the of tin V.iSSKxil'It'I'Il1IN-11'EHi': : ; ( : ; BOUND. and I toget not only living rooms Bodies: wIohC'OIllIel dressed: 1 and preserveduntil > drink investigating.of ginger-ale or water.generally" "stop\\ hat house, but in all the obscure: places: aboutthe burial with or without tin- n"o.of ice. purchased: substantial, jiuproycmenfsfor Leave Jacksonville ......daily, at. b,:\\I) 5'. .vLeave. tin a think of the bicycle-back' theory, I'n'lIIj"coI-tlll''c: are safeguards which mi Remains!l exhumed /l1I.ll'llIl'I.11II ('UI'Ifur rcMdcncc, or in which to conduct their )Fcrnandina' ,.......... .lll.'iliA. M. you caused person, however robust his health, can afford removal.Telegraphic.. IA'fVvhtili'sVtile.! : ......- H02.t.1t! ): that said to be by usillg'Ihe bicycle deformity?" "I know it to bo an error. to disregard. The list! of ills!l that Ail- : orders promptly attended tll..JI..hll business.IXDUCKMKNTS! Ix-uve Cedar Key ...m.. -I 3'\ ) A, M low the neglect ofthcsoonlinary precaution I..ull1111101111 :. 7 (Mi r.tlAxmVo ;So; far from causing deformity I know that : __ : TO MANITA.TIW-( __ _. __ ___ = I " and all serious in their effect -- l Like \ . man's i i.* very long, are : - City ... .fri'4'l i'- M form bicycle\and practice shape more tends: than to develop other a sjiort. upon the human frame. 1 II. i:. oTTiitiit, "\ KHS:: : by exemption fora term( years: from Lt uve Nttvaniiiin -1 ,10: ( r, sLave , ) any ) )Live Oak................ 2 15 \. MLmve into action the taxation offered the Every: muscle i.s: brought by several cities' and THE UUHJM; lit'u..:.-A woman never Madison ... ...11..1< :31 .\. .t und the chest i k thrown ' out lungs arc tested and the shoulders back by the practice. grows old. Years may pass over her head, I+lmX.SUIX.FJ.OJW.) : I .\, town Apply' to Leave (irt-cnvillc.............. ...,.. 4. ;jl J!) A, MLeave but if benevolence and virtue dwell in her ' .Monticello ... 5151 . .. II\ 11rrU' , When 1 began 1 was xtoop-shuiildenil; heart she is as cheerful as: when the springof j2 >Ollc! ; cor, ]heath fi; 7th) st.*' .. Feriniiidiiia.HJlf .. 'I. .. ( , regardedusaconsumptive. Now there i 111 none 1'\: un I II. IX \ (' Tallahassee: ...... .. TOO A tiUtlVeTallahussc life first ojieneil to her view When we .... H :\\11 .t. Ic, and) of it. shoulders My are square my look a good woman we never think ofher --- upon OS .,. 'I Groecrlcs Leave Jiilncy. .It) MArrive the of nc Fttmily' believe that I IUIIII'OUIIII. No. use age; she looks a* charming as!I when the 'rnEi: ':'I'1' ..vSeioiid DROTIIEIC: " the h s Cliattuhooclicc._ ......11 ail A, w bkycletendstoprunitehealth: mudsymim-/ rose, of'outh first: bloomed on her check. metry of form.' That rose has: not faded yet ; it will never ANli / Street oj.po.sjte I'ust-Olllee, CONNECTIONS.At . f.idc In her neighborhood she Is the friend Live (Oak daily with the a'II1f1.h.Iorhln . }>U"ERT'Xl> FLOWERVick's MmtMyMmjiiintt und )bemicfactor.Vhu does!not respect and PROVISIONS.CiisUimcrscuti :: ,. ..nqI'III.1'rFltN (- and Western Kuilway to and from that always: brings us a treat in love the womanlio has passed' 1 her days in l-Ia\'allllllh.I1",1 all Northern; Eastern! ami . the \uy of good amid Useful reading, says ul't'lllf!' kindness and mercy-who has lain I Western Cities.At : there are many who have large &-arllellSu\II1: the fri'l\IllIf a man and O Jod-who*>u whole Like City daily with tho Fl"dd..11- i i often the plants in those are 11111'lluut und I life ]limit been a scene of kindness mud love : : rely njim getiing CHOICE( : ; t rid Hallroad to and; from 'J\'k < \\hlietltigustimie i 'y.. ju.t thrown away, Those plants, !should awl a devotion to truth? "'0 repeat) such a I ; : Pulutku Elltl'rlri"I'.1\I1I1: I-und, they bo given to some i>oor neighbor; might,; woman cannot grow aid\ She will alwaysIx C-OU\Io;; \ ; ;, usNOTHINti: iigh ooI till the M. Johns' Hivtr.At . prove a great "'Il's ing. ,.\ little time spent ; fresh and buoyant inspirits, and active in BaldwilIail; with the Atlantic, (inli , in persuading! some poor overworked woman the most humble deeds of and benevolence. und West India Transit Railway to and fromI'crtiaiiilina to to a plant in her window I mercy HUT: THK: FINIXT UUANDS\ :\ this try grow If the young. lady desires toretain OaincNville! C Key, and would not be time thrown uwu'i'; and us the bloom and beauty youth, let with steamers! for Tumpu, Key West anti she looked from her ' up at your fashion I Havanii, her IIIIt'id,1 to the of and smiling gift a prayer might rise in her Start let 'her love truth sway and V'irtmieundtotime are keltlmmsttmk. !: At ChattahiHH-hee three times weekly with a (Jive to the little child itsbeauty folly: _. .. . for you. u plant clos'eof lift she will retain those feelings --- ------- I the People's Line anti, (Central Line Boats:! to may often keep that little one from which now make life appear' a garden of .'%(...:.. at ..'nll xu. and (rum Columbu., Eufaulu: Fort. (iuiru-a. harm. Mr. Yick has often thought if flow.cry .. fresh and Al'llal'hltullulIII other River )Ltndings. ' sweets-ever ever new. could be introduced by those |ieoplevvho ': .EItirantlcrpjiigand Parlor (:dU tlie,'.\ r \ ('OSJ'flO( EI: , : ; take tracts to the homes of the poor, that PLATO said to his servant once whenangry llAKJmXlt 11 MKlniir and Lucu Patent, run daily Inween - their vUiU would by welcomed with Inure "I would Lent thec, but that I Tallahassee und JackMinville : am I cuuicEGroceries ; : : ; ; KAMiKUS: joy. The love of flowers ojiens the hearts of angry." Plato was a heathen, !but this incident -T-t*< uick time, sure connection, perlivt'afcty. mot people, and the kind words of the giverin might put many Christian mother to 'fiX H1IKKT-IHON. (!' ElMJAU: VLIET.: (.IK.. .., mid 1'OhM..OIIII. ANII WAIH-;: sink into the IUI.Ithe moat cases deep heart have often struck If'tt Master shame, for they or punished Transmitatioff. | I will linger and keep gooil memory up i! ) their children while angry. Punishment HOOJo'JSCiSU (IT..nBlsCJ.tTtITW.It influence. The room that may \be very Inflicted in anger seldom\ accomplishes TOYS .\XUSCY AHTICLKH.Wtddings '( : IV. K. IIAUK.MCJIIT. ' bare will be brighter for some beautiful children\ to detect .: WOOD PUMP - any good ; are quick passion Kntork : .\'.ENT. bloMkims in it. Borne::! persons+ imagine that in their parent, and note when u blow : Kntertainments; und J'K-II il'll.Cunaihl'llut , dowers cannot be cultivated without. a large i lt: struck in anger. Then, as they express it. the shortest notice, at rm.k-Uit- J' large of .Stovs on band. amount of time and labor Lot spent on them. "Mother slapjicd! me because: she was mail," tout I'ri.t'l s, a c'Ull.11111 (xnui are our prices with those of BUTCHER AND)STOCK DEALKIi.: ; This U mistake of course, large gardens atAXOKL'S ! a seldom\ The AriDirssler and they are not right. original : IIAKKIIY: other hums, here or elsewhere. anti coolly green-house plants will require intention of puni.-hiiic.nt U. of course, to i'entivHtrcet t I -, lu !..... a Ach, but we are dealing now only with a punish wruug-4llillg. anti if ]M, Mible. prevent 23 Opji. old P. O. liuilding.JUT -- TENNESSEE: :/' : IIEKK; A' HPEC'IAr.fS! > few-perhaps only one plant for the poor, O. H. OAKEN . t it in the future. It often en the really i jor. They cannot try. but many: outbur of and the llIII"h- 8TKKCT W If.art could give them a few seeds, a few plant, if meat is but an excuse teinj-r for its J Do T It VTK rtoxTiarrou: AXD UUILu.n.I : UHf FERNAXJMNA. V\*& expression \ would\ only think over the matter. A .... . they lunihlurch your children in atmgm'r. It docs -- ---- -,. - . single plant of Toop'zJuluwijaa would \bloom) more harm than Ioflll You cannot ) Ul't'u'1'l'IIUI JAMES }IrGll'FIS.. ano1l1h..l itt delightful perfume over a room always help being tli- and 'rvukwlwhen l.i\ W. I/JIIMAN.VS a whole season. A few seed of tweet alurn )'*- your children I\\ll'li"I..t Then, wait L MOtTLDlXOS. lUtACKKTH.HAWKI: ) AND rO XTR A OTO R: A N I) nUIIrH' " !> in a box would do the same.! .\ |loctui. until your mind h I-effect collected and 'n itS.:U JI.\I.t'H1'l.It.: ', NEw'F:1r: : , i. nLi plant put into a quart tin-can (front i-ool, then {.. the time for the punishment.Itenieinber -FAMOL'Srreparrd ;- KTAIK HAII.H, WOOD KAVrXortillri : : -- . which tomatoes, etc., may have been tuken what Solomon; "Flediserrtiuu HHI-LVriHXJ, Alacluu Street, between rVtt> )il and TiFERXANDIXA and such are found in nearly all houses), says, Flour. WKATHK1MJOAHD: : 1 l of defcrretu hU and it i b a man anger; .: and given to ,ome little boy or girl with his glory to |irL t* over a transgrewion." t IXU 451'J.AJOH.. FLAOnlcrs 'I the charge to take ('arts"( itand ht you hear I -- ISO will tlowern it bore how ojien ' many frv..h an child., which will linger in the heart and aware in the past few )' Urw. Tht total I I f AMJNIC./" -Ther*' will Ua togtdina'rw: bring forth fruit.A eij-.rt of (cereal in lrw' were 1,'*>. ,noilIi, I A SPECIALTY.IMM1IW : AL munU-ation t if Amelia 14dgr,1'*-, tit liusheU. and\ 159tukllM. o bushel in 11*. In .... I)1... on Monday evtuinjf. 44;"' SCOTCH t'IUB.N'uttl h lady hair 1111.I ; tl jrr JT rent, of the whole nroductwa 'Itt'f OI.Il I' o. la'lI.DIXU. ASH WINDOW FllAMKS: i''d: at 7J u'l-luck. shani. TranrhimtbceciitUW! ( to be conversinjr with a t'ovrifrJouri4irei >> exported and eleven cent in 17*. _. ,, - iiencd |vr --- --- OF ALL "'ZJ-:'''. are Pratt dally in vitoC to attnul. -,rtertbeothy! lay, when the subject The xnortatioiu of livestock have /increax! I SITUS('HIIIKTOTIIK: MIIlioU.: *PKU: l'l..t (diet U'I z 11'. 1 11.. F fcfUTT, UIt Tanners fasting came She did ten-fold in the lost two *'l for six month of Dr. up. )'t'1IN. ; JaM Ftmiandina, Fla. Jour ,. Warner, t+errctaar7 11t ; ..'' -t*. 4, : --. -......., J J 01 T....... .-: ,n j.ua' ... Fern4wiln t i b. ...:;:, . .. f . , ... .-, -.ywy. Mlff M, 1mS' r '""" V, jW, : : : A..aw v t I:' 1:: :: -' J 1 __ n 4:.:: :: :.a.;; *"".' i : i j\;;\"' 1 : < : ::.. 'IT : _- '7.r:: I -... :,:."-...... ,1...'"", ,, , 'ff' THE .FLORIDA MIRROR : AUGUST ,U. ,.. . ---- ----- -- --- "--' --- -- . -- TILE 'LOHIDA :MIR1WJF VACTS WHICH Sl'KAK FOR TltKM- JJ'llJ.1 is IT OUR I\TKHIST TO TIll: SUWAXXLL IlI'.ln. HANCOCK'S AttlLlTlKA '.: : SE/t1"IS., f ; suiwonr? This tine river heads in the Okcfenokee Carl Sthur in his: Indianapolis speechsaid The StateadmliiNtratfonVaWdinto Democratic The inN-rpJu t of tfie cities .larkfonvillc to depredate SATUKDAV, AUGUST J 4, 1x80.1) ./ Swamp in Georgia/ and passing nearly a due : "I shall certainly not attempt hands on the hot January, lM"7. The and I Fcniandimi and of in the Hancock and every county of General: '" -- -...--., .. southwesterly: course! empties\ into the Gulf the character --- Democratic; party were pledged to a reduction Second( PiMrift of Florida, we believe, would he has rendered to which InfIOU\:: : (, 'rl( IU''I'. of Mexico u few miles: north of Cedar Key. the great !services of tuxes and of expenses. They have be far better mih On its east bank lie the counties of (Columbia the country, He is '" The right of trial by jury, the hntirnn' corjntt, been in power for three, and n half years( and ( Finley tlmn by that of his competi! Suwannce, Alachua and Levy ; on the private character which I shall the nf rcch for the of illustration will Jake tor. We have a )Democratic) house of discredit.As . liberty the list purpose Arras, freedom of f]> llepr west bank the counties of Hamilton Madison be !sorry to see any effort made to the natural rights nf jirrmat, (md the rights; of the Republican county of Alachuu to show ('s{'nlntives 'and 11 ''lJellllll'ralicI'nate.:; with and\ Lafa 'ctte. It is! naugahle\ ordinary a soldier lie has shown signal bravery it property, must if pl'r.rterl.-k-N. HANCOTK, how well they have fulfilled, their pledges.The U strung aIIUrnlll'e! fin Democratic l're: -J. in General Order No. 40, Nov." :LI!!), 1807. annexed table" gives the taxes as levied Having n large seabird with many inlets Troy about\ 10 miles due south of Live Oak difllcult! circumstances, and Ms. : name I i- drilling rmi intimidate me from/ doiny! what by thelkpnblicnnState government 1 1873, and harbors, we! need l the aid of the Federal and about 20 miles! by the river, from Kll.i- identified with some of the most tip III1i11IIl'hi'v'lIIl'nts I Mieve to be honest find riifht., \ViNPlKl.H I M7I,1873 and 170, and the taxes levied by Government to improve and enlarge our ville. When the river was! full, .steamboats) of the war. For all this every J SCOTT( HAXC'OfK. the Democratic State government in 1H77 commercial facilities. We have such riversas him. Hut the - have will honor question come up to Kllavillc: but u rock !shoal good citizen ls-8 and 1870.1 It will be seen that the State the :St.; Johns, Suwannce, Withlacoochee, shall honor a desen above! New whether Troy is an obstruction at lowwater is not we ;, FOR Ptt!."1)ENT : taxes of 1873: und, 71 were $18' ,.">8I, and of liitonMihntcher, and other: which. can be is whether tlumtdeserving ]If The this river were in a Northern Stateit ing general. question! GENERAL W. HANCOCK, 1M75, $:!1)Hili.l1) ; that the total State tax of relieved of obstructions! and made of great would long since have been improved and general would be the kind of FA OF PESJWYI.VASIA. 1870!) was $13,011.07: -being $0Mil.ni! ; less per value to the people. If we elect Mr. llisbcc 11l'cds-u President made navigable to the State line; as: it i is, President the country aiiiUim\ with increased!! valuation of$:34i( ),. w e !should! have no reason! to expect that it successfully to FOR V1CE-PRirvIOENT : hardly anything has !been done. Throughthe who can IA; depended upon) : ! rr 000.) Our new settlers will see by these!! statistics would be in his power to be of any !serviceto which WILLIAM H. ENGLISH, efforts! of Mr. Davidson $T 000 has !been : solve the problems of statesmanship: from an ollicial source that it Is. to m in continuing appropriations (for work the OF INDIVNA.I'UKNiDic.vTiAi appropriated at the hM session for its improvement are now before tu-to preserve good their interest to keep' the State already commenced, governmentin : or obtaining new 4 appro and no doubt the necessary things: already come and improve upon 1 II.K: :(;TOKK.HTVTK the same reliable hands. priations. Our Senators and Ilrprcsentatives: " amounts will be continued if our presentable t them. : AT I.AKOK : during the last session obtained for Florida .;..<. ; I-'I' I.- representative of the First! District is returned The New York JleraM says! '1 Iiatcoek'sSherman ,::1 :SAMUEL: PASCO( ) of Jefferson CVmnty.ALDKRT.T. --t'-I-O appropriations amounting to half ; : I.. ;: :: ;; -T. i i :: ;j nearly a as there is: no doubt he will be. The letter "disposes: of the allegation\ t 1 : RUSSELL: of Huntl ('otmty.FIRT !; :,.'': ,- ;:. :') 7. ,- ;; 1-1- :') :: million of dollars, all of which with Democratic been repeatingwith !\ have i ; Sinvunnee has two important tributarics- ; Republican politicians!! DISTUKT: !: : : :f": ": :.".. .;... Z1 Representative i and Senators: may be with .j :: cD I. the thlul'oo<' ice, a considerable stream, considerable effect-and we fear J. 1 YOXOK: :, ofEscumbia County. relied\ on to be continued and our interests y. from he I is nothing but enters: the northwest just above the considerable lII:1lice-thnt ! SKCONI DISTRICT: ,'" -. built up. All of t these public works are of railroad. who has given though I Ito I' I',, bridge at Kllavillc: \ ; the Santa Fe a brave soldier never , THOMAS lKlxn of Ah11'hut: ('IJnnt)'. :H\t1'S I importance I and legitimate objects of :( ;; !: ;' ; ; i. appro. River, which is navigable to Fort White, enters civil questions: and hits! no views concerning FOR GOVERNOR: : : .. h"..':'0'1'.1'':'A' .:';. \.7.. 3.i?!.i?!. '7...,.. priation. General Finley would be in accord 1few miles below New Troy. The' any of the duties tn ,whirh he will hi- .4 I- II- .1 7. :t 'T., with the Democratic in the i WILLIAM D. BLOXHAM, fj- .*_. ---2- majority lands) along the Suwannpc are generally high called, if he is! elected President !save those , .... House of Representatives, with the majorityof lit f rolling lands and,1 the timber management OF I.EOS: : Oil'NTY. pine & is! remarkably touching military the Committee on Commerce and with 1 ; fine. Owing to the want of facilities of All of (General Hancock's published paper j yon 1,1 foCnXAXT-lIlIv: :nXIIR : a 8TE3'j ; his! past t experience, commanding presence, ,, and its 1 of the far and this e'l1l'cil111y-Chow that whatever : main line ',": :1: ; :: ) ; : :' access! lying out of so - \I-- ; LIVINGSTON W. BETHDL, c..... !JI'- ;': tact and social, iiiialitie", would be an exceedingly .... F'. ,. .....O!:. '1:.I':.'-. travel it has been almost a term ineiH/iiita, may be his deficiencies there is no tendency ... i," ':'11- ..,. :. ... .... :: ,,,: useful: representative in M. acting 0' MIIXRIJt c'oSTY .. ., ... .... and ii is very sparsely: settled along the lower to ilcinagogism in his disposition: but ;' FOR ('ONGREw-FIi- 41' DiTRICT : -r I .1.a aci-ord with the rest of the delegation in part of the river .\ number of enterprisingmen that he Is a sincere l and patriotic and straightforward ..... , and with the Congress from representatives! ! , ROBERT H. M. DAVIDSON have settled on and near the river during man, and if t this favorable impression f C> ?l -- 15 -rv the South who have "imilar claims for -' M i'i ir I- .... the past; two and a mail contracthas continues unabated till November he certainly - . years OY cI\JIMHEof: 'OCNTY. l1 to- i 'i ; f. i or..1 ; : .... ; !suitable recognition of their section in the '. '-.', ;-..... .1A ,;..::I .... ._I ,x.I 1- :" ... .. 1 _;'> .'..". "been awarded( to Miller it Hendersonfrom will have a good chance of success on .1 : r- :..: ., ,.. .. matter of public improvement. ; : ;M : : -: : ; I " i ? "U ('OSmtF.IISH IIItTRII.-r : -; s ft, fiT .... Cedar Key to New Troy, a distance of election day t\\t Members of Congress but and are ", GENERAL JESSE J. FINLEY men 150 miles. Persons can now )have railroad. . > ,_;, OF (')LAMa1A {nl'NTY.l << R their favorable consideration. of measures: communication by n drive of 10 miles! from COUNTy XOMIXAT10XS. \ B: ;. : :; before Congress! i is often influenced by their New Troy to Live Oak. The& steamer lira The following from the I'alatka herald i i" .l 1.'LOIUDt CENSUS RETUn'S.Ve 'q. "-1-I P ;-f.t.:; 7r. M'-'I-:;: s ;:.J ?iz personal regard for the member or the delegation has! been put on and will undoubtedly promote good advice to be heeded in every county.Let . \ append the returns so fur UoI: made 4-- :: ..,: ...: .;..: ..; .:..-.: : which bus the matter in charge. This the rapid settlement of that& part of the Democratic party select in every instance - ",'i :;.I: >-f:.- I I i.s particularly MI in reference to the choice its! best! men. We will then have ti of cOllnlll' In thin ; public twent.tive :State : .... Florida. If a branch railroad\ is con..tr\l'h 1 q of localities to be benefited' as all .hate a Legislature which will legislate intelligently 1'YXtI'I:, fLETt'RSIC.OJmUclI. from Live Oak to New Troy the settlers on '': ,;. ':'1 -r. claim, hut all cannot be improved at once' ; and for the best intcrestsof! t the State. Leave / 1880. I Inert Ieer..llac1niti. -( "': ,t; c the Suwannec will be as: well provided for .............. 1.,3fol: l1 1./70'1: : ) 1,912! : ;-i-I.J. 8 !; ;: ;;, they exercise a right of l'llOicI'11111 General a-s those! on the St. Johns. There I is, in addition out all aspirants who have axes: to grind Columbia.' ............ ",W-II : :21,59! !J1 1- '5.... .... :-:: :-:: .: Finley would exercise tin I influence which ... schemes to advance. Select .. spite to gratify or - I . Ihlcto .................. IBj M 110Unyal .,. :-: ':::)loi.:..:-,:.-r.... )Ir. Uisbee 'oulllllot do. to the extensive tracts of good pine land' , At last the sessionour ( ................. 17,792! : 11.II1j.lin): / ; oj< .-r.. ( !! considerable bodies of line hammock on both members of the Legislature on the same r1 1a:+e.antbiu............. 10on 7$17'' :!, 'tltl, ., delegation procured appropriations as the Suwannce and the Santa Fe rivers. principle you would select your own business SI\41IUI.! ............... (1,552: 417: 2.iO.Ionroo : .\ S S follows in this district: There tine at the Lower !! agents, having in view IlItl' rll ',rapa'it.\' :; are sulphur springs .............. 10,9:5'! : ,'i.11.-171 5,2f4: ,. 'Y' I": .! --: ,.; ..; ..; I.'or'It./ Johns bar .....................:$12.i,0i; : > and sound judgment : ('lay.................... :! 7,",,'), 2,098! 9'?I 1-!i .,. or".... .... -.:."y. 1 _::. : I. VollIjla:, bar....................... S.OtiO Springs and White Springs within a few " Leon ................... :20,329:! t.'>,2JH ;3,092't ': .t.:;; I ": .".:.. Ifi. ,"f'5..:.".:00.... .7i... Inland Passage................... 7.000( miles of Lake City. These springs: have a -1 word to the County Convention. When Oudsc1c.n............... ."". ... meet, nominate good men. Don't put 10.5.1.. II.HO: 7illlIallillllll. '. Cumberland Sound ............. 30,0(10( good deal of local Celebrity in cases of rheumatism you j ............... 15rt4JI} 11,111: 4,3$3YOh1Mia / .... Lighting St. Johns River.... 5,000) any man on the ticket for mere party influence ............... a.tu7! 1,7231,8-1 etc. The Suwannee River, so well whose record i is not good. If there is .1 : : : : : :0 : : 's )01 : : : thus'providing for the improvements . more important p ...:? ) 3,0111 1,2'x:! J : G : q q'y known in song, is: destined to be well knownas any man who would throw his intlnencc i i i i i i i 1 \"alton..1 1,711! 1.2"'tfJ) 4/1./ '}' : : : :ii : i..F, : : : which had been made the subject a desirable part of Florida. In addition against the party, simply because he thinks 1,44)! 1.2111 :?i3' : :: : : j- : : !; { : : : of examination and survey. A Demo- his: worth i is not appreciated, let him slide. f' '"i i nrevar'l.\.1\ 1:17:!: 1,010, 11'171 : .: ::: : :.j.z ; : : : : cratic member to the& Km we are informed that the steamers You: can better afford to let such: go than to of : : o: !: : : : : : Congress! will be able, undoubtedly I). L. Yulee and l Krie the hold to them for their 3 [,1'vy..1 4,7711( 2,011'1 2,7)1i, .. '" <:! .. c .. .. .. are running on on supposed: influence. ,< )tl\rlon ........,...,..1 Ua7U IUI<0 '2: -QI; ;!e j g i'a"' ';i i i'_ 1 1 i to obtain, the appropriations to river as! freight Lout! The party can afford to do right. //'It. 4.iU..UlH' :!. lm71 .=. :'l.t J.! {, CQ_: 1 :"== = : : : continue all these improvements.! )Ir. Itisbee: There ore men in the county capable of legislating - "' __ . JOhu'II..1 2.312 1,323: : 1)$7I ) ; twaro-: :: ..: d 1::' :'0"d =:: f! !.i i8i3 would be practically useless! ; he would bothl' IN It Alt TASTE. i look round honestly! and and figure faithfully. this It Is time to - n.170 1,41711 C up on : subject. 2rJU.'i QI; 0. Co : < 0 :: i' : = I : td-l--I = .M solitary Republican in the Gulf /States The candidate for in Soon our candidates will be in the nn.i .rl'tfcl'l'lon' ............. 10,284 13,3VH, 2,848 "" I Republican Congress! field I / Lafayette ............., 2.1100, 1,71'1:1: 1417uwanncc r.=. .. if; ; I =; :I Co.e :( .. )01 and would naturally affiliate with, act with, the /Second District seems!!, like Dr. Cunover then will come the tug of war, whl'nlt'will m .... :-; ........... 7,3.10 afJ' 3,7H: 2 a-s-ss-ag-jg a-sSi? and be classed with his Republican allies of be expected that every man will do Id- and )Ir. Hicks in little ' : ...n..t1 ....... .. ........ .5. !, to indulge a dut . i ()rnngc ................ 3tr90, 2,193 3, -: O'SOOO-.aJS'- :.-: .: .= the North, and however desirous to do something ) j _ brag. In recent card he "The simple a : -- - I i I101,214 I- h .. .. u u- S M.S.= says 142OI.i,110.3,3t:! : 7 jSJSJ i(Jf S&l-S (J'. ;;:: la for Florida, would be iwwcrless to do truth is the Second District is entirelysafe .1 FALSEHOOD SAILED. "' '\1 In two rountlc:4-I"rlon: and Al"chua- s = t-: c ? 399 so. As! u matter of prime interest to Florida as against all honest exertions: which\ ST. AuorsTixE: Aug. 3d, 1880. o = =.nnoL qM =-4. General Finley should be elected. We cannot Editor Union; : I am informed that the Sun there 1:4 decrease In Ah\lllUa the Democrats make. but the ;," : an apparent : ;%; ;t; ;t; ::to can Nothing& and Press has county of 1,942, and In \111r1on of 1,425 since afford to gratify Mr. Uisbec's desire to basest frauds. and\ foulest crimes, which heretofore indirectly newspaper stated: that frequently in a speech directlyI1l1lt made 1870. It !claimed: \ that this: is not so in I7I'OSB IXJUXCTIOX. take a scat in Congress or the desire of his: have honey-combed the Democratic by me at the Democratic ratification meet Marion, and the result will probably be disputed Our railroad prospect arc tied l up, and we Republican friends at the North to strengthen party, can defeat the Republicans in the ing in Jacksonville I said that I did not in Alachua. Orange is: claimed to know not when that tie which Mr. Yulee ,their minority the House: of Represent Second District. The only safe rule for Republicans cratic want "colored candidates.men" to vote for the Demo fa tened hy injunction giving him the I wish to say that thi have 7,000 instead of :5,01)0) us we have it in control of the an Internal Improvement, Fund, atives. __________________ is: to find out what Democrats statement i.s altogether false, and has no the list. We have great doubt as trt the will he untied-Vnlatka llerahl. MANUFACTURE OF SALT. want you to do, and then do exactly the re- warrant in anything I said there or else v I'' reliability of these returns.Leon county i.s We have no particular! information on the In Canada salt wells have been discovered verse. When you see anything in a Democratic where.of I the did State say,that comprising in the almost Democraticparty tin- put at 20,32K.:! The Floridian, some time subject, hut we think the herald I b very fur and the question of utilizing them turns on newspaper damaging to the Republican entire white imputation of the State, almost since, added up the tables. and made it about from the mark in supposing that Mr Yulee the cost of fuel. To use cord wood or charcoal tause, take the exact contrary to be true." the entire intelligence, wealth and character 10,000.! It is hardly probable that Leon, hat obtained) any control of the Internal Improvement Is too expensive: but by carrying on the It seems: im]>ossible for Mr. Hishce to be (ol'OulelI110Ile the people find of the State, the colored people which has received but little immigration anything but violent and aggressive in the protection for their right ) Fund or has tied it up) in any manufacture by means of exhaust on live : ; and aid and encouragement in educational z should have gained nearly as much as Duval. way. The eventual effect of the injunction steam produced by the use of sawdust and brief paragraph above he charges the Demo and industrial development. I did say that We see the results in the Northern obtained hits instance against Mr. Vooe's othl'rwi"e1I1n'le :! debris: of saw-mills: the cratic-Conservative party of Florida, comprising the theory of popular government and of qt; States have )been generally given, and we transferring the coupons in his Nanny we manufacture can be carried on profitably.Is the best the ablest and the most our character institutions and religion required\ should that intelligence.! hope that we shall soon be furnished with a should KupjKwe would be one tcp towards there any reason why the bait water in honest people of the State, with being "hon direct public opinion, and that if-party control based and I semi-ofeial statement in Florida. The following untieing the Improvement Fund and hia.sten. our harbor cannot be manufactured into ey-combed" by the basest frauds: and foulest upon the idea of arraying the colored people fourteen counties<< not embraced in fug the i-oncltis'ion of the litigation rexpccting good salt by using the sawdust and slabs crimes," and charges the Democratic the against the white people of the State upon that the list-had by census: of 1870( : with falsifying in all matters damaging ground the freedom of the coloredrace ,. Mr. Vose's claims. It U very desirablethe which are now an Incumbrance to our mills? press came from the Republicans and would! Calhoun iris Internal Improvement }'UllllllhoulJ bccll'arecl The salt marsh back of the town which I is: to the Republican cause. If for instance not be safe with the Democrats and the r 1 Hamilton .-. :i,7 4t) of aid in to the mills they publish the Poland report in reference white 11111'11'-11 party appealing to !I ... 2VkI : the cnbarrosMuenta: so as to new proximity large : would afford dice and ignorance and distinctions preju Hillsboro 3,216 and much-needed improvements.THK admirable location for salt works: if it 1 is to Mr. Garfield, or the DeGolyer re- to make a of race party organization to P Holmes .... 1)72JacklkJn. -- .- .. practicable to manufacture salt here out of I ptlrt, he says "the exact contrary il is to be assumed. political i>owcr of the State, was of control necessitya Un 0,528 I : FI-OKIPUX WHO HAH NBVKR: E:,TKN: the sea water. The importation of wilt dur :' ____________________ great wrong to the country and a great in Manatee 1,931folk jury to the colored a,UIU1'utUI1I11. I (''LIMS WHO w HE?-The New York lltral.lcouUiinsan dog the )'l'arI147$ amounted to over a million DEATH OF Jl"WE.nRThe Pcnacola say that the votes of people the colored themselves. I did .? 3. _! uirount of apolitical clam-bake. and u half dollars in value, with a duty of Giizette contains an obituary notice of Hon. not iieeetttirytn the success: of the people Democratic were Among/ the shaker General Kilpatrick eulogireil eight to twelve cents per one hundred O. M. Avery, Judge of Probate of Kscambia party in this State because of the large Dem- ',. l uy lorWashington............................................. 1,453 "t'he-ter, Arthur as the first man in pounds, about t.wo-thirds, being im]>orted in county, who died on the 4th instant, and ocratie far from white saying majority that I did in the not State; but so f" \"ukulla...................'..................... :2,50(1! : ( New York to favor negro citizenship. lie sacks and the balance in bulk. During the speaks of him in terms: of deservedly high: of the colored eople, I said in want express the term votes,. .-1 ... 2,302 knew him Wl'111l1l1t was glad to have mmd- civil war all the salt required in the Ou1E enlogium : ; as I 'have always 1 Maid and I do here now ,t I eihisuumitination. Ks-StateSenator: :; / KitlN, States: was: manufactured on the coast. Judge .\ was a native of Connecticut! say, that I regard it as an object of great im- ( ..43,44' of Florida, mid his State was I'epnblican I .. -... .. .. and at his very death was: sixty-five years old. I ortance to the welfare of the State that the \ The net in the in the list colored people should < I gain twenty-live time. The custom-house delegated FI'INE.-The; editor of the Sun and Pass, Early: in IIfo he came South, and tirst stoj I: vote with the white every of i is 4 { uPuver of j people the State, and be accessible to the : ,913o .or an average: twenty-seven ned in Mobile. When the railroad mania from New York "A solid South then pounded the table with Mr. :Statin'scutlery ; writing says: influence! which create, control and a ceiit for Pensacola in 1830 attracting direct per cent.adding thirty IK.T t. remaining was many j er- and yelled till thl'1uu"uIIl'lI\'tt! their and a Democratic State; administration for sons from all quarters to our old city he intelligent public! opinion, and that they counties would the should give us population be ) & mouths inch wide. He said he had eaten Florida means a small winter business, littletravel came, too, and ever since has been one of emancipated from the control and; of the State alwmt 250,000) ) which is \ OOO influence of all Persons of either who \ her most industrious, energetic and active race ( lams before but if the club would come to no considerable immigration for permanent appeal to them for their votes less than we had anticipated. If the ratio citizens, in varied employments in both private of on the ground Florida after the election he would give purpose*. and life the gratitude fur the gift of freedom or because for the House of Representatives. is tUed public always exhibiting of the tht'Ulall orange dinner." Who w exSenatorKielU : For nearly four years there has been a strong New England force of (character and prejudices growing out of their former ,4.! at not over 100,000 we will retain our twoCongressional ?-the man who lives in Florida andnever solid\ South (whatever that may mean), anda marked observance of moral and religious therefore relation to the that white the people of the State I districts. say statement which ha ate a clam, and who Mays Florid i"Hl'l'ublil'UlOlllt Democratic :State; administration in Flor duties! -- been so repeatedly made in the Sun and Press 1 invites the ]11l'tlpl10 a dinner ida. It I is: a matter of public notoriety that U\1'TlofT STATE ('oNYENTmos.-We have received III 81) many forums: both direct and Intiirtct r I'OLITLCALIIAmu-IIOOK-Wecall: the attention i" entirely fal..... J of baked ? the immigration, the travel the hU'rl'U"of I i ' the oranges the proceedings of the Florida l Uai>- I am sure no ... of our readers to following notice of person has kinder feelings or t a valuable publication about to be I issued by business has been greater during the last tint Coniventiut, held at Tallahassee, Flu., a greater desire to advance the colored Ill"- WKhave to report more falsecrediting.; four years than ever before. l'rl'idju't'ha January: 9-l:, 1*"tO. We should have sup. pie in permanent and real prosperity than the Washington lt : One uf the ablest and \best printed pa(>ers in : kindly milcd on Ik-nitK-ratic orange nixed that the would have been myself awl this feeling r know if enran- i The editor of thU IUIH.T has waited for the the :State; credits to the A letters of acceptance of the different candidates i- lumber article from the flnsettt \\ hid, Inv &groves and Republican orange groves and primal l in Tallaha-.....ce, where we are certainit Yours WH.KIXSOX CALL.State i before issuing his sometime announced volvetl considerable labor. Ho carefulbreth Greenback orange groves liven Mr. :Sherman : I could have been done as well, and have I, _ political hand-boot but hopes: to get it out r'n. is i"t *np]>o cd tip have exercised any I helped our own industries. The statistics" STE vvEK nLOW lp.-\t.'w Orleans 1 of the hands of the binder by the lost of this l'IIl'n looking over our files we find that ,, influence upon the climate, and'people will I II given show 3OO churches; number ot white j formReol Rim Aujr: make book of three rawi yens week. It will u over slug of 'I h assorted in ouri-wutfof July we ,'ro.titl. l to the under Democraticeconomical : < come preferably a good colored 1 a ea and contain in u connect ; menuVrs 8,410, 8,770. merchandise l blew form about all the political' data needed by A>tfuuceun article tliecnilit of which .should I I utlnministrutiunuhich will maintain e\euing. at Lonewall up Landing.and sauk Monday: Democratic speakers or editors and oughtto 'liave' been given to the #;tCZttfC'. Wur\ :: a system of low taxes and good law WE h H-takell MJUIC jmins to procure and time S''uld clerk' trim killed and'Jef.1.1'n1 . meet with an extensive sale to Ill'! remunerative aware of the trouble the collection of vulua- Wluit Useful) purK| se eau be uherved by publish a valuable directory of njm.e and :< of )Ir. McDermott i u niNsing The boat i stn* u commeniurately. llound total boss. t (:ViC will or be Mtit to any addrci* at the I i blertatistits !hl\'ntH'SI11 regret the unintentional such palpably). absurd statement as we have I residences of the :State and county officials :, inU1 in (She indnnati way ,'ahlel fur$"(.at $1.ul. and I .i" um'C of the /tof. error notiix-d aLoC.,7 I 1uutl..1 we cannot conceive. and of the terms of court. llf her <.cargo i ii unknown. 'fhe"ahu' p 1 "'(f ' r.J'* ..:,,_. -- .. '. _. '......." c- ...... .. ; - : "! : <:r'1 L :: : 'Jh ;il \ ,, ::"': :: =.-...' : --.v-:: iii ; _________ __ ... -V---- .t. % :- ; _______ w- .- : : f . _. .. .... . ' ' \ D THE FLORIDA MIRROR' : AUGUST 14. .' -... ___._ _.____UO__ ._ ___ ..__ ., ., .-- -- ----. ,- -- -----. '- -- ... .I MISTKKLV .I ;TTElt., 1''l':>Iiol1'lIt. That wmild be right enough for POLITICAL XOTl'.S.: that General Hancock's rminstjl ww not as I 1 min cannot carry the flth against" tjieWhite Shortly after the nomination: of General; the law provides that in failure to elect hilt: u'ioti'aRy sought as it wits pntri0licellygiven Leaguers aud. 1,it111mzeric- Hancock atCincinnatiit wiischurgcd against duly bv the people\ the House: shall Immediately THE H.). ton lt suvs : The Republicansdo .1 I t ':They ne\rmlC tl Jlorill., Mr.( lick", him that during t the dl.'t"ralc'rl"l' of 1 CIJ-", elect( the President and the Senate the not know what they) are talking about So much for the ln'\m tulln,11'r of that State", inttrll' ; II fglll lie had written a letter to UI'llI'rlll111'1"1111111; ; 1'ie'-1'resilent, Some tribunal must decide i wll'l they sav that (1'1. llancoik i is not a which the letter was ; and! now, as back there. (Applause.) r in which !h" had, hU'I'IIIIdl'I'Ie'lll1 How isn't Hancock's .May bo not; n.tlrh'll the Tell made known his opinion' whl'lhcrthcl'cople President. : .lnh':>IIn. they kioI( ? to its substance. General frlcnl. 11'(11. on the .1i"l'"h..I.ic.l'lillllllllll.ll.l'III"l 1\his in ( I presume, of course: that it I is in the Matcsinen are lot tlLI: 1\ I ; I hl' are I \\'II\nr Invoke public judgment whether "but tl'iey are 11 over the, rest of the South tention tosni.ji..rt Jlr.'I'ildcn'sehthn if the joint afllrmative action of the Senate and, I born, and General Hancock 'has i\11 tbestrongest 110"1 lot \prove him to be more than a fir Conovcr, FIlrlt., again took thefloor latter chose to take I the oath of office. I It t wasclaimed House[ or why are they present to. witness: I presumptive 1\jll'II'I'lhlt he lucremullierwhitknows, nothing outside of at the ('nIIISiol .Judge Freeman'sremarks. h%' the Republican 1 press th.it this the count If not to see that it is fair and I just 1 :sesses the qualities I"tl li h tiicm.Iliiliecontraryartield's the litaintIpf military command I and obedience "I object; he began, "n ain't tti - letter was little holt of revolutionary 1 1\ it ,it t.< I If 1 failure to agree arises between the two (; :I11'11'I'n'I'I -whether, 111",1.; i does not prove any one speaking for 1 State which he m - declaration-iand that its publication 'in full bodies there C'.I be no lawful atlirmative of service have \proved that i 1"01' a pol him to ha\e hl'I'1 I conservatiNCj nigh- does not hcltl11elk for Florida, and I I would greatly' ilamnge\ : his chances for the decision that the I'l"\\\ hate elected President I itician." minded, cool-headed, law-abiding citizen in say that the Hepublc'ul, candidates will Presidency.General' I and the 1".1 Ihl'l proceed to one of I the most periods through carry that State majority. In that ( llancoik being spoken to I hy a net, not the {'lall'. The cnate elects 1'icePresidents unconditional TIIK llrooklyn withdrawal Kt'ilr, in speaking of the of thf which tin* republic IIiou' (t'II 1 I 1'41 State we intend that the campaign shall) be than has New fork Jlei-'ild on alllr.I:1IHII. I not I'rl.i.It'II*. Doubtless: in hol1'I'Ill'dnll letter which displays !something 11I11'1 than l'Illll'llll n different manner this to say on the !rl'\orll'r\ : caseuf n failure bv the House: to elect a President til'klla !I : The { : common scow: It (testifies t to the )possessionof Ilretoflre hl'I'1 the case. It is unfair for "I by the 4th of the President of pivotal 1I I probably controlling State in of st.itesm.UKship much Republicans, to say (that White Leaguers ami ' hardly rcutetnherelwriting 1 the ral'h. qualifications he !said "until I saw reference;to it in letter the Senate; (if- there be one) would be the the I'liion I Is IO101 011Il1ih'I, hit enthusiastic more satisfactorily than the letter of 11'I'c'I"- bulldozers terrorize the olth. It I is unfair 0: some 1 in its of andKnglish. legitimate exercise Presidential support 111HII.k the Cincinnati nomination. alike to Southern Northern licpublicans. - "t' to ( t the : When I person uII'I'lf alt newspapers wrote it I had! l In this Yorka1llnettbeclass1'uaituathetim "il'\ What and what we mist: 110 idea that it would ever he authority for. the time being, or until thenppcurume l is ling in some of its \iwssajjes: which we 0 published. I I WIIn a Western town on business of a lawful President, or for the I II hI ril States, sounds like au echo of the !spirit of the great have i is the earnest un.llch'e cooperation of !1 Ni with no secretary or ineinlier private vf \ time 1111.10\\1 in the constitution. Such even by the most, sanguine 11\uhll'nl\ *. I constitutional t era of the republic, the era II the North We hl\'e llrl'I.lv the moral support : stall'with !\ > ' lily * peaceful and. I firm nothing Infor{:Il''III'I'I'I lltl'"f and. Jefferson. All of of all thegood )people of Florida. Therehas n\e. I wrote it frankly' and with I'OUI'tul,1 hI'I'1: Washington nC'I'rllJnll'k'IIIIlbh,1 noconstraint. York i is > Hancock now as! :11f. til as against change in the sentiment great public far and tins : - 1.11'1. 1I\fll papers' to II'1 1 ( State in the is "And stick hy what you wrote. ?" IH 1\ ibt Governor; lta.\es would Oartl'll. as candidate.nn1,111'1'. \101 1'\I'I'il\\-: \\h.ite\er may be his of our people. Pour1Lr ago we "I never wrote anything 1 IIfruill1f make an excellent President. 1 have met there i is no tendency tl demagogism were mcreilesslv assailed by 11 the epithets am ; having known and that 1 \would not :stick : him ami know of him, 1'nra brief, period i AWITI., IK Trn-Olc: hundred thousand in his disposition, hit he I is usincere that could jm-wibly! be applied, \ Only tit" he, served under \' l'OIIII.\ as the patriotic and the other day one of our enemies made I 'h' desire inollice. more or :>I", to stay Mlruiglfol\llll\11 ".\1111 you desire: this' letter to he pub I matter stands I can't: :$11'1 any likelihood of ulke.h"lkN. and if this favorable ill'r'I:1inl 1'lllilll( speech at Jacksonville: in which he said, I lished!' ?" his being duly '\declared elected!; by 11'people\ To accomplish this t\.y 111 such unabated 1 till November he I'l'rilil' will 'If cither party can't win on its merits the' "i only' waited for the consent General( unless the Senate and House be in stntFas this : have 1 good chance of SII'I'I':4.: Oi "jlr deserve defeat, and if there arc any bulldozer (-' :Sherman; anil" that having been !given there accord l as to that fait and the House would, In tllil the South was :solid for treason: and day. ______________ they ought to be all condemned.und i1l1o obstacle against! its: publication. ot'l'ollrl', not otherwise dll.t hil'h,1 rebellion : and its hope to :succeed in the Those are liiy sentiment exactly, mybelief the i is UK', ir. ir. HICKS : i>/:. cox- that will have fair count in November The following! u the full text I of the let- I people want I pC'II'fllIlI'rlilltoll destruction of this republic1' was hll'I.lon ./ w t' 1 ler ufthilath'r. as rnininl its l Is bused upon} just: such feeling as i i1'ilC'I.t is : faira.lll'rlinalinl the aid and comtoit )> i by political I Ol'Kll YOKK. C.VlSOMiKt.KT: : : 1'. 0.) :silile and a lawful 11'. Ilhl'r ,llc'rlintll in tbe orthl'r llh'! It is 1IJ Conover went in the simpl' little' speech h)one of :ST. I/n'is, December.o*, 1 tiff;. \ could :tand I the test.: Tie country, if f In ul\orll'I':() sale South I is solid to ruin (the I \\1 knlwl tnt1' t 1l'lul'l of tl 111)1 Irl . Jl>car fienfral: Your favor of the .Itli l\t \hlgl.llntu revolution, become: same country by getting possession: of it ; North recently to 'funds for his campaign I I is understood tllt )' got the resolution lust: rl'lwhllIIe in New York on the ;.th, ", ; I business, wlu1llalglbh, and its :sole dependence is the second time in I FI.r tla. We I find in the New York }" pulsed, although there was evidently the day before I left for the West. I intended 111,1011' bond WO'aII'OIC. I.nlll' lltl adepreciated "lllI same class of ol'I\1 allies, who "'/ u report] of I the proceedings : little faith to these promise Theyhn,1 to reply\ to it hl'forcc'U'ill\ !;, but cares incident I: I was not in favor of the liluf' action have friends again the bargained at to(j1\vutiogprecincts 111'ir ollhl'r The resolution, as uttered by Dr. l oring, just jI\1 result of the aid they had to my departure\ interfered. Then : in South Carolina ; triumph ,provided that t thl' National (I'uittuitteeshunlulx' : SI'I again since my arrival here I have been so: I telegraphed I I to lecently me, o'r; asked nll for advice Rugerlead blood.h'riiu'iiiliirttili which. was lost: to thl'l on the Il'I,1 of instructed to give all the aid in theirpower given Weaver in Alaha ita. occupied 1 with \\l'rl'ollalllnhi mil'a business: I Iwould have advised: 1 him not under to IIulhl'r Republicans in their aliteir1'ittlstluces OithiJoitii-sitfinliTtonilintf:* : nature that 1 have deferremlwriting, from day to allow himself or his troops; ii'iinlal of the .V'/mt; ; to / nation! campaigns.Senator i Tin: KKY-XOTK OF TIIK C.tNV1SS.'fhekeynote . to 1111IIlItit this moment ami! now I tiuil 1 / dcil'r at once j to his feet . to who the lawful members II' into 10)11 jllllt'.1 of the ( .lll''I Wl'rl rilitliniiili. ( : *, myself in debt to you another letter in \ when the : was H'lublcnl 'RnVI:4. knowledgement II"I I of a Legislature.! I could not have Such is! the present: crisis i to which the nation \ opposedit according to the New 1 is "the of favor of the the (lint ( 17th. on ground your i given him better to icier him to lias for almost hundredjcars. tll'laliolulCollli.tlI' it I is worth the received, few \lvil' Ih.1 11'1'1 coming t 1 question' whether really Iilll'C. be days : : , the :> !< of the President ill the might hIIPI'I'I't} III to \leave here the Illl'ialllll' agl .-Krir on 2litli, 1II\'I'I'OIlC'hl'h"1 : took the same view ul.II'I\lrl Pierrepont l'II'l i some I time i lief ire, Hut in to the Democrats, considering the noon so that 1 be of the matter.Wiljiam . may \ South ( had, the 'question settledby ( ; :: : SIIKKMV.N: L their and York the : inst. has 'urnlllll 1 nK\ :nI.ll'nl'I'alll'lulk miscellaneous make-up of party on list It been cold and K. Chandler before t the i a t Com t of the l i for the t at I is ,1"C1\'lol . , l.tbinn present Portlier the obligations it will incur in event of uviclorv .11'1'111'illce my arrival' here. I have worked, trihutual1'llitwhich had, advanced nnv drew Mate-the highest I of fortune. Right on Itl'ntoll Il ) achieved coalitions with huIIII',1 by wU.ll'l'llklr like Turk" ((I presume that: means hard on the question-so: : that line .1.1 heels of his letter of acceptance, of the the presence in the 10"1 of !OIC newspaper \ Protectionists . work;:) in the country in making fences..lit. Ii. .Iul' and warned t those present t Pennsylvania , !It'ell'III\'I'n to be clearer the Cincinnati I nomination-a document r'lorler lltIht.y ' ting! down trees, repairing buildings, t.tc., l\tinl rC'IHI11,11' : what they said I to be reported. lililIlItlllol1 tl and Virginia Rcpudi- F the I 1/oui-iana . l'II' If the Federal Courthail in its substance, :>o far it goes, I'XII'I't that "at is not worth thewhile" etc, and am at l'u tuleto'n '.th lt,1.: Louis: interfered the decision ml'the short of its has I TIl f falling +"t'tuttity-chug" IIJ1 n\'I'rl'II.,1 ul.l to turn out the Republicans and put i N the coldest place in the winter and it I i< ;, "If that I is the Senator 1 logan remarked ; State Court have enabled the of another letter of l'a'I. the hottest!' place in summer! of any that I tl'I'I'.llilt! htI'1 adoubt 1Ihllll11 I have :said 1 till 1 to say IItlii's in the 11'101'ral is I is scant campaign material - his andmore {certainly Lit Fl'\'rlllnlrt 111'1III'rfl'rl,1 explicit prolo"t' I for and has gainedputvcr ' have encountered in ) 11'an'r.ol'l' party gained 1 conference. 1 a temperate.one.\ to (complicate, ; t) everybody might thingsin \ I lt 1 .I iI"I'Ior Ilo I'tl'r by bold aggressive ', HO con h.nowl.1. .St. Louis in December to have I overrule.luyhow. who the H secret conference that 1 would I not sayin I pOll') genial weather throughout the mouth this! w thlt 1'1'1I'alloilule 1.11' a public one, and sure that we will l'I'iwIII:'! to arouse the feelni' III touch ; :' it i is no business! of the army to sbalj : 1111 possess\ \ \ 1rO'I.dl'U.Pa.i the prejudices of t the . 11. ilc'lIlallt"l' 1'e December has been frigid and the river hasbeen if all be iuiguanLl! ,_ cuter such questions, und it what upon C\'I'1 fr (h'i Illin\lrltioll. The States are Democratic frozen more solid than I have ever might be in it' the civil he be followed most discussion. olliherl uniformly) known it1Phen so, ILIt''I'lt, authority 111't dtZl'l. Il' H"lllll'll or he Thl'l 1 extraordinary for two reasons! : 1. Democratic rule, I is Mi supreme, as the constitution declares hol"l! entertain ])1'. Luring defended his i resolution which is a term for the I heard the rumor that I was ordered it to be, the South 'ur"litut'use: was that visit ? Let any' man Wll. on searching but he was met on all sides by oppu'sitbolt. i. in local synonymous attains of (the people who supremacy know to the I'.icillc\ coast' I thought it prohn-- in which the had Mr. W. W. the member of the one army a }plain duty. his heart, detect any III believing 1II'kt, most, think most, work and own most, lily true, considering the past discussion on Had (1'11'ralllul'r u..kl.lle for ahil'I'.li,1 ill of any Piesideiitial candidate, us National (' Florida, was the given them cflicient and lot economical that subject. Tie( possibilities seemed to me if I gin'l I. should, of course! have tocitlien character or ability,i ,quest ion himselfwhether first! to be hl'll1 He l is 1 very strong and with public peace the faithful government administration to point that way Had it been true, I notified you ( my ICOI immediately, so he i is not i I danger of sacrificing his ardent As ho rose he was recognbjcd of the } of should, of''ours! e, fuse presented no complaint t that it could have been overruledif I his Mr. and lanlli security person promptly, patriotism to ': !' liH he must hy Jewc'l, great applause ensued and property 2. The Democratic nor made resistance of any kind. I it should have hln deemed advisable by 'believe, so-If facts force on W11'I, opening sentence, Ir, the party aim represents would have gone quickly, if not prepared; togo you or other superior in lutwrity. General his rmasoi-let it 1,1 1 source lt'sorrow unalloyed Hicks IlnoUICl't that llorlllWI:sure for which hU\'e'L'governmental their aim principles the perpetuationof policy promptly. I certainly would have beenrelieved did ask fur and the of linger not 1.lvice., I inferred with the slightest gleam of pleasure e the the individuality of the States without from the responsibilities!' and anxieties from that and other facts that he did It I is:'! by no means the least merit of thenoteworthy South," continued Mr. Hicks, "feel the responsibility the concerning Presidential matters, which nut desire it, or that, being in dir'c communication letter addressed by General Hancock that has C'CI placed upon her. weakening Union, or while{:compromising the Republicans solidity under thepretence ofthe , may fall to those near the throne or in authority -. with my military at the to General Sherman on the 2 Mth of December All the people of that section arc aware of of the within the next four months well scat of who \ lu\I'riol him the fact that in where Re nationalizing; government, government- to <!, which the yesterday place \ lXiI t113'lV 1 lmlllll'rintcl gradually the active life of the States as from other Incidents or matters which I destroy in time and distance than I was-he deemed thlt disposes of Republican :'! nourishing as it 1 is in 1M and could not control and the action concerning it uuneee!'tarry:'! As General linger had the politicians have bl'l'l repeating luLlcallil :of the North. Despite) this, tai prepare suited the way centralized gov.frnlent to dictator ending which I might not approve. I was not /?x. ultimate responsibility of Ictonuu.l had really with considerable effect-atid, we fear, with )however, the Republicans of the South do in a or consul _ actly prepared to go: to the Pacific however the greater danger confrnt in the considerable malice-that he I is:'! nothing but not expect to be left without the aid of the I monarchy of some lort. Misruleand and I therefore felt relieved<< when I rt.'CelvcllyonI' final action in the matter, I llitnutl'ntur a brave soldier who never has gjvcn thougl North. They had a hope that they would the ) extravagance IJll corruption, note informing me that there was untruth by Republicans' gave the Democrats the to not he deserted and emLarrn.'JI by tu c. W\S a to civil questions and has no views cOI'ern.In left entirely to the mercy control of the Southern State.Nor is it in the rumors. Then I did<< not wish! c'omuuLIll'r and the lawful head }, any of the duties to which he will be of the Democracy.)'. So fur as Florida" is fear of return of Radical u rule alone to appear to be escaping from responsibilities of the military administration within the called if he i is elected President save those concerned I want to say thil: If you give us the rememberance and of IIII< around military commander in the East: knew that he had been culled to Washing Hancock's command! of the Fifth Military to aid us, then the State is yours beyond all Democracy are all- especially'ln the critical period fast: approach tOi for consultation before taking ", comprising the States of Louisiana doubt. Ilut I will say that whether you powerful in the South because they have ing. "All's well that ends well." knew that he was in direct command COl mi, amiwas Ditril! the troublesome winterof help us or not, whether you extend to UN the proved their ability to lighten taxation and 1 The whole matter of the Presidency seemsto probably aware of the \'lcWI of the administration I- 1M7-M! is! cited by his:'! to be same comfort that you give to other Statesor remedy public ills. In South Carolina, the Ulholl'r to the ) saving me to be simple and to admit of a peaceful' as to the ch'l alilrln his com sure, us u conclusive reply)' : lot, we will {carry Florida for the Republican tuxes alone people in three by Democratic rule inState solution. The machinery for such a contingency mand. I knew that le WI dir't communication but in our iudgment his canvass, as it progresses candidates by at least 11,000 majority.My and years, is over twu million as threatens to present itself has with my Hupl'rilr in authority wir rely even more upon this Sherman friend, ex-Senator Conovcr, of 1"lnrlcll. u quarter dolar. Even such been all carefully' prepared. It only requires in reference to tho ( subjects presented to prove the maturity and the I is here lie is u candidate fu the (f in rejections the South of public debt luLo taken place* I lubrication, owing to disuse.: The army for his:'! consideration, or hud ideas of Ids soundness of his thoughts upon high and Governor of that State, and would like thiscouference are a present relief to the p. should have nothing to do with the election own which he believed to be suilicicntly in difficult' points of cvi government.. In the to 1"tcl to Home remarks:'! from securing them either lower taxes titan( or inauguration of President The p people accord with the views of our {'OmOI superiors North, at l'a'4t. rC'l'olstnlrtol period him." something cllt that they value more elect the President.: The Congress declaresin :'! to enable him to (.t intelligently according which { tho (' I very long Mr. Conover I is 1 born Southern ontlr, public crcti. Where there is complaintagainst ) u joint session who he is. We of the to his judgment and! without suggestions way off. A large portion of those who will When he IJI.akl ho gesticulates with his (emorat, as in Ylrglnla it'is: army have only to obey his mandates, and from 1 those not on the spot and not vote here next November has firgotel the head and well as with his hands. ostensibly : party gone are )protected in so doing only so far as they as fully acquainted with the facts !himself. intricate lerplcxllcl of that tile, nun! Indifferent The f'larkl of Mr. Hick had )produced a far enough in effecting retrenchment and i may be lawful. Our commissions: expressthat. :'! He desired, too, to be free to act. 1'1 he had the, ilyect not to care vl4lbll! impression thc 'o present, and not becau.it there is with the mae any desire I like Jefferson's way of inauguration; the eventual greater r'pm4ihiiv.! and so to make the effort to revive ali comprehend 1f r. Conover followed up the ud vantage with to give the Republicans tie control 01"the it suits our system. He rode alone on horseback the matter was \' \ him them. Jut the 1'01'101 which either bus a wI'l )(' of ten minutes dun State. The Republican (campaign i to the capitol (I fear it was the "Old und IIlclf. -"-*! .IP, i,ut._... .,, tin. ..., if.f.. tol. He called attention to (lie c'olditlol therefore, Is not united to the luutb. and it Capitol"), tied-his horse to a rail fence entered .\I have been writing thus freely' to you which attended the clec-torul eohii for tlC! If sirs in the Mouth, tW1 particularly will task Mr..Uarfelt's apply anti was only sworn ; then rode tJ the I may Iti further unbosom myself by stating 11'"i.lcll'"lr four )'t'ar ago Is \ very UJKMI the relations unc parties in his own successfully llraplea of inconven Executive Mansion! and took possession.: have nut thought it lawful or wiseto ole. Substantially the whole body of; State. "The South," he said, "expects: the ience in the with any He inaugurated himself simply by taking use Federal troops in such lIIattl'r as voters all over Hie country is able wlhontunu"ual North to do something for them It was cry that the Natiol" is in danger in the the oath of otlice. There is no other legal have transpired 1 east of the Mississippi withil effort to comprehend and ftlthint unles'sNorthern sympathy were extended South inauguration in our system. The the last few months, save !I far as thc? may the which (.I'nl'rl 'I'rllc almost everything 'would be lost. The pica that it is nut worth the while to . jioliticians may institute parades in honorof i be brought into action under,the article of pres: .O\iliol'1 curnandi11officer in this There was no use whatever in trying to obtain exchange the "OUtl" for the "ins" can have the event and public officials may add to.t the constitution which cuutlllatel meeting praiseworthy letter during that crisis! the votc s of the South unless at least but 11t. weight in the North and Wet. . the pageant assembling troops and banners united resistance or 1 State It needs I to be said) in strict justice. that moral support was given to the Hc'puhll'u'' the small but respectable clm' of but all that only I comes proiierly' after more powerful I than the State lutlo'ite General Hancock probublv' reckoned l. whc'l of that section. If the South independent voters. A much larger body the inauguration before, and it 'I is not can subdue by (the ordinary processes, al1 I he wrote the letter, that might at Home enter nM>n the c lpnign; with Wli the IlOWI'1 of voteIl will argue that, if there is no bet- u part of it, Our system does not providethat th1 only when reijuected'by file legislature time reach the public, eye.I ali possibly was I )iort of the North.coiiplcd with Jorllu\\,c ter reason than this for opposing the electionof nne President should inaugurate another. or, "if it could! not lt convened 1 in session not unconscious of Presidential aspirations assistance could be given, there was u great Hancock, they may its well stay quietly There might be danger in that and it by the Governor; and wht'l the President while be framed its Iculc'II'C His name chance that certain States; could be ( tit home and let the country take care of, it- was studiously left out of the charter. of the United ttal' Inl'rv'llln thatmanner ,,I hud been prominent on many:ballots In theDemtucrutc uteri to such u degree as to cause 'nl. self They had been told, at every election, Hut you are placed in an exceptionally it js; u state peace. The I, National Convention of iHtM, cast their electoral VOt'1 for the tll that the return of the Democratic party to important position in connection with coming army l is laboring under disadvantages, and and from that time forward thueu.+ u nominees. There were ninny rl'ILO"HeplII'UI power would be the signal for unlimited ex events. The capitol is In my jurisdictionalso I has heel u'cd unlawfully at times in the I I constant banco that it might hl'11 con- the Republicans of the North should, not travul slice, disorganizing (, and e\r , but I am a subordinate and not on the judgment of the eople (in mine, certain! ), ;i snicuous lllln similar relations. Nevertheless turn the cold shoulder on their brethren of description of :snot ; and if I were, so also would be my and w*have lost u great deal of the kindly I t t any) |political expectations( of the the Hmth. I wal not speak of legislation, The Democrats reduced exi>cn- superior in authority for there is the station; feeling which the community.ut large once sort, if he really entertained t\1 at the ( at the Il''c'arr All ho ditures (enormously, in which there was nothing of the General-in-Chief. On the principlethat felt for us. I IOI'lt. must have hud a distant would say wits !that ff Florida very alarming, and endeavored to a regularly-elected President term of It i h time to top and unload. Officers in peril one so distant that they cannot would mirely go Republican in! November, amend thu ch'.tol laws no as to lrotct the office expires with the 3rd of March (of command uftroll often find it difficult to I detract much from the intrinsic value of the (On) Friday lust the State Committee of FlorIda I ,tlon. from being intcrferrcd wih on :- which I have not the slightest doubt) and act wisely when su t'riurs in authority document. A President had ,[Iaatbuneletteil l met at J\'ktUvle. and the members of day by United States oOc'er nominally - which the laws bearing on the subject uniformly I have different views of the law from : by thq electoral culcll' or if that was not that l.rc..ut.l reports as to the apjiointed I to It.O that are free recognize: and in consideration of theirs und) when b-gislation has sanctioned so, one was to 1 us provided by the condition of the several conn- and lair and really ho active and audacious the possibility that the lawfully elected action seemingly in con diet with the fUIla-i constitution In the case of their failure to ties Florida under all drcuniltunct was a agents of the Republican ,)arty. ThU wasa President may not appear till the 5tli of mental law, and theY generally defer to the make a choice At any rate the place was Republican State She never failed to go surprise to the Northern Republicans, but March, u great deal of responsibility:! way )known judgment lul]>eriors. Yet the I not within the range of General JIuncoik'H Republican. At the last CongrcAsional clef they clung to their faith und voted the old necessarily fall upon you. You hold over. superior officers of the army)are so regarded ambition for four )'t'r to t.U e. The opfiortunitv tits the First District Republican ticket, being assured that the Democratswere You will have i ower and ,prestige to support in such great crises and lu.il to such JI.| also for writing the letter was not Congressman, but by tie Htloctc..II\grosncxt the only feigning innocence and IJtrlotbu J Kponsihilify, >eciay!! those the in vented by himself. choice of the rraulr and would speedily break The Secretary of War, too, probably esi near I was written strictly people ( the out in .dan-'er- vou. ' h'olds; over; but i if no President appears hea'd of it, that it is necessary on such momentous | in rettjMjnse to u request of the General of UCluJrul|Iu j>owtr. The 1tluJlkal sui- ous plate.V'iat' are these voters to nay he may not I he able to exercise functions ill occasions to dare to determine( for the Army' for his views concerning a critical was not allowed to tt'at. midultbccuuscof when they are told that the keynote of thc the name of a President, for his proper .(* them.Ih'C what I is lawful and what is not I; civil emergency in which mitar interference the frauds I Jo'riotrut'lhy h. present C'IUVI i the assertion that the Ke- those of a known Itul.erior-a lawful lawful. under our "YttD. If the military might |1",+>ibivr he Ul'IIH'rlh. ThU net was tie imbhcuns are all that they to be, are l're"hll'nt. I authorities should be iuvokud. as might I"'*- I cal 'mrtsliltrtionsutlhateuuinentsmddierwerewell wholesale vnuurv fr CUIllluat.1, but the Democrat Ir This U wide .\, You act In your own responsibility and nibly be the Case in such exceptional (tlC( ,' known t"I lie din.re from those of hiscorrespondent lint. of the names of from four to five thou. Iv dlfl'rent from th worsu appeal to bv virtue Ida commission only restricted lIJ\' j' when there exllcl luch .tn.rltut U and fac that he frankly suns HC'.ubll'l voter "It Is,u party (the ) North to put its foot on the neck niouth- to the correct the suffer sought his counsel tlott'lltelaUC oj the ' the law. The:$ecrcnryuf War is the reult circumstance tuctiiv( that we & "rebtlo&uth, The roiicliuiou of a President. You are not. If neither from !Its past atiul if it 1a' acted wrong Implies I In itlf a high compliment, to (iert. tight, said Mr. Conover in conclusion. 'Do tl of many vottr outside of l'rrCxlolallll-i I candidate piece has a constitutional majority of I j fully. Our regular army little hold ul"| lUncoik' tudy and jud/meut civil you wonder that we want help (torn the tlelans 11U"t l e that the the Electoral: Collie, or the St-nate and i I I 011 the affect ions of the |>eopleof to-day, ant !' attain. We discard with utter contempt f the North?" 'have cried W(>lf! too Uc'publ'IU, 1111 lie left the occasion of the count do out its superior officer I"huut certainly, as r.i insinuation which has been thrown out in I Mr. Sypherof North Carolina to take careof thIIlh.for one i-ainiate' HUU* on declaring some "" legally't-Iel'lt.'ll I I as lies in their {tower. legally and with righteous certain I..nl.rltie quarters that the corrcsjxindence '! rlarkPI : I C I'lmrUttuu Aruand (.Imritr, in pot' bv unite the People. there i is a lawful machineryalready intent, aim to Ilet'u.l the right, which :' wa induced by any disingenuous ( "leutc'ull, let me tell you right hero I ... . ) to u is the law institution which motive l Sherman' Although fur c'awlllah' depend upon the ' muettbat.cattingeneyald ; part. - Ot'utrl : ( I 11oI'U\-jolul, i I | vote of the OIK It ton much tu lawfully. It haoj thev represent. It is a well-utranhmg institution *. Itttn which are you are licked to-day. ) iimtemporarieiihave nut been divide recently the question uboxl l. IlU Ol"l."o .ion present- I! ,uinl it would J well if it should have in Ctn.ral ( reply ave JtlltiOI.1 lut yet You have( 1taJ1 (rout Nome of tie &uthtf nay &t.nt; tissue ball/jU at the South f-ve. 1 tit reconiized! as a bulwark beii given t the States. iel representing have forefather: pnmded an cipjiortunity j.ublicthe reply t beat' Il'm.u we not a beam In our O when Kepul III;'ha"been exercised our l and bus been .'{"")It'j I U support of the right of the l.lJlo unimpmetwhabie witness totheconfldenceandionliulity fepoktrii. They ay (that if an honct count Ie' !t Emitted 1 to as lawful on and ( t.l I am t .uu. I II of the relation* which exUe l between can be \'urt.{ all will L wel Gentlemen, 11 l.ulldalL ay twt lc than nized 1 ami Il'Isrrxui4.lexe.ttc, them all continue unabated by there are too many .Ir! cane." JIO.OOO is needed to carry each of the I-mton any 'lumd elect: Mr.'ripen I I Tu GEMKM. W. T. SHKBM ', t'ournawllJ jxtliltical divergenco to present stay Judge Freeman also spoke at Hume length districts? Csuia' nuy be able to decU" That machinery President \\'vulolj'roLaI.l.r' ires Army of the I'nited State*, Wa.hln.-un.! I There i I. not a _had.\of tt' to suppose and slit among other thing : ortocorrupt whether it bt'tl.r.-torl.?ludo,' Jlcndd.to cheat a voter ( l lI . J 1 .,' ... - .'J -- - k :l 11'1 i fl ru.Tf"3JnJT 1 ) I. r. _. ,f onl AU" lib flux, 1', llL" ) " 't'fliu/' a, : i'MiyJ ,ry en 7r.w 9Vn".R" nwwrwt- ... .. ,......4C' .-., ,, . _____--_'..:..........:.-_ _- ::'". -- " ,, .. < o ,_."""" __ _., _.., . F i THE FLORIDA MIRROR : AUGUST 14. I .- -- --------- 4 A POLITICIANS CAREER. GEN EitAL 'UIUWTOR'. BUEVARD COrSTV. j CONDENSED TIME CARD X K: W SCIEDl1L1I: , CHAPTER I. County Judge -\. J. Whitlock, City Point a United States<< O III cor is. OF THE (" Clrrk-A. A. Stewart, Titusvillc.Suirrintftulfiit . 1, was not brought; tip) to any trade or pro ATLANTIC. ( (fSULF --. ' tAM OFFICE, GAINESVILLE.: : + ; of iSV-AWjt Alexander Tin A WEST INDIA TRANSIT .- wj - fession. * k I At eighteen I voted for the first\ time. It was then I chose my life occupaHon. Umt"trr-I. A. Barnes, Gainesville.Krccirer dall Lake View. RAILROAD] j ( ; | { } ; -John Rollins, (ttiinesville.SitrrcyorGrnrrul PENINSULAR: I RAILROAD . I entered politics!'! and became; a. politician. CLAY rot'NTY. . -L. I). Ball Tallahassee.MSTRICT ( \\'ulilo Jiranch ' t ,) FLORIDAr1NLANDTL'.1Jllil.l'I' County .1"ll-\\'IIl.! Peeler!!: trees Cove CHVPTKR: II. ('OfRT.Jmltjr Springs.Clrrk' AND'CCMI11R1.AN1) At twenty I was an efficient "worker" nt -Thomas Settle, ..Tacksonville..Wirfhiil -O. A. Buddington<< (linen( 'ovc ) ROUTE.; : ! the polls and political meetings. I was !-.1. II. )Durkee) Jacksonville.OrA Springs.tftiiirriiitrntfcnf! I, . l Walter Jacksonville.' ; ( .'\rlWII.-)1. 1n / Kffcct; Filrunry let, 188fJ. - large stoat and belligerent, and had good -Philip nf ieiger, 'i I ]lIug'l.!' At the polls I challenged the votes INTERNAL UEVENfE.: Middleburg.( : 10MI'AX VI HOIXOIxave !!stiCTn C of citizens. I faction of ('ol.t' IIIL\ C'fifNTV.County . I quiet joined a our awn )political) )party, and yelled and stampedout h'rt'Jrelllll/ ) Eagan! : Jacksonville.COU.MTOns Jii,1,,,:-\\". M(. Ives .Jr., Lake City. : Atlanta, < a. 2.15: ).. ;M.IAMUU ", M( ..... . d'a .. w adverse speaker} *. OK ffPTOMS.; CIc.k-.JolllI Vinzant: Jr., I lake Citv.h'uKriiiteiultiitofSfliool.i act Hi, 7.45 r, M. John \ Howcll, Fernandina. ; ( Lcavc Brunswick! ( a. (!.15 A. ;M.Arrive . (' "I'rER III. Edward<<1 Hopkins, Jacksonville. -Juliu!' PotsdamerIjike Fl'rllnlllillFla., : ................10.15.1.: M. ' City. y'1 At twenty-two I was rewarded for my services Leave Fernandina.1U.IW: A. ;M.Arrive . John' F. House . St. << Augustine.J. ; . PfVAI' (')CNTY.Crmnfy.Jtvge'illiant.l. by becoming "assistant"' in one of; our M. Currie, Cedar Key. Baldwin, l.iir. ;M. ; I I. courts! at $::1 per diem The duties of "1I,, btUllt" McLean, Jack Leave . Baldwin for Jacksonville. f.'SO i : : sonvillc. :! p. M. are simply to assist!'! the paity. My, regular " C'/"rk-TholJlIl.'I E.: ltnckntan.lacksonviiIc. Arrive Jacksonvillel'lun.loutc.r: ( : ) 2.35: p. ;M.Ijcavc . in instated I. presence court was: never ( - ( neon 'fhat'lIot!'! at all essential.' Hut punctuality Slate Officers. frnjirrtnfnitfriit; .tirhuoLe-.IIbert' J. Uus ; Baldwin for ((Cedar; -Key.::..: 1.W) j..'u. So :SEASICKNESS: : : :; No OCEAN DAXOEI5STHKSTE ,{ at ward meetings, primaries: etc.; isindispensable. F.XEITTIVE: : DEl'AUTMEXT.ivnrnnr ) sell' .Ja'k nllville. Arrive Waldo (Junction P. If. It).. 4.11 r. ;M.Leave ,\' : } It Is here that. a politiciancum ( -(Jcorge F. Iretv''I'allahavvee. IIVMII.TON COfNTV.Cnitiiti Waldo.) ... 4..!'I1) P.1.; . t !* his salary. I'rc*!i.Leave i. \;MERS'ITV ,.\,. '. 1 1 Gainesville..... : . CII\PTKR: 1\ Tallahassee. Clerk- !! 5.2:!!>II' ); t. From an "assistant"' 1 was promoted to uclerkship Strrrf'iry nf! ....,iIfr-\C. D.) III II X lUll II, Talla- Mijifrintrnfleiit Robert(!if S. %Stewart/IJ"I.-.J: ,Japer,! litia J I. Rob) Arrive Cedar Key. !H.JiO:; I'1.; ( OF ItltllGETON } at $2,000: ) per' annum.\ ) This I pmiHon i. 1 11"1 ""('('. c'rtlIc'rlllll.: Trains to Jacksonville and North of Baldwin XAItK. ' n..n And giving me more means!'!, pave me also .1. 0"11///1'1'-1'111111111.11"/ Drew, Tallahassee.Trinfiirir tlail . . influence. I was active! and diligent in politics -Walter flwynn, Tallahassee.\ : : ItMtNVMMi: lOf.NTV.County (.OIM XoKTII.Leave . \and found'I little time to attend to anyoflloe .1II1I"P., ( P. IJaney: Tulla- .htdye-\\'. L. Fricrson, Brooks (Cedar Key. 4.15.1.;) ;)Ir . \ duller! Hut as I have said before, an hassec.' y'ille.lcrl'.T. Arrive (:iaincsvillc. s.41.1.. ;)Ir '1't. Tim: 1"T'5 t_ 4 z- ollice-holdcT h not paid so much for what (hl'i.'Jl/rl'/ tif 1.lIntl.-III11h)l A. Corley, C. Law. Brooksville.tiujierlittfHtlcnl Leave (Gainesville' ........ ............... $.;\' .\:11.: ( - t lie does: in the ollice us' for what he does out Tallalllo\"l': : / vf Se/iwl -Dr.) S. Stringer t Arrive Waldo. ( P. If. R. June.). !U.* A. ;M.Leave 1' 1.I'SI"I::: ::: ( : z ,; VWJKTAHLK": , I a ; g of it. Assiduous as! ever at political gatherings :::;"/".,.,'",(.",(,.iit, of Public//; /Hnlrvctl'iH(; ". P. Bronksville. \\ ,. !).55 A.M.; I I ""' *--*" 1 commenced( approaching socially Haisley, Tallahassee.A : int.i.siiojtoroii cofXTY. Arrive Baldwin, .t.12.17: P. M. t of the lesser the I "It IJHfftnt'rnrrnl-J.' J. Ui.kl"on) Talla LIXE.Sc.'nllU'r : .- of !some great men party.tl - I hassee. County .1"l1r-H. L. (Crane: Tampa.: Leave: Jacksonville' (Cum. Route)..11.15 A. ;M. ( might call them our political gentlemen'sgentlemen. Clerk-WnJ. C. Brown, Arrive Baldwin.12.30:! Tampa. p. ;M. ? I commenced, being recognized,l laY C niniiitincr! of! liinni;iyl'rtliun-Ir.\} Hl.thI. - n person' of I inllucnce I by them.t French, Jacksonville.KfPHEME; Sn/irrlntciiflrnt of Sellouts-II. L. Crane, Leave Baldwin; ... .. .................12.40. p. ;M. c''it.v' of lii-idgefoii; , Tampa. Arrive FcrmmdLia: : ...................... :3.40 I'. M. JOIN 1'iTZOEIIAI.DViiits I (VPTER V. ; COfllT. LEVY: COVXTY.County CAIT.! > , Leave .: : I'. ;M. I ran for the legislature and fleeted.My ('I.ilfTusNrr-I K. ),. IlandalI.Tacksnuyille.: II. and was Jiiilr/c- :1.hrill.Trol1. : o1\; Leave' lirunslviek.s; ( ) I'. :)I. \ at Fernandina for the Monday ( : flection\s'aq largely e to the Sunday, .1sr.nrinfruntiesJ.'estri; ( tl, jr., Tallahas. C/C..k-.J./ M f. Barco, Bronson.SujirrintrmlrHt Leave Mucon' S.10) .\. ;M. Thursday' night Vegetable/ Trains'! of the ''i pumic 1 pivo the residents<< of my ward in !see. ,, of 8r1t""I. -Jos. I'; :ShandsHronson. : Arrive .Atlanta ( 'a.-.. 1.15 I'. :M. l1 one of our suburban beer-parks.,' It was! at A>fnri,/lf Jiirtlcc-U. 11. Van Valkcnbnrg! Trains: to Cedar Key and :South: of Baldwin ATLANTIC, iULF ,v WEST ]INDIA . my expense and cost half II year's salary. ,J nC''klloll"iI Il'. ;M.\ .\nl: : COL'XTY.County daily except :Sunday.: AM v lug Hut the legislature was a fortunate: ('I".k-(\ H. Foster, Tallahassee.fllllflT \ . eventful session and I roujt.That .fmli/c:-E.: M. iraham: Manatee.CVcrA PENINSULAR: f RAILROAD, PEN: 1XSU[LA R 1\11.1:0.\11:0: :< I>::, was an came : i .Il'lKIEH. / -''''Robert S. (irillith,, :Manatee.Siiiirrntnnlfiit ( . back to my constituency' with a pocket full firs Uiiririt-Augustus: ].. Maxwell( Pcn-' of! firliiml*-Felix .1. :Sewanl: W"ld'J( il/'llurlt.) leaving n'lItrc Street Dock direct for Savannah. of bank checks. saeola.tircoiiil) Pine IA.-VCI. WIIti\l; $nl'Ti1. PuvsfngiTs' and shippers are assured! , CHAPTER 1. Cifctilt-David) Walker:: Tallahassee. ;MVIUOX COl'XTY.County \\'aldn.iuuctiun, (1H.I.M.( ; of connection at Savannah\ with the steamships t mi. i After this: promotion' was comparativelyeasy. \ Jwlije-J. M. Melntosh' Ocala. Leave Hawthorne....................... i."<0> .\. \1.; and trains for the North. 1. I was known, and in the regular line Third (.'iirin't-E.: J. Vann Madison.' CM-II. "'. Long; Ocala.tfujiciiiitciiilcnt Arrive Lot'hluos.a. .;.10.1. ;\1. of succession.!! This 1 had, earned by bcven Fourth Ci.rl/I-I; I*. Arcliibald Jacksonville. ' : SctiHtil of *-II. C. Martin, (10INO: ; NORTH. Steamer UitYi ('lu'I'1'1' , t consecutive years of hard work and( party Fort )(('( 'or. Leave I/iehloosa. "! A. ;M.Leave i " fealty. I was made park commissioner. I Fifth Circuit/; -James Dawkins) : (Jaincsville. ; MONROE CofXTY.County : l Hawthorne........................10.45.1.. ;M.t ('.\ P. H. WARD became a park commissioner' because! thatnl1hu Arrive Waldo .IIII\I'Ij.III..1.1.., : ) 1'. ;M.Trains Leaves Street )Dock) Wiilne.Ml.iy, , / .Jet '-Chas. J. Ruben, Key AVcst.Clerk Centre< < every : ; fell in thu : to me deal and not because' . AS7.r//i/ ('i""IIt-l; [ \IitncelI'J'ntnpt.. : : from Waldo, to Loehloosuaiid return. tidunlavftrS.l\.1NN.111: John : tunchingutfll'NS'I'K :Sitchcr. Key' West. tutu ; my 1 have way any, ] partiality'! for be abolished.parks.! If I They had (ford.i s.t.tI.' (i;"'nril-\Viii.; Archer ( '''ckl', San- ffujM-rtiitetnleut; of School,J. V. I Harris( Key Tuesday, Thursday' and, :Saturday.CONNECTIONS.; : : :ST. SIMON'S. DARIEX: and, West. ( : DOBOY, OA. vast of valuable occupy' areas building ') 1 ground to little purpose. 1 !ll'rn'ilIso a xvs.su-". COUXTV.County ATLANTA. .llt'iiioniiuln..steamers ,.1 y reason on the board, of health. An olllcious t'ourt ('.h'l..r..r. Jitif/ti'-Hinton J. (Baker Feniandina. 1 Close connection<< is made at Atlanta (ia.. .! I doctor made himself particularly disagreeable : Tinnn CIIUTIT.E. to and from all)) points: Xorth, East: t. West andXorthvvcst .: / urn connected Through Tariti' I 1 to mo there by insisting: on various: :. J. Vann, Judge; M.( .\. Hloiint, State's/ ('//I''' '-c: \\'. Maxwell, ]Fernandina., daily. with I the Atlantic, Sulf( iV: West India Transit - 1 "reforms" in the! crowded jiortlons.' of the !Attorney.ftjtrini 8//I'I'ff-l'l'Il'r/ ;( Cure, l''crnamlna.AtrMor : \T ;MVCOX<< "'\1 and Peninsular lallro/lllI.1I1111: / :Savannah : ,, t He wanted of < of Tiuff-Win. 11. (larland Fer with steamships' for Haltimore Philadelphia c.ity. a general Ttrin With : I. Man y! Trains: for Eufauln; Columbus: (h1.loutgoulery'iluhile ., drains, wastu' pipes, etc., and worse all, Taylor I'd in April.Madison nandina.Collector. )' tutu New Orleans. I New York and Hoston.For . when we attempted it, he wanted it done on :3d Monday Monday[ in April. / of Ilrmiue Warren F. Scott, "Fern I :State-KoonH: ): +, TickeN( and 1 all other' terms which would have ruined any politl- I IIHlllilfo'L. Jili! .Mntiiliiv.. : ((11 April. nandina.Sitjieriiiteii'lrnt. AT FF.UX.VXUIXV, .'1.\., )particulars_ ', upplv to the following Agents! : 1 tall bounced --.J S'I"III-\r.. With New York ami Fernandina Steamship and I Offices contractor. or plumber.e 1 Suwannee, 1st Monday' IInt'rtl h :Mondavin Mahoney, : / him.( .\ 'silo {'nil a ha II. Line from Xew York on Wednesday 1 Fernandina, !'!n.-1('apt. J. L. Rnumillat: , I J XOTE.-If people\ are not I healthy, they Columbia{ :lM? I Monday( '] 1I0'rtth :Monday( OKVXOKCOiXTY.Connti I0.i"t: "I III. m., and for Xew York on FI'i.lalit .\l'lIt.) ('entreat.: bet ween:( :Second; und'fiorl.1 ! should take IlIl'l kine. That is what medicine In / ..1/11IVr-1]\ L. Siinunerlin (Orlando.CM :3.40 p. m.; from Xussuu, X. 1'., on Wctlnes-( :-a\'alillall.lill.-Vor.: Hull and Hryau :Sts.: , I is for. There might be a greater number l.nfayette, 3d Monday' : after Hit Monday[ in / -J. Ilughey( ; Orlando.Siiiirriiitrnilcnt ) ) duv ; for Nassau, X. P., on Wednesday.With (lilt,,,..itc Puhi!' ki and Seruven HOII l'. of free dispensaries' held by efficient- April.Fall ; [ of. School*-John '1'. Becks (ietirgia; and! Florida Inland Steamboat Jacksonville, Fla.-Corner Hay: and\ PinoSts. I )party workers on decent lIalur < "I. The 711I- Fort Reid Co. from" :Savannah on Tuesday, Wednesday ., Hr. L'Englc's: ; ] )Drug\ Store' : .\. 1'. Lan- ( druuWry( of prescribing and CUIIII"llIIlIlinglouhl | Taylor, I'd Monday' in October. FT. JOIIX'H COVXTY. FJ'i.la.111.1. Sunday::; ; for :Savannah:; on pheri'. Ticket Agent; .\. L. llungerford[ , he done by assistants at $10 week : Tuesday, FridaIIl1d :Sunday:: Agent. l : : ) JK.T Madison' Mondav 1 in October. Juu! R. C ; CII.\PTEH ".11. Hamilton( 4th Monday I in October. County. ytM.. 'uupcr :St. Augustine. ;' With Charleston :stcnmen (St. Jill.,.',.IIUtI<\ ;t. Augustine, Ia.-Oll the Hay, U. F.Armstrong . I It is' a part, of my political creed that t ajiolitlclan Stiwannee, M Monday( after 4th Monday l Clerk-Bartolo I,'. Oliveros){ : :St.: '..lugu.tine.SupnlulemIeJ Wednesday City: )%111(1))and from Sunday Savannah; for and Savannah I Charleston and 1'alatka!, ,Fla.Agent.:-Lilienthal Hrothers & ('II., _ in October.Columbia. . l is lit for any sort of office The of School*-Thomas: A. Pacctti Charleston :\101111:1IlIh\ Friday.With Agents.' t 1 or the office bo :L'd Monday( after Hit Mond.iyinOctober. ( . } practlculduties : can always I Augustine.: Steamer Flora, daily to and from! \ St. GUSTAVK; LiVK.ienenil : . performed by subordinates.. Hut the political SUM; TKIS: COfXTY.County ;' Mary's, Sa., and seutt-weekly to and from (; 1'1I:04.1'III.rIWIlt.: . ' of duties] which t.alil'l'Itl',3.1Iollela\ after 4th Monday.11I round may give one\ the ) :St.: Mary's River " t October. Jiulijt-Henry S.IIS.idy! l Lec.sbnrg.' Landings.: W. 1< HAUUY. open icame to any office requires years of Clerk-Tho'mas J. Iv'e ', Leeslnirg.Suitertntemlfiit .' (UCIll'rnlt'lIt, Savannah I toll and cxpCrdencel1'heu: I was appointedinspector IOVKTII CIKLTIT. : } / AT KVI.DWI.V, 1\ ) !! of steamboats I didn't know) what R. B. Archibald, Judge; Samuel Y. Finley, of Sthool; *-H. H.Duncan] '\" Trains for Live Oak, Tallahassee, and 11 J. X. HAUltlMAX:' . Lake Crillin. iartOf boat to inspect. Relying on that State's Attorney. all points! in Middle. and West Florida. -- Manager.SUMMER f / fortunate Destiny which has never deserted Fj'riny} 1''rlll- HrWASXEK' fOfXTY. AT LOCHLOOriV, FLA., SCIIEnt.I; : me In'oar 1')1it; l'alfl'Cr': I went t calm and. :$;t. J lln'lI. :M Tuesday in March.( County Judy.-! Michael( A. Clouts, Live With Steamer Al/>liu for all points' : and I collected on my first official tour of inspection Clay, 4th Tuesday 'in March. Oak. ]landings on Orange: akc, on arrival of Peninsular TilE fTE.VMF.IW; ( ai\ board the old Iluxtttj. Said I, "Cup- Bradford, hot Tuesday in April. Clerk-Robert A. Reid, Live Oak. Railroad Train.ATUVINIWILLE. [ 'stain, I've come t.) inspect your'bout; show] Baker, :IM 1 Tuesday in April.! Siinerintfiuleitt; SrlwIJI.t-.J.. O, -Jones' (I- a .--_ J due ht-r defects He waved mo1 to his private Nassau :M] in Live Oak : FL\ , Tuesday April. , 1 : tt\ t ;;;, cuhhi, where:a rrfhfrcht collation wits Duval Tuesday 1 in Mav.t'alt nlll'$I\ COfXTY. With Stage Line (for Ocala and Tampa on 1 ST. JOHNS } *" !:' <;IT\ POINT'} pr<'JlarCt1. We drunk to the defects! of the 1'I'TI/I- County:: Juiliie-Vrt.tl. I. LalYnoticre, Enterprise. _lolI.lay.l'hll'IIllIr and Saturday ; from .- --.* *. . litutup and at the close of the entertainment St. John's 3d Tuesday in September. Ocala ami Tampa Tuesday' Friday and Sun ,, thC'ngl'ut'of the company presentedme Clay, 4th Tuesday in September. t'lak--JollII. Dickins: l Enterpr('. day. 1 \ with a neat little testimonial of respect, \T ('F.I\\R KEY, FLA., ) Bradford lilt Tuesday in Octolx'r. S"J"'ri"tflllltt of Si-h<>ul.i/ --James ]II. Chandler d J \ \\f which I took to a bank for safe-keeping. .\ Baker :Jd Tuesday in" October.) [ Enterprise.: With Tami-a Line for tJ mouth afterward the Hnntuii Litnp., yeti Nassau :'M Tuetubiy in October.Duval ) Tain|>a and Manatee 3itilttiayand' Thursday' \ ' i l.t the inspection had been natl-factory every \ 3d Tuesday in Xovcmber. lit 4 )p. in., and for, Key'iVest Sunday and 'if- , . FLOICIDA A.MI ... unC'whd( took part In it. IIAVAXArEEKLY Thursday, at Ii! p. in. --- : ; FIFTH (IR'CIT.Jatni : . E CHUTKlt: VIII. : FAST MAIL SERVICE. With the United States and Havana( Fast 1 j ; " l"l''f t A thorough political training requires that B. Dawkins, JudgeV.] ; A. llocker \ Mail t Steuner.lbrri/'al for Key \\'l'*>t, 1(luvana, VI7"ILL ]leave Fernandina for Jacksonville: 4 one vhould hold, alternately offices under the Solicitor. Cuba, on arrival of Special Train, every Tuesday 11 and Palatka, and intermediate laiul- '" L' Sjirng TcnaSumter ings::: on the St. John's River and : afternoon, at 4.0:! 1'. m. From Havana, :Savannah Yi city, the State and the Federal governments, { besides. :I'd Monday( iu March. Oil I' and[ [K."t en'l'H.&tllr.la. '. Special and Charleston, as folows : I i carrying one's inone's I country majority )Marion 3(1! Mondav[ in March.Alaihua ; . 1 /0./ train connect. I , !I llCket. In such manner within three 1st Momlay[ after 4th Monday in From Fernandina . i With Steamer for points'(' on the ,: Ese1ertlriee l, \ years I wus: deputy United ::;tuh'8l.II'Clor. March.Levy' r :J> Suwanneo River, un'I 1 bur-days' tit (0 a. in. FOR JACKSONVILLE:: : \ afterward a State commissioner: for something 3d] Monday 1I0l'rttlt Monday; in AND PALATKA, :j .' I and Performed the and 1 '" March. by new << elegantly tip Jiir E'EltY'EDNK; :-:U.1Y.]) -r etc., apply to i s thence I new to a went in Congress.It's Putnam. hot Tuesday after lt Monday[ in jMiintetl steamship ADMIUAL]): : (sidewl'ieel; ), A. O. MvcDOXELL, 't all after know the The II II1 t easy you ropes. March according to the following scheilule : From Fernandina (icn'l Ticket and I'uss..lgent.' offices themselves' merulv' holes into are Full TrrmSumter- I 1A'\\'c: Cwlar Key on Tuesday' morning. . D MAXWELL: (;ien'lSupt.) 21.ST. . which the political] 1 roulette ball fulls. This 4th Monday( in October. (Passengers: from Savannah leave by steamer .SAVANNAH: AM CHAKLESTO.V:( ) , -- -- -- --- " i is the crowning bounty of our system of Marion, l Monday after 4th :Mondav in City of Bridgeton on Saturday 4 1'. in. I..caveFcmandinu JIAUY'S KIVKIl IMC'liKT. Jiff EVEnFml: Y.-t 1t'1I1& regular of ; government. row steppingstones October or Jacksonville l by Transit Railroad i.t from deputy United Stall's marshal Alachua, 3.1 Monday[ after 4th Monday in train Monday morning; ), Arrive tit Close connection made, with teamen for, to the office in the of the up highest gift October I Key West Wednesday' mornlllrrh't' at Mellonville) and Elltl'rl'ril'eIln: with t-teain- ( l 1I'OI'I001IIIeuII I the politieians.CIUPTER Levy, 1st Monday after 4th Monday[ in I ]Havana( Wednesday afternoon. i : ers for Ocklawaha [River; also: ut Savannah ix.At Xovcmbcr.I'utnam. Returning Il'lIn.'UanllllThunotta, even with .steamers for New York, Philadelphia, the commencement of my career, 1 :1.M Tuesday after Monday' [ in I ing. Leave Key West Friday JIInrnili Arrive Boston and Haltimore.and Charles-ton with somewhat feared the press. I have long Jccember.William) i Cedar Key Saturday morning (and at ] :: :STEAMER FLOKA.CAPT. steamers fur New York, Philadelphia, Baltimore since: gut over that Xo genuine politician tI.EVDTIl (1R11. Jacksonville and Fernandina hTrnn'lit l'H and with Northeastern & South Curlo- now pays any attention to the raving andscolding Archer Oocke.! Judge; A, St. flair- }Railroad Saturday! evening and at Savannah JOHN RICK ARDSONl'1I.I.llL'N ] : Ima Railroads:: for routes: North East: and :t. of mere editors. Jet your office, Abrains, States: Attorney. ny !steamer! nty:01 Itridgetutt'Iontla: )' morning \ OX THE: ST. MARY'S RIVer West. - hold it, and when they scold] lay back in ), thus forming the shortest jiossible sea during the season as follows : y chair and ask words Vofuwialst route between the United States and (1tta. EVERY )(OXDA'\' FIRST-CLASS. PASSENGER] : .\('('oDIO- I your them in the of a Monday in May.Brevard Leave ST. MVRY'S : and 1 1)\TlUXS. I r" lamented but unfortunate compatriot of 2d Monday in May. PASSAGE: RATES.C THURSDAY MORNING ut G o'clock, for t 1 mine What are you going to do about it?" Orange, 3d 1 Monday in May. !". Fjcvrtion.; }'ER U tlI1U ; and will I leave FERNAXDIXAhame Through Tickets and Staterooms wtured ,t useful when Savannah to 1I\\'alll&$32 00 $-IS MFernundiiia 8 for CAMP PIXCKXEY and all information t Reiwrters are you want to use Datte.2t1 MOlltla.ln. June. days at u. III., furnished at office, corner f. )a them, ,,1 regard& editors only as boss: reporters. Fill TermVolusia- to Havana..... 20; 00 38 00 and all intermediate landings on the river. Centre and { The people are useful and serve u !great, lilt Monday In Xovember.BrevanJ Jacksonville to Havana ...? :33 00 3* 50 Returning EVERY TUESDAY and FRIDAY :20-ly c. A. NOY ES. function us voter They must necessarily :Jkl! Monday( in Xtivt nilier. For staterooms and tickets' : apply to LKVE: will arrive at ST, MARY'S at :5 i p. m., N belong to one or the other of the two great Orange) 3d Monday in Xovember. .ALDEX'S:) Tourist[ Offices. ouching at FERXAXDIXA. A. II. XOYES, parties in the country, and us one tide nearly Dude, 2d Monday in December.County Savannah, (ia.-Corner Hull and Bryanftrcets. On \\' ': : .\y ? and SATURDAYS i t- balances the other the jieople' as a factor in .. II. .A. l"LL.X.t'llt.. will leave ST. MABY'S at 8:30:: u. in., and can GROCER AXI SHIP CHAXDLEIt: :, politics.,are almost eliminated. The real o't'rllul1linulUollt Hotel. A. I. MEI: be chartered for excursions: toDuugeueaM struggle lies inside of the parties themselves. OHIrerN.AL.VCIIl'A LEN, Agent. DEALER 15 Owing to the present per of our |>olit-- JaCklllll\\"iUl-c.'urJ\ Hay and Pine st street in the tr t\lfSTY. A. C. : : and other points of interest vicinity Provisions, Liquors Etc. 1 cat system for ]olitUiaiis: the people proper LAXPHERE. Agent.St. . I llnd' it Impossible to &get inside of. affect Influence County Jiulije! -Junius C. Gardner, (iainesVille. Augustine-On the Hav.* If. F. ARMSTRONG Fcrnandina. - f t ... or iu any way derange the appliance Agent_ __ :JOtfMHS Through IIIIU or Lading AUE.NT FOR H. F. AVERY & CO.'S PLOWS. r' +* whereby we move the great machine. CUrk-J, A. Carlisle! (Oullll ,me. by MALLORY'H LINE of Steamers to all t; I'The 5'l offices originally intended for the ben- .!lIp,rliitfndtut i If tchuol* \}, ..\. Myt-rs I AXXK ('I..'UK":, founts on the St. Mary's.Clone - the people have been converted into tiaincsville. CEXTKE STREET jte6tof Couuertloiinade I "' ] cordon of defences for the BIKER ST., BET. CEXTBE AIACIII-A, Ja vast politician, roi-.vry. 'l'lnnu with the Xew York and Savannahsteamers. :52 tf I other one supporting and all working and connecting in bt.'autifulooJ\'rt with the Qjuiity Jwl t-JlIlm R. Hcnulon, Sander Jo'tnx.\XDi"\: ..\., Mark all"b"Outi:: Cure of Steamer -- ._- FERXAXDIXA. FLA.WM. . I together for theside that has possessionAl of40C liOn.ClcrtJo'. J. Puns Sauderxoii.A.fjfrinttndtntoifch I'EVLERIX THE flora' tOOD! Femaiftlina.ACX-OMMODATIOXS FOR PAStengers. II. C. DVKYEE ..-\ew 1"lIrt.GrapMc.. Olustee. ('hol't".t Fruits and Vegelnblex.COXFECTIOXERIfX find this:: a very attractive trip, as the Menerys GENERAL MERCHANT MEW have been known to correct their BJUt\t'OIiP l\l'.NTV. :: grand and alligators and other game are fEsrte ST., NE.4K R.; R. DEPOT fit ,vanity subdue their pride and even over- touts Jtul j<-J. R. Richanl PI'\I\' <1eIU't". : ETC.Bliss : abundant.For , ? v''j wrae: their BUiwmtitloiw! but, once Impregliateil t'lerl-Ilt'nn. F. Turk I lake Butler.tiujxriuteMlfttt further Information apply to FERXAXDIXA, FLAt ible for : uf G'houL--t'. Harrison: Garden Suds JUAN RICHARDSOX: , ( 1 with it, it U: hl1po u man to Flowers, Farm and yet rid of his vulgarity. Starke. Garden Implements 7 tf 25-tf Jo'rnmdilll'Ia.: IIuj ('orn, Oa.li.1e . IL ., I _ .---- -- - , .... # e '- ',,, ,, ... . .. . 't' .; ... n ...._ "" I THE FLORIDA MlUROll : AUGUST' U. ... -" .- "------ .-.-...- -----.. .. ,- --. - - -- --- ---' -- i "\VffYM.Y: C'lYilCKi':. I fOCK-J--un, n.tnr. Hut in the. growing season the case reverses lWUfJ.1 TIOXI1..II. .. 'I' I dryness i is then fatal nnd wetness I is u re -- Jt;. (Successors: to J. M.( Cooper t ('0.,) Hock-a-bye, babv, in the treetop.When quisite.: Sometimes 1\ !lielllOnwntcrin does Sr.t.r l Kmr: .\TJIThc) farmer's children "3 ;, 1>VLKU.S 1VT(9' : the wind blows tbe cradle will rook ; not !'suffice because it 'snot penetrate soil are too apt to give up the idea of ,securing a .\, I When tbe bough )breaks the cradle will fall, that t has become so dry as to repel water. good education because they cannot bo sent : ( School and JI Iil4'IIIUH'OU1! ,,! 'r Z Down tumble)' )baby, ), and cradle 1\11I1n1l.:' Hanging vases are apt) to get in this condition to' the high schools and college, as are the ,I 0 :\11111':111 only be soaked nut of it by ten children of rich men In towns! II lilt cities. ,": hock-a-bye, baby : the meadows: in bloom minutes! more )fllrtl\alnnd complete Immersion i This I is all wroll The Knnsn, l-'mmirr says \,\, -I si- Uiugh! at the sunbeams\ that dance ill the in a pail of water. Such a bath the man or woman who, has. learned to read '. II' -- ---* room, Lcn'titsthe can master almost any branch of knowledgeif -" :1 BOORS 3 HOOKS | F.cbo: the birds with your hntlllll'), 1 ing insect which plantMLy(1ruwniugwilt-t'xltnnst are often too minute) to "be possessing: average natural abilities. Hooks -. tare .., 'I;.( +. p $ Coo at the sunshine ;and !Hotter* of June. 't'llItiI'iihle.! These!' remarks!' were prompted cheap and abundant which treat on any : ---l I 1---t by" the case of a fuchsia in a lal'gl'l'nt branch of art or science the student may > :"; : Ayer'sHair .. Hoek-a-bye. )baby ; as: softly it .lwint"On'r which seemed to get dry faster" than! its rather choose to t pursue. And addition to standard the cradle the mother love t sings ; fady foliage could be expeited to exhaust' works on all branches: of useful! wad . ,I : i 5'; STATIONERY: ) AND FANCY ((500DS: OKALL Brooding/ or cooing at even or daw if, the water, and was not looking "" ,II. Ex practical knowledge, there are periodicals: What will it do when the mother t is ? gone did \ devoted to dispensing Information specially KINDS: I'OIlUI'I'to summer rains of continuance: \ ::} Vigor \ not seem to ht'lit.\ On at last turning it on those< brunches of art or sciencevlnch ...... 01l11ll'till' skies : Rock-a-bve, baby: so \ , all the details and experiments' relatingto 11'W111I11 removing the it give 'or. Congress and St. Julian. SK, IIhlt' the of upside\ ; pot was I depths! own laughingeyes " n:4 your that takes in 1o found I that the middle\ of the ball was quite every new discovery place : '1liFOR\ RESTORING GRAY HAIR TO ITS Nutaiiimh, (:('or llI. ; drv. It had been too loosely potted for one their 'particular t field of labor. ,... ; :Sweet i is the 11I1Iaho'l'r \'OUl'lIt'ot, ." It should be the aim of man, down the every young ------ -- -- thing, and the water ran near j' ': ;t' NATURAL VITALITY AND COLOR. TILCO\, CJIHIIS A ('0., That tenderly sings little baby to I't'ol. walls of the pot ; there was: u notch in the and woman tent who are just entering life, s:>: ,11. : :: rim had to make special study of one or more ;s; 1 too, which prevented a watering 'II. IT is Importers) and Dealers in Bock-a-bye, baby ; the blue eyes will dream of and In this *.*> : t ; a most agreeable dressing, which Sweetest'when'mamma's : from amounting t i to over quarter of an inch branches knowledge, making \ eyes over them it should always be with reference to choice :k' I is at once harmless and effectual for preserving ------ --'- beam . -. 'l I >* ; Pixcmso: IlvcK: lIu\. .: 11x5..1: correspondent the line of business!' : they propose!' to pursue! I r'; the hair. It restores, with the 1 i Never again) will the world seem so fnir.It.tp. asks if we would rl'e'Ol1lnll'llIll'hH'h.' as a living occupation ; that is! the employment t ,r : gloss and freshness of youth, faded or gray, { ::: light, and red hair, to a rich brown, or deep "' '-- .-_. '" Rock-a-bye: baby ; the blue ores will burn grow rampant If J"pinching the: back" bemeans daily: bread. This point having been of determined reading ,. '', to pinch oil" ends of the tender definitely, a systematic course - ) i I black, as may be desired. By its use thin .\llIlnchl'with t that your manhood will learn; vines, we say no. Our custom is tntl'illlOllr should be laid down and all books and \ 11Y ,.\ hair is thickened, and baldness often US STRKCT: Swiftly'burdens the years come with sorrow and I care" vines: in early spring) after all danger of periodicals treating that }particular branch 't, ,' hough not always cured. It checks falling Suviiiiiiiili, C l'nrgla. With must bear. the wee dimpled shoulders freezing i Is past t, being governed in the of knowledge should be sought out and carefully - ; amount cut nway by the growth,!: made the studied. Anv young man or woman : of the hair immediately, and causes a new hniul of I last year If the growth has been great we who will pursue this. course for one year systematically. !! a growth in all where the Keep constantly iju u IIfltll'lll\\lr\ \ luck-n-bye baby\ ; there': coming a tiny11'hose : if weak less the aim the hours to ; cases glands are their rcli'brtiti'il sorrows'u; mother's can't kiss cut more; cut being" to devoting spare 4 not decayed ; while to brashy, weak, oj lips check excessive tendency wood growth, readingand gathering available information - Sat aWII"nape and, to divert to fruit growth_; After all the hearing on the object of Hlr. J&MANIPULATED <'A.5.Nothing ( : having a ) otherwise diseased hair it when its shall\ )be change t to Imparts vitality :song a of time in bunches of have suckers grapes\ set!, or young suit, while avoiding waste light, and strength, and renders it pliable. better can be bail for fall and will- moan shoots of vine will start at the union of the trilling and promiscuous!' reading; as much as ), bear all alone.. ter ('ro)''. Price FIYInOl.LAHS: PER Crosses: that baby must: leaf with thc cane or new growth As soon possible, will I be agreeably) surprised: at the The VIGOR cleanses the scalp, cures and HAS( or FIFTY DOLLARS{: PER TON') as these shoots or suckers\ are two or three amount of solid knowledge) (that will have , the meadows in bloom prevents the formation of dandruff and F.O.I! railroad or steamer at Savannah. Uuck-a-bye, baby ; ; inches long we break them on" from the been gained: in the "idle I hours" of this short ; the frost \ the in Send for circulars giving certificates, etc May never )pall beauty main and thus throw thin strength into tilt period. If you will Inquire into the lives of by its cooling, stimulating, and soothing bloom. fruit and main rather than the Mick- who have become ------ - elutes: any of our great specialists) : t properties, it heals most if not all of the FOR SALE Be thy world ever bright" cradle as: to-day:i is it i is 1CI'C'II-" ers. This! operation! corresponds to that of famous in some branch of science, ns explorers Rock-a-bye, baby thy green rubbing oil suckers' water from and discoverers of truths humors and diseases peculiar to the scalp, or sprouts) :, inventors : new } apple trees in ! keeping it cool, clean, and soft, under 'of and branches AaillCULTUlUL.TIIK amount labor improves the one or two of knowledge, :::1 which conditions diseases of the scalp and i +++.........................................""..... ".......++1. crop. There is no one thing on the garden exploring' and tracing up every avenue care hair are impossible. 1 ri SCIKNCK: : OK lvlclII\o-\lr.: W. W. Lordcrl' better than well-eared vine. a thorough understanding of the i A ISIKAUM: 1I0'l'IU. New"nun, in a paper recently read before the Alter pruning in the spring' there i is no cutting subject i is obtained. This complete learning As a Dressing for Ladies' Hair ; Onondaga Farmers' Club' grants that there to he done until the spring following.Mn. is t then( put into practice and it almost invariably - 'tj. +++"........................................................+++ is some foundation for the common belief 1 proves source of valuable income . The VIGOR Is incomparable. It is color- that soil covered bv boards" stones: or a I .1. F. '1'11.1.1\1111: < a large grower of for life, by which large fortunes are frequently less, contains neither oil nor dye, and will :oituat'llllirl'dl on the Railroad: mulch of any kind is: mellowed and fertilized vegetable plants in the Pennsylvania coal! ,. accumulated. There) is no class! of though Il"thilll'all he ,derived region ail vises giving: plants which have so rare! an opportullih'fllr not soil white cambric. It ....... ..... .. ........ even ;)\ persons \possessing ' imparts an ++* .. .. ....... ++++ except) in the last raM, from the covering been removed from I the seed I bed I and have this plan of study as (arlllcl'I. Farm work agreeable and lasting perfume, and as an I i IN ONK: OF TIm : material explanation) of the edict produced lost manv .,their line rootlets, time to formllv I is such that it must be performed by the ............1 I............ V feeding mouths before, setting out in "4 article for the toilet it is economical and be find, first in the fact that the light of the sun When the shades oI'eve "' I: HEALTHIEST: ][( ; ; PARTS OF FLORIDA !: ground'is kept moist: and porous, no. hagl 1 1I full exposure to sun and wind. He recommends ning close around the farm active labor unsurpassed. in its excellence. I +H-+.................. .........................................++++ I crust: being! formed on the surface by" the sun that the roots be dipped into muddy ceases and season of rest and Idleness in and beating rains ; and secondly, that ants, water and the plants laid in 'oollllll\-It\: tervenes. Idleness is not n healthful rest. Prepared by Dr. J. C. Ayer & Co., For particulars: address worms and smaller! animals live" and bur place for twelve to forty-eight hours or till but a change t' of labor; a change from tinsTVcrrphysical - Practical aDd Analytical Chemists --- FLORIDA{ HlWn, row and die under such a, covering, pulver- small white rootlets, are seen issuing from ( exert irnrinlposetbv the act-' - i/.ing the soil and fertilising it with their excrements the routs It is certainly of great importance lye duties of the farm, to mental[ activity Lowell, Mass. 5'Mf: Fernandina) Fla. to a plant or cutting that it be and their bdies.Ir.) Newman: young while: the body is in repose, is the most SOLD BY ALL DRUGGISTS EVERYWHERE. "supposes: also: that the difference in temperature not allowed to flag and this is a good way healthful rest that it is possible to take. The .- --- -- --- _. to prevent it when plants have been pulled . II. J. D.t (EI{ A I UO., caused by the mulch may have something mental and physical powers arc well balanced THE F'LOIUD.\ to do with the enriching:; changes that up roughly: and carried some distance, or by such a system, and the most robust t go on hchcath it, but for this supposition: we when the weather i is parching. Instead of health and vigor are imparted to both mind final no foundation. Indeed, we may almost laying the plants down would be better to and body. In the cold season there are threeto LA\D: AND IMiliIATIOCOMPA'Y; 215>> Pearl St., New York, : be satisfied with the first reason.: Everyarable stand th,11up thinly in sand or mellow five hours daily which can bo devoted to soil contains an immense quantity of earth Hut careful lifting and immediate mental work and culture, which time is utterly - OFFERS 1 plant food, that is not in 1lit condition for planting: out of n pun of water with water t wasted! in thousands of farm houses. the use of vegetation but must first suffer: poured into the bottom of each hole if the The excuse for this deplorable waste! of time certain chemical changes by which it is: converted soil i is dry, is a safe Practicevith all plants and neglect of mental improvement, that 800.000'r.....* MANUFACTURE-US OF'rIIIRE9TER'N but the few refractories, that always show offence - from insoluble to soluble fitrlll,'or after\ a hard day's work the body is too tired from compounds that are les.s acceptable to at being removed excepting V-itli an and! sleepy to study, is: utterly void of truth. Of the most: those which are more acceptable to entire ball out of u i pot or with the protection Those accustomed to labor daily on farmsare the plant. /Such: changes cannot go on at all of a hand-glass or paper. not more fatigued than any other class ACCESSIBLE: AND DESIRAHLKLAMW ; : I in a'rr dry soil, and they will go on most A KRUiT-ricKKn is the latest! invention. It of people' and such a quiescent state, of E rapidly in a wout, rather than a wet soil. body, while the mind is interested and act i Is eollarof sheet metal four One of the most important of these unavailable simply a ring or ive in the pursuit of Home cho (,study, is! - five inches and the in diameter IX TIIK or high same - constituents of plant food i is the nitrogen the most rt'litful"f all conditions.! with the ortion formed I into half of vegetable and animal res lhlt't.: Ily upper i> The habit of reading must! be acquired if STATE OF FLORIDA, ORANGE TREE: MANURE:, oxidation in a damp soil with free access: of a dozen points like it crown, each point being it has been neglected, by some effort, or a covered with indiarubber disc shield air through its po rOllS surface, this nitrogeniwussc.s. : or languor! will steal over the senses of the out to prevent the fruit from injury by ( Intact. : to a greater or less extent into the door laborer when he himself to combes} At only $1.25 per acre to new settlers:, with nitrates A socket in the fide receives a )light j form of spedall'alllaLlc"for plant 'bottom read, after\ exercise in the open air, which the privilege of selection in parcels of 40 (Undsr Formula of CJeo. n. Forrester.! ) food. It has been recently shown that this: of any the rt..luin'lliength ring or crown, extends and from a light the hosu of will soon carry him off to drenta-land, but n nitrification, as it is called: i is brought about little will correct this acres or more. These lands are located on cotton other material to practice soon tendency drilling light and adjacent to the )line of the by the agency of minute living organisms convey the fruit or down to the hand of tileopl'mtor. It must be understood that no very profitable - and that they work better in the dark than headway can bo made if time la squandered in the light ; hence in a soil under a covering or into basket wagon, or wherever in chatty, miscellaneous reading. To Pronounced O the desire! !Standing on tbe ground, the by Orange rowers ATLANTIC, GULF AND WEST INDIA very of any kind that excludes light and prevents operator reaches for the fruit the points of habitually read what there is no object or evaporation, but does not exclude the side profit in remembering, tends to weaken and the each of the crown passing on : stem TRANSIT CO.'S R. R., air the conditions are most: favorable for le troy the retentive and analytical facultiesof and detaches the u light upward shove easily this exceedingly ingwrtantcheuicalchan ,l'. and the memory, and this is the reason. why fruit it down the Beat :Manure for the Orange Tree Nitrates arc easily leached out of a soil hyI'er'olatill drops through; crown much fiction reading \Is injurious to the and hose. The hold the t [extending from FERNANDINA on the At operator[ can polein hoar.ltlll'llcal'llillg water under stone a or a mind. The ; reason! why our girls and young band and the hose in the !antic, to CEDAR KEY, on the Gulf coast, will not take place as: readily one other or women make no little headway In acquiring the hose can bo hooked to a small moveable [thus affording to the producer cheap, constant as! in an uncovered soil ; therefore we are inclined bracket placed on the pole for that useful knowledge when the amount of reading - to believe that a soil Which has: been purjMj.se they do is: contrasted with the information awl rapid transportation to the best thus thus: allowing of handling the (Mile with : protectdduringseveral weeks of warm of value they which on subjects (markets., : FOIlllESTKK'S COJII.L. TE 91ANURKN weather will be found to be richer in nitrates hose.both hands: or an assistant can manage the are most: intimately possess associated with their The belt of country traversed by the Tran- than a soil close by it but unprotected, everyday lives( 111 answered Iti thou con. lit R. R. embraces aid that herein lies the chief reason of the FOREHTH: ANI) Tilt ATMOSPHERE.-The at- slant and 1 ,uarcitmitllnj;r f ; devotion; j; t to i fiction.j;: .. enriching of the soil under such circum tlfHer'i L'lironich says : From concurrent Their ( abuliim is: composed of sugarplums stances.SELECTING. thermometric observations: male in forests Instead of wholesome thought food. EVERY VARIETY OF SOIL DAIRY 'oWS.-l.oI"Mk first to the and away from them at 1,40 and at 14 meters There can be found no higher enjoyment, FOE EVERY .'.\KM CROP, great characteristics! a dairy 'ow-a large above the ground level M. Fautrat arrives while nt the name time more profitable employment P, o JtO be found in the State a large proportion stomach, indjcated by broad hips broad' or at the following conclusions.: In consequence for farmers! especially the young double chine of the ditlerenceH of temperature men and women or the farm-house, than [ -these indicate large digestivealgpatatlS l being IIl''uliarlyallliptl.'l1 to the culture of which observed underneath the the '\ which is the first essential are foliage study of different branches which have h.yo SIM-TaoPIC\L: FRITH and Early Vegetables, }Prepared scientific principle- producea to the manufacture of milk. :Secondly requisite \I and above the summits: of trees, a current of a direct relation to their dally enjovment. s [and The urge Compact Bodies of Timber a good constitution, delpt| ending largely ujxln air from 'below upwards: is! established in forests These subjects are numerous and of Infinite [make these lands: worthy of CAREFUL K l.datIxt large yll'lclp'r acre.ALpo tile lungs and heart which should I be wt.1Idevelolll'll : and also lateral currents around woods!, variety Wo will enumerate a few : The curfcr * TION by manufacturers of LUMBERI and this is: easily determined! by from the foliage towards the open space beyond. lIt breeds: of farm stock, their physiology, , examination ; but the vigor and tone of the These current cause n healthy breeze care, management, etc. Farm buildings I. i, "'liD I N\V\tSTORKS. constitution are indicated by tile lustre. of in hot weather. The ascending current carries dairying-which carry the student into time' the hair and brightness: of the and horns oil'above the forests the vapors from the realms of architecture, ventilation, heat, eye soil, puts this latter in communication with with all their kindred subjects and chemistry NEW: SETTLERSiParchasing DKVU.BS!: : IS and the whole make-up. Thirdly having determined by her capacity for digesting surplus the clouds, and fills tile office of a ligbtnlikg with its wonders which are but partial food for making milk, look carefully to conductor; and it U to this: no doubt, that ly ('developed. The composition of soils the land from this company are fur- PRIME AGRICULTURAL CHEMICALS the receptacle for the milk-the udder-and I forests owe their remarkable projierty of growth of plants; horticulture, with its re' Jnished with entire free pottage on the Tran- the veins leading to it. The cow may 8J4.'tilU- I keeping hailstorms at a distance" fining and uttthetic tastes ; entomology{ botany ;:_sit Railroad for family and personal effectsto SULPHATE AMMONIA, late a large amount of food which goes mostly PKoriTH SHEEP JUiHijro.-Four years ago ornithology. Tbe diversity! of.the field to lay on flesh and fut but if she has of knowledge which invites every fanner to ; > along Mr. Fleet bought ten bend of shevp, the the station the land says .: nearest purchased. .NITRATE: SODA, its study and which enters Into his broad un.llll''l' udder, with large milk JIJIISatuteliew, for which he paid$' each, or pursue , :1'ITLE.COMPLETE, being derived by veins, it is safe to conclude that her large $-tU for the lot. The first year the wool crop everyday life and labor, is unequaled in [grant from the United States and purchase SUPER PHOSPHATE LIME, -upacity fur digestion and assimilation are sold for $18 ; the second $'lH ; and the third, any other branch of industry. In the house active in tilling this receptacle.' In fait, the $MIJ, era total of $142. He has killed' MX hold the developments which are, being < }from the State of Flori'Lt. SULPHATE: OF 1-OTASH udder I h the first jtoint to look at in cursory I r head, which have netted him more than the mode are scarcely less numerous, valuable - examination of a"' M Jw. f.>r nature U not apt I: original outlay, and still has fifty howl IIr old Interesting subjects of .so'lntercwting Isno CORRESPONDENCE SOLICITED. NITRATE OF IXJTASH. to create in vain.{ If Jt reUAhtlt"'l the buck ': sheep and thirty young ones, from which lie class i>f enple who have a I line of the thighs, well up behind, reaches estimates that he will shear at least '$UiU; field for study and investigation, so much Descriptive M.in and CIUTLAK mailed on MURIATE OF POTASH, well forward w broad and moderately deep, worth of wool. This will give $.}oo for wool time to devote! to it, and from which so application. and teats well apart, and akin Boflandflaxtic. .I in the four rears and his flock'U worth $ 'iO large an amount of pfcunutry compensation W. LEWIS, MAGNESIA, it may be inferred that nature has provide" more. Of (wura'their keeping has been a can be drawn, us American farmers. Thousands Land Commissioner. menu for,filling) it. I If the udder be a small source of exit-lute but the benefits of a Hock I ot precious hours are wasted which Office cur. l\ew't} a nd Seventh +ts.t SULPHATE.OF FODA, round cylinder, hanging down in front of of hheep in keeping down! wce ; the thighs like a six quart pail, the CU'ocall I oil a farm almost coinitenaate: for their fnn minds to thought and training them to men Ilf Strlvtly Pure Ground lIou(>. not be a profitable milker, whatever! tli '-H- A fanner of experience| in wool growing; ha* tal vigor, compare In some degree to the Iiolt.iIE'DIIEW.1Vholeiale the apl.aratlwshemey> have. yellow .skin I well said that there is more money in grow symmetry, strength and vigor of their per and u yellow ear (inside) are alm<...t universally lug wool at twenty cent a jtouJid titan to sons.: In place of the, dense ignorance, which regarded as present in a cow that gives loan your money at ten [per cent, Interest U too often found in country neighborhood, and RetailOOKS .1.1CJIAS. t Our circulars give full particulars and aremail.l rich yellow milk ; but.ufler you find time in I I intelligence and a high ktandard of self tultitre - free to all will interest dication mentioned alone, you may admire ,, fcbould lie the, rule. A change: in the applicants. They as other inU WI: 5 ly when we assert that branchc' taught in the public school KTATIOXr.KY, you if interested in Agriculture many | > as you .pleaouch asa Vegetable might: you arc las. Hall' Sicilian !Hair Renewer be aid or Orange Culture. ti"'t-'I fcHcuUheoii ; a long lim tail ; a I U llIl..lto materially in the direction --- --------- 1545mOr. beautifully turned, dishing face ; drooping( ;I the last article of the kind} sold oa the wp have endeavored to |*,lnt OlJt.-'luhi/ And JII'SIC, waxy 'horn.a small, straight, lhu l leg, or American Continent.. 1.1.Jnaltriaallaa._ de- J'ryittrr AltTIIUIt (,, FORD, any other Jitncyj-oint* ; but du not look for I luonxtratuJ this and the article is an elegant _. Ti 50 W&T lUr STBET : these till you ha\efound thernliaI".-.\''(- and cleanly one, without which Wt think i A -BMEa'* WIFE, in s speaking the smartness DENTIST, tip,ud lire lfN.t J'iur IYd. no toilet complete. Messrs. Johnston, JIol. aptne-u and intelligence of her on, u luvvay Co.. tm; Arch tre4, Philadelphia, lad six old, to a lady JACKSONVILLEFURIDA.. Fourth St., bet. Centre and Alachua, A TIIIIWTY+ Fec'.w.u.-Thtt watering of ,' are the agent; fur the article, and} when our : "lie years ran read l fluently in acquaintancemid ot .plant* in twits i U an art to U learned.. Differeul allpart Philadelphia (friend return (room ( I 'uj-e May the Bible, relfl'l1t tile whole catechism and -i/j/ tf FEU.VAXD1NA.: FLA. tare in required. at different , cuaoii I they should and at j' certainly procure home of it. weal onions as well, an his father." '.Yt'I. different ktagiai of growth. When ttt I We know of no such article extant for the another" added PRINTING, In style and at rent it is .cafe young hopeful yesterday JOn every to let the root become almost hair and thus r lkbool Uook u Speelallj lowest rates, at the MIKUOK office. dust dry, and actual wetne if I destructive. I I j-ak in uch decided andemuphatte I licked lUwou, throwed the rat" tenui.-Oceu*J wiui'upe MuytfJt into the well, and stole old! Smithy gimlet.ll . S - 1 ernans ita, } ),m T .. '1'ht1BE 'ru T11E -.. .\.,... '\ 1'JX .. .. ac IJlJlI"rn ilitlt011. c"Jt.tM 4 A.1fI . i .1 fUr "2 1 ii - six . n.t wwmthe. t ,. Jlux li4. op ALf. $r7 jjhr3fuw1lilMa. < }iua. . -. .. . -' ...,( .. , tt, !" ". ,.t2'n. .., ojf'!! ..,II'J.! E: .. .....i -" .... ,"", ,,,;;Jt"f, .1' : -- .- -S-- 1 : : : -., c , THE FLORIDA MIRROR : AUGUST H. ----- --.------ --' ---- -- ..- --- .---.--.-. -------- _._-- .._----- _.- --- -.- --. ----- .-- --- -. .----- LOCAL REFLECTIONS. "(1Rsrtlt CoiMifftvftijnia" Statistic Vegetable iroiclno tn Arretlondo.Klit'ir 7VtnT nt (I ('emits. And on the same day there will be held ' We have examined the returns of the ecuSIM ; Mirror :-I promised to give you .\ ('n"e of first-das* Prints, worth 1)!I cents, in each (Constables county of the each/State a General being Flec allowed . for , enumerators! for this county, on file in some ideas!'! of the result of the vegetable ju"t received J. >'0>. T. vim's.) lion county - entitled to ! .f ; the Clerk's oflicc\ nnd obtain tile following In this section this number of hundred registered! voters in the h_ ____n.____ _. ______ _... .. _. __ crop : year, For llcnt.Two every that '-t h results: acres 1.ll\lIft.lnllt mode and time of planting I county; 1'romM; Amrmr, no (county 1 ii(yeti+s ttwdlill -huu: WOOD'S( DISTRICT! AMF.m ISt.AXD.) There was! planted 111I melon and . a tl General. J. l A. J. Russell Vegetables repair in good. "darhhurhtloll.lIl1ll''pl'l'IIIII! that each be entitled to nt lent Finlcy, Major White ]persons.................. .................. !Nil : in this !section' the past, !season at i desinilde! n* summer residences.. :Stables: : Cunt. !hl of the number of two , Hon. C. 1'. Cooper, General: Win. taring, Colored........... ......... ........................ 1 ltKV I least t !<('\'IIt.t'IIII1I11lretlll\'fl'i ,, but owing to would, l provided, if tt 1 mrh Apply l l t to l registered! voters, \rtll'1 } t A. St. Clair-Abrams and other Democratic White lIIalt'IJ\cr! twenty-one\ ...... ....... :2w!;: II 1'1.mnett'Cowx1NI'RmvEM:"( : nsT: ('o'Ir\sv. WHERE, the of the State of speaker will address the people nt the following Colored males over hn. ty.olle........... :2.!;141<> the dry, weather, early and heavy and rmntinutil I (Opposite: Kgmont:) Hotel.HVmfrd Florida. of A. I D.) 1t.ilntnc: ; determine by a .. places : 0':11.1J.qTlUlT, ,unr.SI1.: rain later, there wa* not much over I --- --- vote of a majority Lit'all the IlIeml'J, dtl.telt" Orlando August. 24 White person-! ......... ......... .................. 88 half crop made, andsomc! men planting at Once each .of the houses thereof, that it is necessary Tuesday.Apopka ) 'I City 2' Colored I......... ...... ............... ............ ... IiiWhlh' low hammock land almost t 1 Angu Wednesday.Maitlnml ! : August/ :a!II?, Thursday. tattles! over twenty-one............ :IK!:.t I crop*. All who met! with no disaster. used .'\500' busliel: :Seed: Potatoes.' : C Constftution t of .lhl State, and did 1 I ('ikI t San ford or Fort ]Reid l Augusi 27, Friday.Enterprise Colored, males over twenty-one.......... l." lUiaAXn's A II. :\I>n:". :such determination upon their respective proper economy' and worked close: and journal, with the yens nnd, nays thereon! , I August 2N Saturday. ( MSTKItT\ MAIN t.\XI hard have. I thillk. tlllllWI'II better than'tlily did refer the to the I Orange! City, August! :'M, Monday.VoluMa White persons...... ......... ................... 1.111 ; XO'I'I('I: CU' I.II."I'IOX.: : mud next to be chosen!alI and whereas LeI"lutn1'i11 I the August ill, 'J'u(': q Daytona, September 2, Thursday.Crescent White males ".ter twenty-one... ......... :20!,: other crop'* usually planted in Florida. /(, nil,nii'l nintfiiliif; tlif t>" sv'r;$b oIda;/ .",',,,1(' of! to wit I.1tlre: the Legislature of\ A. D. liI!>, did,1 by v:y City, September' Satifrday. Colored 1 mules: over twenty-one.......... l'.KtKIXo'S : I \\\TEIDIII.II-'e:"( plant here the rattlesnake ( nil! the member elected to eachhouse : Palntkn, Septemf-'r C O, Monday.Welaka Kxo'w'vk'that I, W. I II.> IILOXHAM, Seeret.iry a Jajoritof , : l'I"TRIlTIS' .. \SII. or Augusta melon, which in considered t thereof, agree to such proposed: revi- k . : , September> N<, Wednesday. I of State of the :State of Florida, do 1f Tocoi, Septembers), Thursday.St White 1 I persons! ....................... ...... ..... 4lsu! the best t for :shipping; and, properly hereby notify all\ and\ singular: the :Slierill: of ion; nail whereas the Legislature; of 187I!) did is' < Augustine: September' !II!, at night.! Colored......... ......... ......... ......... ......... *' :21 planted and, manured, ought to produce. NHI' ) I the several (Counties' : of the :State: of Florida, liv resolution duly passcdrernnittendtothe! , l' Green I Cove, :September: 1 III<>, Fril la V.lltlt1ldHlrlX. White units over twenty-one' ..... ....... IIU\ I I that electors of I the next election( t for; the members :\ September 1 1.1. :Monday., Colored males! over twenty-one.......... 101 melon* per ..Il.'fl''t' plant ten feet apart .\ Gc; >n<>rnl KlccHon: of the I legislature to vo e for or against a ('ul'h'ny, and iimnuiv in the' hill with cotton (c"I\'lliol, and 1 did thlrdn provide,' ami direct - Mandarin, September 14, Tuesday.Pottshurg lM.ARl'd DISTRICT' MVIX' I.\SI''Irlh' . September 1 I 1.1, Wednesday.Mavpnrt \\ person*......... ........ ................. \1.-*; '-eul.! stable manure, or Peruvian guano ; Will; be held in each t County in Florid-i. that. with tIlt.'I'rl'tan'the:: notice of of State the (General should; hHor.l"llah' Klection - Yellow( )\ lth, :Sej: : >teinberVedneilay.10, : Colored........ ...... ......... ............... ...... fi42 lisli guano was: used,ll by !some thi* year, but I I' ON: TI'l! ::11.Y: :\Sl'CCKKDINd: :: : ) : T1IHFIRST : to) he held in the year LSSO' a notice of September Thursday.Fernandina White mule over twenty-one............. Ill owing to disaster to the I am unableto Miih \ instruction - crops I fel'oIHl'IIItioll proper September/ 17, at night. Colored males:' over twenty-one.......... 101 : MONDAY() IN NOVKMnii to the mode, with * Callahltnl'ptC'lIIhl'r:; I 18. Saturday say how it will\ do for melon PIint; as! l'ompliu1.c : :, A. D. 1..0. t King's Ferry, :September/, :'jn', Mon'day.: White population' of county......,....... .tlil: > !) about, the 1-t of March fllI'X"rtIIl'J'IIlIIarl'I", !'lIel recommendation; 'L Hatdwi'n, :September; :21 I, Tuesday.! Colored....... ............................. ......... .V lll-- sooner for :Southern 111:1 rk.t". The said Tuesday hliuug't1e'crnmmiI!. day of .11'.I'IIfiJt.i ; given notice, and ut'such, the /1'\0111I1111- _____ ____ eTnnltev. > ltol Ilerll\ ( said l November , . .. Total.............. ........ ...... ......... ......... (i.ViO!, ; 1'.ettTUts.-Tnnutnes should, be sown in are hereby given n to the mode. ; J.Ikill refurneil, on the 12th:! beds, mad rich and in about compliance with such rIJJlatlol: w Excess: of t'lIlllrl'll, .>!I H. : warm January, Fora Oov'rnarand Lieutenant (Governor t from n visit to his sick mother in .\Iaballlll.'ti : 1st. .Any tll.tor desiring to vote at such of I the :State of Florida and for Four Electors the I 1st I for Protect cold White males: over twenty-one............. 702( : early crops.: from election in ftvnr of such a Convention, sIu111hnt.t Ills( health lias greatly improved.CAITAIX ]. I Colored male over twenty-one .......... !I21 I:!I and if too thick transplant to other l'l'll"rhl'lI United, of :States President tutu Vice-President of the writl1 or 1'1'llItt,1I the same ballot iff ]HIXKS I; ; has--resumed; 1 his place us Excess of colored, I l.Vj.; \ the (,,1.11.. i* over transplant in field, in For one Representative: ); of! the First: Congressional on it Ihl'IIIII'.of: the person or Ic'rl/n'; , Oldest person in the county, C'lItll:1I1itla:: rows: five or six feet apart and, three feet in District of Florida, in the Fortyseventh \'II.tf"rlir any ottiee or ofHees at !': < tnnuuuulcrofthe Wnltrn Trfn*. II is vacation nail ; : on ( ,.j (colored), lI l..llOJ. ro'l' plant Hathaway's Excelsior: nnd (Congres* ,,1'1111' United, :State: \ ; tl,1, f.writt'I'ol'I'lilt.I, tJ''IIIIl ,,('ell\1 tn have agreed with him, judging For one I Representative of the :Second: side (' ( as : names: are wl'ilt1 from his: improved( ll1l'pellrlnl'' (". The total population\ of the county in I 17''> the ,\011('. They carry well\, and are hand Congressional) \District) of Florida in the printed' and not' on the" other ftide. the words> ;- u .... ._ was .Jti-of: which 2,277 were whites: and :nlllCIIIltI smooth' ; average price during the Forty-seventh Congress; of the {'lIitl'lllall'4.:: : For 1 Convention ; and any' elector desiring fi Orn river front presented very lively appearance li"0! eoloreil. The white population: \ Im* season: aho' out :2NI> per Jin-hel crate in market .\11111111 the' same\ daa. (General Flection ]have to written vote' against or printed: on Thursday.! The steamship) increased ';'O11111:! the colored I.C1O7. The netting! about $1 :!."). .\ good yield. i I.* will be" held the :-1.11. thereof above prescribed. the word, tirn, Trfuji, Ci'yl'ntilt; Jtnvtd C'lurk and 1 Flora !tendency, now In to an increase:, of the white about l l.Vi' bushel PIT acre, the way we plant\ In the County of I I.oIt; uimbia for Senator:: ".\!alnt a Convention.1' :seven vessels! loading! with lumber nnd.} one population-:small fanners, lumhcrmcn.) togvet' ; and cultivate.\ I from the First :Senatorial District ; NOTE.Nothing hl'rdl is intended! tnll'c'- who desire ' discharging\ cargo, kept nil hands busy.! and planters. The county Is: well adapted : \, (Crrr>iiiEiM.-\\\' plant cucumber) in January III the (I'"lIlItof Jackson for a :::"lIalllrfI'III.i or\'l'lt against 111t1t..tnr: a C'J\ltllll 11,1', may! to lot v intendto : -- -.. .- to rice growing vegetable und.I fruit farming and! in four feet time'fbiril Senatorial District ; : February row apart ; i i vote for any i person' for any ofllcc, from In the Counties C I of Calhoun and Franklin The Western Texan. sugar cane, mind root crops of all kind.. after the 1.,1111.i* OV/T work to a stand. l': qi This popular steamer sailed Thursday I elector. I is to permitted to vote more than' lt. cotton seed, :stable mannie: or li-h guano; ; 1 evening" nt 7 clock for New York. :She; Republican Meeting. any kind I of\ guano i I.* good for t. cucumber", I In the (Counties: of Uh'rlI: I Wakulla I one: *ballot for shires t 1 and ph'llIf, for! or voting for a both Convention. ,: !person r had ten from this port nnd fourteen .\ Republican: meeting held in (fora Senator from the :Sev'inth: :Senatorial: against passengers was: Lyceum Plant early. Improved\ White :Spine: ought District Only one ballot should. be received from Jacksonville. l Her freight list was Hull on Wednesday! evening.; The hallWay to.roduce) :2oo I bushels: per acre and \\ ith In the;; (County of Jefferson fora :Senator 1'111 each'elector I at such election. small this trip.Quarterly_._ __ u fairly lillcd 1 with a very mixed, crowd, \proper cultivation :iHHo( ) IIHI( per acre. .\11 I fiiim the Ninth'Senatorial, : Distiict( ; be I :2d.!canvassed The vote 1 cast declarations on this question and n.turntllt'ltIIfolmll,1 shall the majority of those: present being colored will in In the County Hamilton for 11 :Senator all Conference. crop net m.irket about ,|UH'< per : made hv the hl"p"l'lnIII,1 from the Eleventh :Senatorial District men, women and children. The !stage was> crate.IKXS.. ; ( ': +'Ittg *, and the :State The Quarterly Conference of tho Methodist In the County Alachua: for a :Senator: : 1'lard. I Episcopal Church) will bo in session III occupied\ 1 by u !scant representation\, of white1'epuMicans. { .-Plant l arty Mohawk' I beans: here from. the 'I'hlrl.t'lIlht'llatoriallj..trid:: I )m '; at(Canvassing I the t UI.ml. in ,.:4lll', manner; alt -, : If there were other* \present! early In January fllllllell'I'IIII"' later. <!h'n- In the (County of Itradford. for f a Senator:: ,all' till', I'lt : II ttr persons this city'on the llth and 1 1 l.'ith of August.Services ; I for ollli'e nt said election und required, bylaw from the Fifteenth Senatorial)' tr l't they were not l'rIlIll' lll'lIt. l'r.llItill' bean i I. atl..rat'IIfPota I ; to be eurv'asscddelured] and I ! III1 will be held to-day by the Rev. T. crop\ In the. (County of Putnam I for' Senator: : rllrll.,1 \V1farePresiding later.I' The first' !speaker' was jcncml Lcdwith, ., ulDuval toes have: not \proved profitable, so lilr.'t' I from the :Seventeenth: :Senatorial: District ; Ilaw I The Ilh'lllnl of Slui-itls: }I. ( tll' _. ,____ h.___ ) formerly of the Confederate :service have so little experience in cabbage; and I In the (County of Marion for a Senator: requiring thl'l to cause a notice of !' cauliflower that I that election to bo 1 in . can only we published sow ! say I newspaper Fanncru' Monthly. and now Republican\, candidate, for I.'ull.n.ulltUO"l'fllur \ H''elill )bed, in :September.:: \ : Oct'ober), and November. from the Nineteenth Senatorial nnd District) ; printed, in th"l'"lllr. if there I be paper in (In the Counties of Dade 1'revard for I We arc again indebted to Mr. J. 11[. }still: The General wearied the audience ) I a :Senator: from the Twenty-first :Senatorial: the county! ; and, if there be no paper 'pub of :Savannah:; (hi., fur the August nuftibcr, of for nearly two hours, being very ill at Jo'EItTII.J1.tII"-\\\ used( the past season I District i ; h'ell time. euuutv, they:shall ('.III"l'ut least i I this( admirable( agricultural magazine, which ease himself! and decidedly trying to his almost: altogether fish guano and find it In the I County of :Sumter: for Senator: 1i\'l'l'll.ir.! oftl.* "'ltt.C to be pn ll'llll the does: well\( for almost all crops.) h 1:. from the TWt'lIt.lltlrtl"lIatol'ial:: District' most Iullt' II county.)'. continues to maintain its high reputation.i auditory. Some one remarked, in "Ieof| ; 1 ."' WHEREOF I have hereunto . ; 1F.vl/ : , .Ir'c'biedo.fuyoetz' In the I 'Olllltof Walton 1 for' Senator: : llIs\ j Its' .valuable matter and elegant typography his long hesitation in engaging in the canvass from the TWl'"t.linhic'lJatorial: District: : !set my hand awl have here J II give it permanent value. that it took him as long to "stop when hmw.'II'r.sTJos.The: :"( Georgia; :StateConvention In the Counties: of folk and Manatee for untlltxl'l, the Great at Tallahassee Seal of the --- ----- Senator:: from the (Senatorial : If FIIIJila. , I he :started lu. it had to commence, lie deprecated adjourned after an eightday'sM'ssion a Twenty-seventh the " Fertmndtna [r..*.j] Capital, this the fourth day of Work ' liar. District on any disall'ection toward( tile candidates without making nomination forGovernor. : : August, .\. D. 1S80. '. General has published otliriiil From point of view the In the County IIf'olu*ia I for Senator:: Gillmorc particularly :Mr. Oonovcr! who he said our action W. D. 1JLOXIIAM, from the Senatorial District of the minority A-as indefensible Governor Twenty-ninth ; ;0-td; I : I notice, inviting- proposals for constructing had gone to New York to get help for them, Col'luitt hail: << :'I''olt.' ... nnd no other In the (County lit' St. Johns for Senator:: -- Secretary of:State. I jl'ttit'lnt the mouth of the St, John's River, nil, In pl'oufIf )fr. Conover's ability to be candidate nnd over :sixty-two, slid all 1"1/1-/ from tlip Thirty-n'rsj) *'natnria(1)istriot.(, } : I y and also! ut the entrance into Cumberland Governor he raid that ho had succeeded 1 in bincd had but 1:1Thl': : minority made: n j On the :same day an election will) be held r.fOHY'S'RUISlla:-; t factious nail caused in the County\ of )Madison constituting; the MOItll Sound l In.. the'udjournment 'between Georgiannd I.'Jorll( Specification opposition\ ( MM? having him* 'hf elected to the Legislature : without, nomination, und( 1'1'lIlh"lIl1torial: District, I for a :Senator to I blanks for pro osuls: to obtained hud then succeeded in getting) appointed to issue:, an ti nddres: to the people proposenow \The till the \'III'IIIII' occasioned I bv the resignation by addressing (Q. A. Gil I more, Licutcnant- (inptrolhralthough, ( & no one recollected that majority )passed l a resolution recommending; of Hon. Dennis) latgamiwwimo: : wa elected Oiil.v IHroct Uiio to X('" York. (:lolonel of Engineers, U. H. A., United States lie had ever held that ofllcc); that he then Governor (',)I'l'litt.' He ran only he defeat I Senator for t the term of four year at I the (General Election held I the first i , Oflice cd by a fll"illluf'the faction, opposed 1 to Governor on Tuesday : UijUding York. : Engineer Army New succeeded in himself elected 1 the ' getting to Colquitt with the Republican: <<1 it Unl r thc' fi""tfollla: .\ of November A. I D. Rids: tn.m. opened( August 31st. Legislature again, und t finally .succeeded in is: doubtful If they will defeat' him lsi'I ; -- In the of }Duval, constituting the County ! getting vlcctctl Senator und in procuring the l Coutiy.4J sirs. Eighteenth; Senatorial District} i for a :Senatorto : . ( The Board, of County Commissioners hove nomination for Governor: his whole ability MAKIXK. I till tilt''IU'IIIIl''' occasioned 1 by the resignation . been in session the week in U'nerllll.t'tlwith'lI opinion consisting I of Hon. .F. H. Durkee, who was, THE FINK: STKAMSIIIPS: : ::, during ( past examining JV,rl j''e''Lamll ! of elected. Senator for the term of four *, nt in his: ability to take cure of himself, a qual year "'I: : ) the asscMiicnt.rolls. They have fixed HIGH WATKU.: I the (General; Election: held on the first Tuesday S'nx ''I X.'S. the tax for the 111140, us follows ity which we fear the General envied him. after the first Monday. of November. .\. CA1T. HINKS: county year : , : ..... . ( did\, Saturday: August u. 1:15: \. M. 2:21:?::! I r. au i. He not that lie had done . 1 t County tax l'roI1Cr..1} I mils. allege any public Sunday, 15....... :!::5I": :'M2: : D.):I 1X78" ; I (' '\ DALLAS, County: uchool tax.........................21 mills. service, but that he had been very goodto :Monday<< ".. 10.,... ::02". ::41" In the I I'ounties of Taylor and afaycttc, .'.119. RISK.ONK . i hilll l'If. A very tedious reference to the Tuesday: 17..... :It1. 1):1: I(0; constituting tho Twelfth: J&nutorutl District, I Bridge tax.l;;: mill. Wednesday. \ i 18..... f :U" 0:12: : for n :Senator to fill the vacancy occasioned : of the Uh"l'tl.tll':; Irate Sinking fund and interest tax........:2)?) mills.> Legislature, some Mule Joe Miller stories Thursday, ., 11.!) ..... .::10" 7:1:1::t:t by: the death of Uon.::E!!:. uM. :\Il'ulwho for New York every wi Friday with very little point, concluded his:' }part of was elected 1 Senator:; for the term of four (to the tide . I Making tenmill:! for the total county tax. Friday, :20...... 8:(lM) $::17.tltlnyF.l1. lit ) the performance.Col. yearn, ut the (General; Election held on the Thl line transfers mills having!! no to make The-State tax in in nil ; seven making lonI:1of t'n>t 1'1I1.oel.Iuftl'r the first ) November betweenFFRNANDINA llfcbee followed ' tut:1ll'tmn and State tax seventeen mills. ill'l'rr temperate .\. 1). 1S78! ; li s language, giving) the stock Republican: arguments August! .V-Sch: Carrie WiMrr, Willev, New In the County of llillshorough; constituting AND NKW: YORK. Cotton Seed Oil. and with a very mixed up conception I York. the Thirtie'th Senatorial Di.-trict.) for a I i Oilers, the . Augustus) :SteamshipHYrffru Trios, 1 lines( :Mills for (expressing the oil which is: so of State ammo(, made out that the $-tl'S,- New York. Senator to till time vacancy: occasioned( IIJthe 1SKST AND) : T'RANSI'IIiT.ITIWN , resignation of (Hon. J. T. Leslie, who waselected CI'\'I'.1 abundant cotton seed are 'being establish-( IKiy) saved hthe Democratic State nun.m.1 August 11-Rrig CiinJlue E1.1',11'arucr, Senator for tho term of four years: at } SIIIPPKRS.Vegetables : 'P : tl I all over the country, Wo understand .. ml'nt'in the last three yearnv u 1 New York. the General EI't'lil.1I11C'I,1: on the first Tuesdav und Fruits: will receive serial g that the machinery for u cotton seed nil the contract system of hiring convict and Ch August rlc..wn.! 12: -:Steamer City l\>;nt, Creascy, after the first: :Monday of November A. |I1I:1"i i care in handling. ) : mill cat'bo ,obtained for $2,500:? und upward by the reduction of the county school tax, aselfevident CLK\lIEI'u And in each of the resju-ctive Counties 1It'1 j 1 I 1'\: y Xtm .\\'cmnln.\'lX: i in-cording to its capacity, .\ ton of seed will blander<< The Colonel is: a giwulvolitical .\ 'uttdlllllll'r:: Rl'h""I'lJl.. Oitfeit, the :State: a General Klection: for its coiistitu- j! tH."T.tr.i : . yield 20 pounds of oil, or about one barrel, [ speaker und exercises better control (Powell, Philadelphia.August ) tional number of members of the (kttenmlAssumbly i I The traveling. public are offered 1 the a'1- I und the residuum will be 8oO( pounds: of oil of his tongue than of his i eii. No one !4-SdmtxmctEllmes:; 1 /111(111I, War- : to wit: j vantages of a DIRKCT LINK:, "TfIH"rY till tun, Philadelphia. .\ CHANGKS. Connections cdke worth 80 cent j>er 100 pounds, und 830Miuiul could except; to any language used by him, August 10-Schooner Fanue 1J". Juhnnia 1'"l'lInhil1l.tUllt J three; Jacksonville with all htcambmts UUllt for all '. fi | of hulls good for conitOBting.| : The and we trust that thin will be the spirit of Outten, Philadeli.hia.August :Santa Walton Rosa: county two two; I 'points on the St. John's, Oddawahl. and nil we do (not know the value of, iw it I is used the campaign. lIe mast have rather fctrctchcd } 11-Schooner Stint C. t'nmt, Sylvan Holmes county one; Indian (Rivers, and with Transit Railroad for various >osiug it worth hit conscience when he wail I lie believedthe us, New York county ; at Fernandina fur all railroad stations : purposes; vupi Washington: county one; August 12: -Rark / s only one dollar per gallon the result of the Republican State ticket would all be York Franklin county one; manufacture of one ton, say 40 bushels, elected as well us the Presidential ticket but August Si-hooner H'. U. J would be that doubtless New York. Jackson county' ; AS LOW AS BY INDIRECT LINES. : was for the jury. The audience Liberty county one; August 13-Steamship' IVmttrn Vita IinemNew Oil, 3.V, gallons, ut $1.00.................$35.00 were well-behaved, and showed great York. Wakulla ttmnty one; .Ri Through! Rates and Bills of Ladiii" I I Oil meal, 850 pounds, at I 80( its..... (;..&0 .atienoo under such long speeches on such iadsdcn ('1luntthrc'l'; I to all points. Public Lion county finr; For passage or further information School Xotlcr. I" hot , :Per .ton................'.*...................$41.40 I a night. -- Jefferson ('tllt; ) f.lr; I to applyR. A general examination of public schoolteachers I The cotton seed is gold in Florida at 25 cents i }Ia.lheonUllt) three; W. SOUTHWICK, Agent. Ve r May of Fernandina will be held in schoolroom NO. 1, '1'aylorcounty one; ;per bushel -or $5.00 per tun. There would We Frrnandina, on Wednesday, the 1st SepteiiiIKT } Hamilton two F'eruandina.'tier . are pleased to know that Mr. S. A. county ; C. II. MALLORY (y).. N'e1U'to in commencing ut ti o'clock: ; a. m., anti at & m j be a large margin of profit the county two; Svrann I Is 20 Fast intending to have executed u\\'annl New York. a newand manufacture of the seed into oil Callahan on the following Saturday. All Lafayette county one; 1 __ __ ____ :2-i fC. complete' lithograph uf Pernandiua teachers who wish obtain certificates ------ to map are county three A cotton seed oil mill would be an admirable l'"hJllhil ;; F. A VERY 'I attend other upon which will be shown the prex-nt earnestly requested to one or the Alachua county ( ; , enterprise for Fernandina. We have boundaries of the city.11r. of these public examinations; Levy county two;our A ! very facility for buying the tl't.'llll.UtI all the ( Chas. Lewis has opened a MibsvriptionXMik W. .\curt. MAHOXEY' of Schtlly.Itrick Hradford county.; two; 1 oil cake manufactured could readily be Hold and as but it limited number will boprinted --.-- lay Maker county one. one; the State. There several large oil county) ; HOARDING STAHLES.CARRIAGES . in are I JH.TSOIIS wUhing to I t't'url'1'l.il" Nassau county two; 1.4'EIIY \\J . mill* In New Orleans and one near Nashville.FtTuandina should apply without delay: Lime, Duval county f.lur AND Cement WAGONS ought to have an oil mill and a -- ""- Plaster. St. Johns county. ; .To and . 1'olusit one Train ) ; fn.'Ult\1uleM rico mill to begin on : a ('Orton.factory, u Church Service -.l/orroir.. *IrATMXBOBX Orange county county two; ('S'fUC FOR HAULING, ETC. tannery, a wheelwright establishment" for PKWBYTFJUVX: -(Rev. Dr. J. II. Mvers, at : jt* un's. Puttauttouutytwo; '. FOB .: furnishing timber tarts.etc. Vegetable (rates 11 ti(')lox'k a. m., and 8:00: p. m. 'fI. Marion county two; HORSKS t.\LE .lust Jleceli-eil HUGGIES, HARNESS. # ; M h.'TlloI' 'THe.J.tkill", ut 10:30 o'clock 1 : :Sumter cuuntytwit; s houM bo manufactured here and vegetablet : T. ) u. in., and S m. 2. grown, to put in them, along the Ft. Mar)'*. Services conducted I' by the Itl" '. J. R. Uy.ROMAN :to) tack Com. li.I"rull county two; y4-TEI1MS: C.tII.-4i along; the Transit Road and on Amelia 15D: barrels IVarl (Jrist. (un1' ; XA? Otlioe and trt'near C.\TJWLll-ltl" ( tuMl-J'int J. O'Huyle, at u Island. A few Jive indu>trit* of this sort 10:30 u. in., mid r:M p. m. 100! barrels K. D. Meal, Manatee l'tuutoe UnJtl Street 4< _tfSU1JSCRIUE t :+) lioxo. Ikuon.WO Dade county ; ----- - would at once enlarge our j pnlation and Ertstrrtr.-Rev.: O. P. Thackaru at 11 :; bait Tiuioihy Hay.C llrevurd ('OUI1"tnl one: TO THE MIRROR. PER- uur bushttsy.I o'clock u, in., and ":.'!') p. in. "u iacks Oo1t'4. A. II. ?\on:.:. Monroe county two. ?l far six months. I I _ v--- 4 4 -- .. _.. .-' ; ff- .;;;,.....-. -- ; -T ....L T-T 711E .u.'Wla.. Y s=- Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2011 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Powered by SobekCM
http://ufdc.ufl.edu/UF00054505/00077
CC-MAIN-2019-18
refinedweb
38,408
76.72
I. That being said, I’m more interested in type safety being understood more as the extent of program correctness rather than just making sure what I expect to be a string is a string and not a number. The goal of this article is to present techniques that you can apply when working on your day-to-day tasks to increase your confidence that your code is correct. Often in our programs, we have to handle different cases, and the majority of bugs are caused by handling a particular case incorrectly or not handling it at all. This is indeed a very broad definition of what causes bugs, but the remedy is also generic and has many applications. To address issues that originate from incorrectly handling decisions in the code, we use algebraic data types, a popular concept in functional programming. Either left or right An algebraic data type is a kind of composite type (so a type which is a result of combining a few types together). Sound familiar? Yes! We have a similar construct in TypeScript, and it’s called a union type. Result type accepts only “left” or “right” value, “forward” is not assignable to the type Either. Is this an algebraic data type we are looking for? Not yet, first we need an interface. type Left = { tag: "left", error: Error }; type Right<T> = { tag: "right", result: T }; type Either<T> = Left | Right<T>; Either is now a tagged union (discriminated union). The TypeScript’s type system is structural and tagged union is as close as we can get to an algebraic data type in TypeScript. This notation is actually very close to how we can export algebraic data types to JSON in purely functional languages like Haskell. What’s the benefit of such an approach? While it might look like unnecessary boilerplate, it pays off. We can now simulate pattern matching with a switch statement. The function allows us to match on a tag of a value of type Either<string>. Right away we get a hint on all values from which we can choose. Now TypeScript knows that the only available members of the Left value are tag and error. The result is only available on the Right type which we know doesn’t fall under the tag that equals left. I forgot to handle the right case! Thanks to specifying the match return type explicitly, TypeScript can warn me about cases I forgot to handle. Now, match returns a string for every case of value it accepts. Now you should have a grasp for what algebraic data types can be useful. The reusable implementation of match that generalizes better can be implemented using callbacks. What’s really neat about this particular match implementation is that as long as you get the type of the input right, the rest of the types for a match call are inferred, and no additional typing is required. Before we look into a more complex example, have you heard about Either type before? There’s a good chance you did! Either type is often used when we have to handle either of two cases. By convention, Left is used to hold an error, and Right is used to hold correct (“the right“) value. If you have a problem with remembering the order and the “correct-right” analogy doesn’t stick, think about arguments we’re used to and callbacks in Node.js. import fs from "fs"; fs.readFile("input.txt", (err, data) => { if (err) return console.error(err); console.log(data.toString()); }); The first argument is an error (left side of the arguments list) and the second is a result (the right side of the arguments list). If I got you interested in algebraic data types, take a look at fp-ts, a library which defines many different algebraic data types to choose from and has a rich ecosystem. Type-safe reducers The very same technique we used to come up with our Either type can be applied where using switch statement is already popular, in redux’s reducer. Instead of having an only binary option of Left or Right, we can have as many options as action types we have to handle. For the record, we strive to optimize for reducer correctness and ease of development thanks to accurate autocompletion. enum ActionTypes { REQUEST_SUCCESS = "REQUEST_SUCCESS", REQUEST_FAILURE = "REQUEST_FAILURE", } type SFA<T, P> = { type: T, payload: P }; const createAction = <T extends ActionTypes, P>( type: T, payload: P ) : SFA<T, P> => ({ type, payload }); const success = (payload: { items: Todo[] }) => createAction(ActionTypes.REQUEST_SUCCESS, payload); const failure = (payload: { reason: string }) => createAction(ActionTypes.REQUEST_FAILURE, payload); const actions = { success, failure }; type Action = ReturnType<typeof actions[keyof typeof actions]>; type Todo = { id: string }; type State = { items: Todo[] , error: string }; function reducer(state: State, action: Action): State { switch (action.type) { case ActionTypes.REQUEST_SUCCESS: return { ...state, items: action.payload.items, error: "" }; case ActionTypes.REQUEST_FAILURE: return { ...state, items: [], error: action.payload.reason }; } return state; } I defined action types as a string enum. SFA type stands for a standard flux action and can be overloaded together with createAction to accommodate more action shapes, but this is not the most important at the moment. The interesting part is how we built the Action type. Using ReturnType, we can obtain types of actions returned by action creators directly from the actions object. This significantly reduced the amount of typing we have to do in every reducer without compromising the type safety. Runtime types Have you ever defined a type for the JSON payload? In general, HTTP clients allow you to do that, but you have no guarantee that what you are actually going to fetch matches the interface you have specified. Here’s where runtime types come in. The io-ts library adopts this approach and blurs the boundary between what’s possible to type statically and what otherwise would require writing defensive code and custom type guards. Defining Repository (runtime type) is as effortless as defining an interface in TypeScript. It’s also possible to extract the static type from the runtime type using TypeOf. I can fetch the payload without worrying about specifying the type of the response I can’t be sure of anyway. I decode the payload to what I expect to be the Microsoft/TypeScript GitHub repository. I don’t have to define all fields, only the ones I’m interested in. Calling fold on the repo is similar to how we used the match function. In fact, the repo is of type Either which has a slightly different implementation than our Either, but the idea is the same. The left value is a list of errors that prevented payload from parsing correctly, and the right value is the repository. Takeaways I intentionally tried to avoid throwing and handling errors. In the provided examples errors handling is not an afterthought, we model software treating errors as part of the domain. It’s not easy but I found it to be a great learning experience. I would also encourage you to avoid using any in your interfaces and function signatures. It’s an escape hatch that quickly propagates across all of its consumers either forcing you to lose the benefits of static typing or assert types (explicitly using “as” syntax or guard function). I hope the provided examples give you some guideline on how you can incorporate algebraic data types into your own project. Don’t forget to try out io-ts yourself! This article has been originaly posted on LogRocket's blog: Pattern matching and type safety in TypeScript Photo by Fancycrave on Unsplash.
https://michalzalecki.com/pattern-matching-and-type-safety-in-typescript/
CC-MAIN-2020-10
refinedweb
1,266
53.92
Hi, I have this "number game" which i just learned tonight ..It runs..but ,not without this warning box poping up, which says: "uninitialized local variable 'guess' used"...This confusing me because i know i did everything exactly like i was taught ...can you find/fix my problem abd explain please it'll be a blessing ...thankyou so much.. #include <iostream> #include <ctime> using namespace std; int main() { int random; int guess; srand(static_cast<unsigned int>(time(0))); random = rand()%7+1; std::cout << "Guess my number! (1-7)\n"; while (guess != random) { std::cin >> guess; std::cin.ignore(); if (guess < random) { std::cout << "Too Low!!!\n"; } if (guess > random) { std::cout << "Too High!!!\n"; } if (guess == random) { std::cout << "You Won!!! My number was: "<< random << "\n"; std::cin.get(); } } }
https://www.daniweb.com/programming/software-development/threads/193061/uninitialized-local-variable
CC-MAIN-2017-17
refinedweb
130
79.36
Know your history — Containers aren’t just a flash in the pan Welcome to our History 101 series! This week, we explore the history of containers. How did containers replace virtual machines as the technology of choice? Open your textbooks to chapter five; class is in session! Containers are a solid mainstay of the developer toolkit. Between the rising popularity of Docker and Kubernetes, containers are impossible (and foolish) to ignore. Let’s take a look back at the past and see where it all started and how far the technology has come. Adolescence & early years When Docker set sail on the high seas in 2013, it seemed like containers was a new technology. On the contrary, proto-container tech has been around since 1979. Yup, that’s right – the idea of containers are old enough to rock some sweet Electric Light Orchestra vinyl and remember when Alien hit theaters. Of course, this early relative of containers was far different than what we know it as today. Version 7 of Unix introduced the chroot system call. Chroot introduced the idea of changing the root directory for a currently running process and its children. It is the process of virtualizing a new environment in the Unix OS and separate it from the main system. (Sound familiar?) In 1982, chroot was added to the BSD (Berkeley Software Distribution). Almost two decades later in the new millennium, FreeBSD Jails hit the scene. FreeBSD was an OS call similar in nature to chroot but built upon and improved the original concept. According to its documentation, “Jails expand upon this model by virtualizing access to the file system, the set of users, and the networking subsystem…Jails can be considered as a type of operating system-level virtualization”. A whale of a tale The Linux Foundation took a look at this important piece of pre-container history in their blog post “A Brief Look at the Roots of Linux Containers“. Interestingly enough, this blog includes a sample course video by a Docker Captain. It’s looking like the roots of the early chroot days are starting to connect to containerization as we know it today! Released in 2013 by Docker Inc., Docker brought the idea of containers into the spotlight. Today, Docker does not use chroot. It instead isolates filesystems using the Mount or mnt namespace. Containers had a powerful benefit over virtual machines: they are more lightweight and run on a single OS kernel. Containers are safe and easy to deploy, start and stop quickly, are portable and easy to scale. It’s no wonder that many developers kicked their VMs to the curb and started singing the praises of containers. According to their website, Docker has 50 billion container downloads, 2 million Dockerized applications in the Hub, and over 100,000 third-party projects use Docker. For a time, Docker was the biggest whale in the ocean, but then came a change in the tides. Did you know? The Docker whale logo was created by Ricky AsamManis in a 99designs competition. What might the logo be in an alternate universe? The runner up is actually a giraffe. Can you imagine an article on Docker without a few whale puns? I whale-y can’t. Competition & wide-spread adoption Initially released in 2014, Kubernetes is an open-source container orchestration system. Originally created by Google, it is now under control of the Cloud Native Computing Foundation. The annual GitHub Octoverse report shows that Kubernetes dominates. In 2017, Kubernetes soared as the top most-discussed repository with over 388,000 comments, and took second place in number of project reviews. Will the 2018 report have similar numbers? It’s easy enough to find claims such as, “Containers can make your life easier” and “containers bring so many benefits that outweigh the complexity of the technology“. Going by these statements, the age of containers is in full swing. According to the 2018 Container Adoption Benchmark Survey by Diamanti, “nearly half (47 percent) of IT leaders surveyed said they plan to deploy containers in a production environment, while another 12 percent say they already have”. Not only that, IT teams are devoting big budgets to containers and have plenty of use cases for them. A shaky future? With every big swing, comes a big drop. Right? What’s all this buzz about ‘containers versus serverless’? Is there actually a battle for dominance or is the relationship more complicated than that? Our new issue of JAX Magazine explores this topic and how the two technologies compete and complement each other. As for the future of containers, there is also the ever-popular discussion of “Docker versus Kubernetes” in the orchestration war. While according to the aforementioned 2018 Container Adoption Benchmark Survey, Docker is in the lead in terms of numbers, rival opinions claiming Kubernetes has won are out there. The future of containers is debatable and speculation is constant. For now, let us take our time and acknowledge how far this technology has come and what it has done to change the way we work and play! Miss a week of class? We’ve got your make-up work right here. Check out other chapters in our Know Your History series!
https://jaxenter.com/know-your-history-containers-150485.html
CC-MAIN-2020-34
refinedweb
873
56.35
« Broken allocators... | Main | More on Drivers » Long ago, I promised to write more about gcc inline assembly, in particular a few cases that are tricky to get right. Here, somewhat belatedly, are those cases. These examples are taken from libc, but the concepts apply to any inline assembly fragments you write for gcc. As I mentioned previously, these concerns apply only to gcc-style inlines; the Studio-style inline format doesn't require that you use this same level of caution. gcc expects you to write assembly fragments (even in a "separate" inline function) as if they are logically a part of the caller. That is, the compiler will allocate registers or other appropriate storage locations to each of the input and output C variables. This requires that you instruct the compiler very carefully as to your use of each variable, and the variables' relationships to one another. The advantage is much better register allocation; the compiler is free to allocate whatever registers it wishes to your input and output variables in a manner that is transparent to you. Instead, Studio requires that you code the fragment as if it were a leaf function, so the compiler does not do any register allocation for you. You are permitted to use the caller-saved registers any way you wish, and even to use the caller's stack as if you are in a leaf function. Arguments and return values are stored in their ABI-defined locations. Depending on the optimization level you use, this can be wasteful of registers (though the peephole optimizer can often clean up some of this waste) and can also make writing the fragment much more difficult. In exchange, however, you don't have to be nearly as careful to express the fragment's operation to the compiler. Each assembly fragment may have any or all of outputs, inputs, and clobbers. Each input and output maps a C variable or literal to a string suitable for use as an assembly operand. These operands can then be referenced as %0, %1, %2, etc. These are ordered beginning from 0 with the first output, followed by the inputs. Alternately, newer versions of gcc allow the use of symbolic names for each input and output. Clobbers are somewhat different; they express the set of registers and/or memory whose values are changed by the fragment but are not expressed in the outputs. Inputs which are also changed must be listed as outputs, not clobbers. Normally, the clobbers include explicit registers used by certain instructions, but may also include "cc" to indicate that the condition code registers are modified and/or "memory" to indicate that arbitrary memory addresses have had their contents altered. %0 %1 %2 "cc" "memory" Outputs and inputs are expressed as constraints, in a language specifying the type of operand that will contain the value of a variable. Common constraints include "r", indicating that a general register should be allocated, and "m" indicating that some type of memory location should be used. The complete list of constraints is found in the gcc documentation. These constraints may contain modifiers, which give gcc more information about how the operand will be used. The most common modifiers are "=", "+", and "&". The "=" modifier is used to indicate that the operand is output-only; it may appear only in the constraint for an output variable. Even if the constraint is applied to a variable containing an existing value in your program, there is no guarantee that it will contain that value when your assembly fragment is executed. If you need that, you must use the "+" modifier instead of "="; this tells the compiler that this operand is both an input and an output. Nevertheless, the variable with this constraint is provided only in the outputs section of the fragment's specification. An alternate way to express the same thing is provided in the documentation. Note that providing the same variable as both an input and an output does not guarantee you that the same location (register, address, etc.) will be used for both of them. Thus the following is generally incorrect: "r" "m" "=" "+" "&" static inline int add(int var1, int var2) { __asm__( "add %2, %0" : "=r" (var1) : "r" (var1), "r" (var2)); return (var1); } extern __inline__ uint32_t swap32(volatile uint32_t *__memory, uint32_t __value) { ... uint32_t __tmp1, __tmp2; __asm__ __volatile__( "ld [%3], %1\n\t" "1:\n\t" "mov %0, %2\n\t" "cas [%3], %1, %2\n\t" "cmp %1, %2\n\t" "bne,a,pn %%icc, 1b\n\t" " mov %2, %1" : "+r" (__value), "=r" (__tmp1), "=r" (__tmp2) : "r" (__memory) : "cc"); return (__tmp2); } But suppose gcc decided to allocate o0 to both __tmp1 and __memory. This is allowable, because the "=r" constraint implies that the corresponding register is set only after all input-only operands are no longer needed (input/output operands obviously don't have this problem). In the case above, the first load would clobber o0 and the cas would operate on an arbitrary location. Instead, we must write "=&r" for both __tmp1 and __tmp2; neither variable may safely be allocated the same register as the input operand. static __inline__ void incr32(volatile uint32_t *__memory) { uint32_t __tmp1, __tmp2; __asm__ __volatile__( "ld [%2], %0\n\t" "1:\n\t" "add %0, 1, %1\n\t" "cas [%2], %0, %1\n\t" "cmp %0, %1\n\t" "bne,a,pn %%icc, 1b\n\t" " mov %1, %0" : "=r" (__tmp1), "=r" (__tmp2) : "r" (__memory) : "cc"); } uint32_t func(uint32_t x) { uint32_t y = 4; uint32_t z = x + y; incr32(&y); z = x + y; return (z); }: c2 00 40 00 ld [%g1], %g1 <=== func+0x18: 9a 00 60 01 add %g1, 0x1, %o5 func+0x1c: db e0 50 01 cas [%g1] , %g1, %o5 <= SEGV func+0x20: 80 a0 40 0d cmp %g1, %o5 func+0x24: 32 47 ff fd bne,a,pn %icc, func+0x18 func+0x28: 82 10 00 0d mov %o5, %g1 func+0x2c: 81 c3 e0 08 retl func+0x30: 9c 23 bf 88 sub %sp, -0x78, %sp In this case, gcc has allocated g1 to both __tmp1 and __memory, and o5 to __tmp2. Note the highlighted instructions: the initial load destroys the value of g1, and the subsequent cas will attempt to operate on whatever address was stored at *__memory when the fragment began. In this example, that value will be 4 (g1 is assigned sp+0x64, which is simply the address of y). This program is compiled incorrectly due to improper constraints, and will cause a segmentation fault if the code in question is executed. g1 o5 *__memory sp+0x64 y If instead we use "=&r" for both __tmp1 and __tmp2, gcc generates the following code: <= OK This code now assigns o4 to __tmp1, which eliminates the problem described above. This function, however, still does not do the right thing. Why not? o4 Compilers keep track of where each live variable in the program can be found; many variables can be found both at some memory location and in a register. Sometimes, the compiler chooses to use a register for a different variable, and stores the value back to its memory location (if it has changed) before doing so. Later, if this value is needed, the value must be loaded back into a register before being used. This is known as reloading. Other reasons reloading may be required include a variable's declaration as volatile and the case that concerns us here, a variable's modification via side effects. volatile In the example above, incr32() is actually operating on a memory address, not a register. So why did we assign __memory the "r" constraint instead of more correctly expressing the constraint as "+m" (*__memory)? It turns out that the "m" constraint allows a variety of possible addressing modes. On SPARC, this includes the register/offset mode (such as [%sp+0x64]). This is fine for instructions like ld and st, but the cas instruction is special: it allows no offset. No constraint exists to describe this condition; the "V" constraint is clearly similar but is not correct; a bare register ([%g1]) is an offsettable address, so "V" would actually exclude the case we want. Conversely, "o", the inverse constraint of "V", includes the register/offset addressing mode we specifically wish to exclude. So, the only way to express this constraint is "r". But this does nothing to capture the fact that although the pointer itself is not modified, the value at *__memory is altered by the assembly fragment. Is this a problem? Let's look at the assembly generated for func() a little more closely: incr32() "+m" (*__memory) [%sp+0x64] ld st "V" [%g1] "o" func() We see that gcc has assigned z the o0 register, which is not surprising given that it's the return value. But after o0 is set to x + 4 at the beginning of the function, it's never set again. The line z = x + y has been discarded by the compiler! This is because it does not know that our inline assembly modified the value of y, so it did not reload the value and recalculate z. z x + 4 z = x + y There are two ways we can correct this problem: (a) add a "+m" output operand for *__memory, or (b) add "memory" to the list of clobbers. This is a special clobber that tells gcc not to trust the values in any registers it would otherwise believe to hold the current values of variables stored in memory. In short, this clobber tells gcc that all registers must be reloaded if the correct value of a variable is required. This is somewhat inefficient when we know which piece of memory has been touched, so (a) is preferable for better performance. Whichever solution we choose, gcc now compiles our code to: "+m" func() func: 9c 03 bf 88 add %sp, -0x78, %sp func+0x4: 9a 10 20 04 mov 0x4, %o5 func+0x8: 98 10 00 08 mov %o0, %o4 func+0xc: da 23 a0 64 st %o5, [%sp + 0x64] func+0x10: 82 03 a0 64 add %sp, 0x64, %g1 func+0x14: d6 00 40 00 ld [%g1], %o3 func+0x18: 9a 02 e0 01 add %o3, 0x1, %o5 func+0x1c: db e0 50 0b cas [%g1] , %o3, %o5 func+0x20: 80 a2 c0 0d cmp %o3, %o5 func+0x24: 32 47 ff fd bne,a,pn %icc, func+0x18 func+0x28: 96 10 00 0d mov %o5, %o3 func+0x2c: d0 03 a0 64 ld [%sp + 0x64], %o0 <=== func+0x30: 90 03 00 08 add %o4, %o0, %o0 <=== func+0x34: 81 c3 e0 08 retl func+0x38: 9c 23 bf 88 sub %sp, -0x78, %sp Note the reload, which will now return the correct result. There are actually two other ways to correct this, although the use of "+m" is the most correct. First, we could declare z to be volatile in func(). This would force gcc to reload its value from memory any time that value is required. Use of the volatile keyword is mainly useful when some external thread (or hardware) may change the value at any time; using it as a substitute for correct constraints will cause unnecessary reloading, degrading performance. Second, and perhaps best of all, the compiler could be modified to accept a SPARC-specific constraint for use with the cas instruction, one which requires the address of the operand to be stored in a general register. You can find more inline assembly examples in libc (math functions), MD5 acceleration, and the kernel illustrating these concepts. Be sure to read and understand the documentation completely before writing your own inline assembly for gcc, and always test your understanding by constructing and compiling simple test programs like these. Posted at 01:32AM Dec 06, 2005 by wesolows in General | Permalink Today's Page Hits: 50
http://blogs.sun.com/wesolows/entry/gcc_inline_assembly_part_2
crawl-002
refinedweb
1,970
54.76
This HOWTO describes the process of enabling acceleration for certain cryptographic algorithms on the BeagleBone Black(BBB). A week ago, I tried and failed due to all sorts of kernel modules problems, but it now appears I have everything in order. Specifically, I will detail how to configure OpenSSL to use the BBB crypto hardware. Update 3/22/14: In the 3.13 kernel, the OMAP TI crypto drivers are enabled by default (for the BBB images). Instructions: - Download and flash the Debian eMMC flasher image. - Do a apt-get updateand apt-get install build-essentialsto get a toolchain on the BBB. - Download the cryptodev-linux-1.6.tar.gz device source. This allows user-space applications access to the hardware accelerators. - Download the linux kernel headers provided by Robert Nelson. First run a uname -aon the BBB to see what version of Debian you have. I was running v3.8.13-bone26 so that’s the folder to which you should navigate. You’ll want to download the linux-headers.deb for your version. If you have v3.8.13-bone26, you file is here. - Run sudo dpkg -i linux-headers-3.8.13-bone26_1.0wheezy_armhf.deb. - There is a slight problem with one of the headers. Basically, RNelson’s deb doesn’t install all the headers because he was trying to save on precious space for the BBB. So, you need to make one tweak: (Thankfully, I stumbled on this post which gave me this idea!) sudo nano /usr/src/linux-headers-3.8.13-bone26/arch/arm/include/asm/timex.h Remove / comment out the line: #include <mach/timex.h>and replace it with: #include <usr/src/linux-headers-3.8.13-bone26/arch/arm/include/asm/timex.h> tar zxf cryptodev-linux-1.6.tar.gzand cd into that directory and do a makeand sudo make install. sudo depmod -ato register your module. sudo modprobe cryptodevto insert it. lsmodand you should see cryptodev in the list! - Edit /etc/modulesand put cryptodevon a line by itself at the end of the file (this will make sure the module inserts on boot). - Ok, we are done with the module, so go back and download OpenSSL (the starred version) and tar zxf openssl*and cd into that directory. There is a patch from TI for OpenSSL that their instructions say to install. But that patch was a year old, so I’m not sure if that’s current. I did not install it. - run ./config -DHAVE_CRYPTODEV -DUSE_CRYPTDEV_DIGESTS shared make(this takes a long time) sudo make install. One thing to note, this will install openssl in /usr/local/ssl/binwhich will not be first in your path to /usr/bin/openssl. So you should either change the default install directory or update symlinks as appropriate. - Enjoy! Future Work - Package this up into a deb for easy install? - Update my tor relay and measure the performance gain. - Work on enabling the hardware random number. UPDATE: This is now enabled with kernel version 3.13. Without cryptodev debian@arm:~/openssl-1.0.1e/cryptodev-linux-1.6$ time openssl speed -evp aes-128-cbc Doing aes-128-cbc for 3s on 16 size blocks: 2666405 aes-128-cbc's in 2.99s Doing aes-128-cbc for 3s on 64 size blocks: 905987 aes-128-cbc's in 3.00s Doing aes-128-cbc for 3s on 256 size blocks: 240811 aes-128-cbc's in 2.99s Doing aes-128-cbc for 3s on 1024 size blocks: 61145 aes-128-cbc's in 3.00s Doing aes-128-cbc for 3s on 8192 size blocks: 7677 aes-128-cbc's in 3.00s OpenSSL 1.0.1e 11 Feb 2013 built on: Mon Mar 18 21:48:12 UTC 2013 options:bn(64,32) rc4(ptr,char) des(idx,cisc,16,long) aes(partial) blowfish(ptr) compiler: gcc -fPIC -DOPENSSL<em>PIC -DZLIB -DOPENSSL</em>THREADS -D<em>REENTRANT -DDSO</em>DLFCN -DHAVE<em>DLFCN</em>H -DL<em>ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D</em>FORTIFY_SOURCE=2 -Wl,-z,relro -Wa,--noexecstack -Wall The 'numbers' are in 1000s of bytes per second processed. type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes aes-128-cbc 14268.39k 19327.72k 20617.93k 20870.83k 20963.33k real 0m15.114s user 0m15.031s sys 0m0.041s With cryptodev debian@arm:/usr/local/ssl/bin$ time /usr/local/ssl/bin/openssl speed -evp aes-128-cbc Doing aes-128-cbc for 3s on 16 size blocks: 28166 aes-128-cbc's in 0.04s Doing aes-128-cbc for 3s on 64 size blocks: 22445 aes-128-cbc's in 0.03s Doing aes-128-cbc for 3s on 256 size blocks: 29933 aes-128-cbc's in 0.05s Doing aes-128-cbc for 3s on 1024 size blocks: 16018 aes-128-cbc's in 0.04s Doing aes-128-cbc for 3s on 8192 size blocks: 4861 aes-128-cbc's in 0.02s OpenSSL 1.0.1e 11 Feb 2013 built on: Fri Oct 4 01:48:18 UTC 2013 options:bn(64,32) rc4(ptr,char) des(idx,cisc,16,long) aes(partial) idea(int) blowfish(ptr) compiler: gcc -DOPENSSL<em>THREADS -D</em>REENTRANT -DDSO<em>DLFCN -DHAVE</em>DLFCN<em>H -DHAVE</em>CRYPTODEV -DUSE<em>CRYPTDEV</em>DIGESTS -march=armv7-a -Wa,--noexecstack -DTERMIO -O3 -Wall -DOPENSSL<em>BN</em>ASM<em>MONT -DOPENSSL</em>BN<em>ASM</em>GF2m -DSHA1<em>ASM -DSHA256</em>ASM -DSHA512<em>ASM -DAES</em>ASM -DGHASH_ASM The 'numbers' are in 1000s of bytes per second processed. type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes aes-128-cbc 11266.40k 47882.67k 153256.96k 410060.80k 1991065.60k real 0m15.326s user 0m0.225s sys 0m5.990s 44 thoughts on “How to Enable Crypto Acceleration on the BeagleBone Black” Great article, thanks. I’m going to use my BBB for OpenVPN, so I’m seriously thinking about doing this, but I’m confused about something: Without cryptodev: “Doing aes-128-cbc for 3s on 16 size blocks: 2666405 aes-128-cbc’s in 2.99s” With cryptodev: “Doing aes-128-cbc for 3s on 16 size blocks: 28166 aes-128-cbc’s in 0.04s” Does that mean that only about about 1/10 as many units were completed in that 3 seconds with cryptodev? I.e. 28166 vs. 2666405? Also: “Ok, we are done with the module, so go back and tar zxf openssl* and cd into that directory.”. I didn’t see a step where we downloaded openssl tarballs. Could you please elaborate? Thanks! 1.) That is a great question. I will have to do some research and get back to you on this b/c I’m not sure. I interpret these results as it’s using less CPU with cryptodev, but now I’m not sure how to read the speed. Thanks for looking at this closely. 2.) Ah, thanks. I need to fix that. This is where I downloaded OpenSSL from : . Pick “the latest” (in red) and then follow the directions above to configure and make. Be sure to capture CPU performance before and after you upgrade with OpenVPN. I’m very interested in how much it helps you! Will do, Josh, thanks. Ok, I think I figured it out. This post helped. The hardware appears to be optimized for larger block sizes. On 8192 blocks, cryptodev screams: 1991065kB/s vs. 20963kB/s. Look at the 8192 line: without cryptodev did only 7677 blocks in 3 seconds while cryptodev did: 4861 in .02 seconds. So, cryptodev finished in th of the time ( ). Extrapolating, cryptodev could perform 729150 rounds of 8192 blocks (94 times faster!). My guess is that the overhead of DMAing or whatever over to the crypto hardware is inefficient for small block sizes. For most SSL-like applications, I think the data will be using the large block sizes and be more efficient. Do you agree? The .02 seconds presumably represents the CPU time, which with cryptodev enabled, should indeed be almost nothing. I’m more interested in real, elapsed time. The “aes-128-cbc 11266.40k 47882.67k 153256.96k 410060.80k 1991065.60k” result looks really encouraging, as you say, for the larger block sizes. I’m most interested in using this for OpenVPN and HTTPS, both of which would use larger block sized, I would guess. I’ve followed your instructions and installed this on my BBB, ran the two benchmarks, and got results very similar to yours. I’m also running some other tests – doing AES128, AES256, SHA1, and SHA256 on a 5 GB file. That will take awhile to run, and will not be quite so accurate because of SD card access overhead, but it should be interesting. I’ll probably post the results on my Tiny Computers blog. Here’s an update: With my 5.2 GB file, if I do an aes-128 encryption on it with the old, non-accellerated openssl, it finishes in about 16 minutes. If I attempt that with the new one, it crashes my BBB hard, to where I can’t even ping it. My guess is that it tries to send the entire dataset to the cryptodev device, and that won’t scale. I could be wrong on that, but now I’m scared that this may pose a reliability problem, so I think I won’t be cutting over to the accellerated openssl any time soon. Fun Sunday afternoon project, though. Interesting. Were you using the command line? What was the command? On Sun, Oct 6, 2013 at 3:49 PM, fortune datko time /usr/local/ssl/bin/openssl aes-128-cbc -pass pass:testpassword -salt -in 5GBfile.tar -out /dev/null Hey! Thanks for the great article. I’m running ArchLinux on my BBB and made PKGBUILDs (sort of compile and install scripts) for both cryptodev-linux and openssl with cryptodev enabled with the help of your instructions. Both compile and install just fine and i can load the module but it seems that it’s just not working. I did an openssl speed test before and after for md5, sha and aes but sadly they don’t differ at all. lsmod shows cryptodev and it’s Used by is increased by 1 when openssl is at work. My kernel is compiled with the right options set: CONFIG_CRYPTO_DEV_OMAP_AES=y and CONFIG_CRYPTO_DEV_OMAP_SHAM=y and the kernel headers are those of the installed kernel.. I’d really apreciate it if you could point me to the right direction. Really want to see this work. Thanks! Cool! Ok, some things to check: – Are you using the version of OpenSSL that you compiled for hardware acceleration? Mine installed in a different location and when I first tried it (using the default openssl), it did not work. I actually did a apt-get remove openssl just to be sure I was using the right one. – Are you using 1.0.1e? – If you do “openssl engine” do you see “cryptodev”? If not, openssl does not recognized the module and it won’t use the HW acceleration. – When configuring openssl, I forgot to add “shared” to the configure line. Sorry. I will fix that now. Otherwise applications that want to use OpenSSL will have to be configured for static linkage. This doesn’t enable the crypto. All you did was took the processing from user time to kernel time. It does add the cryptodev module which takes the processing to the kernel but it does not activate the crypto device in the hardware. I finally (today) got the hwrng running (had to patch about 4 files in the dts and omap directories of the kernel and rebuild it). Beaglebone still has no real crypto hardware support, though. It’s all there, just not enabled yet with any openly available linux drivers. TI has some drivers in an eval kit but I believe the distribution of those are controlled. I will also agree, and after my long response I realize this may have been your main point, that my title is misleading. :) Thanks for the comment. I’ve started to get the sense that TI is more closed lipped about their crypto. I’ve seen questions on the TI boards about needing to talk to a Field Engineer for certain docs. Although, I did just find their Crypto Software Download Page the other day. It looks like they have some kernel drivers. I’m curious about your patches for the HWRNG, do you mind posting them somewhere ;) ? The TI Crypto Guide mentions that one should enable the HWRNG character device in the Kernel config, but I have not seen that option in the 3.8.18 series that Robert Nelson is using. Also, I do believe it’s using the crypto hardware. We seem to agree that cryptodev pushes the operations to the kernel, but at least for now, I am holding to my belief that it’s using the hardware (you seem to be more kernel aware than I, so I will let you refute my points). My belief is based on the following observations: Hardware support for the OMAP4 AES and SHA/MD5 engines are enabled in the 3.8.13 kernel: --- Cryptographic API [*] Hardware crypto devices ---> --- Hardware crypto devices <*> Support for OMAP4 AES hw engine <*> Support for OMAP4 SHA/MD5 hw engine The time recorded in the tests above for AES-128-CBC on 8192 bytes is 1991065.60kB/S. This is in the ballpark of what TI recorded for their tests, which was 1321096.53kB/s. Computation time decreased with cryptodev. While I agree this could be due to an efficient kernel implementation, the time decrease is drastic and also matches TI’s metrics. Without cryptodev took 15.031s user + 0.041 system, but with: 0.225s user, 5.990s kernel. Real time is about the same for both, I think this is due to how OpenSSL is using timers. I believe TI’s Omap driver is included and available to the kernel. I have not studied cryptodev’s source, so this is where I’m making the leap of faith, I believe that cryptodev is using said driver. So, I agree that there is possibility that this is just shifting execution from user-space to kernel-space. If so, my guess is that it’s because cryptodev is not calling the Omap AES driver. However, based upon the observations above and mainly because my test results are matching what TI has published, I believe that it is. Have you looked at cryptodev to see how it uses kernel crypto drivers? To make your packages ‘easy’ I would reccomend using ‘checkinstall’ which will automagically create the .deb files for both openssl and the cryptodev module. Might be even better if we have a place to put the ‘deb’ files! That is a great recommendation! I will run that on cryptodev and openssl and spin up a ppa on a VPS. Thanks for the suggestion! Did you ever get hwrand working? Would be cool for doing lots of keystuff (like a cert generator appliance?). BTW: if one is using ‘browser’ ssl is the default block size 8k? If I set cipher to only be aes128-cbc? I did not. I sent message to TI, so hopefully they point me in the right direction. I think the block sizes are a bit confusing. AES always uses a block size of 128 bits, so I think the “block sizes” in the OpenSSL test represent how much data is being sent to the test at a time. I did find this: looks like the patch mentioned. No idea how to implement, but you might be able to figure out. Found a way to actually edit the original ‘openssl’ sources that come with debian. Basically Assuming you are running in /tmp apt-get build-dep openssl apt-get source openssl cd to the directory openssl opens go to the ‘debian’ directory edit the ‘rules’ file and edit the confargs line to look like the following —————— CONFARGS = –prefix=/usr –openssldir=/usr/lib/ssl –libdir=lib/$(DEB_HOST_MULTIARCH) no-idea no-mdc2 no-rc5 zlib enable-tlsext no-ssl2 -DHAVE_CRYPTODEV -DUSE_CRYPTDEV_DIGESTS ————————————- Finally, run the following to build: (you will need to install the debian build tools to do this) debuild -us -uc -b This way you have the ‘original’ sources as included and intended for the ‘debian’ distro. Provides you with ‘full’ crypto, and you stay ‘on the rails’ as it were. I will send you the modified ‘approved’ .deb, but if you want to do yourself, here it is. Nice. And thanks for the other links as well. My guess is that the HWRNG just hasn’t be ported to the 3.8 kernel yet… I’m working on a patch for OpenSSL’s cryptodev which will let it use more of the AM335x AES modes at the moment. I am using sslbump, so the crypto is important to me. I can also send you ‘ssl bump’ enabled squid if you want…..what a pain in the A$$. Squid 3.3.9…..compiled against your (and my!) crypto accelerated openssl….!! How’s sslbump working for you? I noticed some issues with Tor and I’m not sure if it was the OpenSSL, cryptodev, or Tor. That and I have to work on a few other projects at the moment. SSLbump is working flawlessly. Youtube bumps realize 30% processor with 720p and no stuttering. Was wondering if anyone had gotten back to you about hwrand and kernel 3.8? No, but I’m getting breakout boards fabbed that will have a SHA chip on them as well as a HWRNG. I’ll write an user space app to access the device over I2C. It won’t be as fast as the TI one, but it would be a good seed… I can beta test cape for you if you want. Cool! I have my test batch of cape-lets on their way. If they go well, I’ll order a limited-run batch and make them available. Probably around mid-december. It’ll just be the SHA capelet at first, but the other features should follow pretty steadily after that one. Thanks for the reblog. On Mon, Nov 18, 2013 at 9:53 PM, fortune datko Reblogged this on Musings of a Technical Geek and commented: Cool! Hello, currently I am using RaspberryPI as OpenVPN server and with AES-128-CBC I am hitting CPU limit at ~15mbps (overclocked @900mhz) Did anybody try what throughput would BeagleBone with HW crypto module enabled and used by openSSL produce? I have 70/70mbps link and I use VPN quite often but I rarely need much speed, although when I do, I need a lot (file transfers) I could not find any results on the Internet would anybody be willing to test it, please? Thank you very much in advance I did do connection tps measurements, and using 128bit aes sha1, we got 450 tps, without was 200tps. I suspect that the acutal thoruput won’t vary that much, since once symmetric cipher done, not too much work. Hey Martin, I haven’t done the an good open OpenSSL test yet. I recompiled wget with my cryptodev-openssl, but I didn’t see any noticeable difference. I’ll have to setup a local test server to eliminate the latency across the Internet and give it a shot. Maybe this weekend? If I run the tests, I’ll add a blog post. have you had time to test the OpenVPN performance yet? I am very interested to see the result and I would be very grateful if you could post the results soon :) Thanks in advance Martin, See my latest post. Hopefully that does the trick. The bandwidth numbers are a bit low, but I think that is because my client (BBB) is in the U.S. and the server was in Europe. From a CPU point of view, it seems to do pretty well. Thank you very much in advance, I really look forward to the results and I hope you’ll find the time to test it and post post the results soon. Best regards, Martin Reblogged this on Cryptotronix, LLC and commented: The BeagleBone Black’s TI AM335x processor has cryptographic modules built-in. My tutorial shows how configure OpenSSL to use the onboard AES accelerator. Any updates on the cryptocape / HWRNG? I did see some new kernel images out, but I have yet to get them working (I did have a non-bootable 3.10.xx tried the kernel faq). Oh well. I also could skype you got some wonderful package help on making openssl much more friendly. Apparently, the 3.13 series has some of the patches: I haven’t tried it yet. The CryptoCape is coming along (My daughter was born early… put a dent in my development schedule :p) see: That would be great! I’m also hanging out on freenode (jbdatko) if you want to chat there.
http://datko.net/2013/10/03/howto_crypto_beaglebone_black/
CC-MAIN-2015-48
refinedweb
3,538
74.79
Overview¶ In this lecture we will - Outline what Python is - Showcase some of its abilities - Compare it to some other languages At this stage, it’s not our intention that you try to replicate all you see. We will work through what follows at a slow pace later in the lecture series. Our only objective for this lecture is to give you some feel of what Python is, and what it can do. popular programming languages. Common Uses¶ Python is a general-purpose language used in almost all application domains - communications - web development - CGI and graphical user interfaces - games - multimedia, data processing, security, etc., etc., etc. Used extensively by Internet service and high tech companies such as - Dropbox - YouTube - Walt Disney Animation, etc., etc. Often used to teach computer science and programming. For reasons we will discuss, Python is particularly popular within the scientific community - academia, NASA, CERN, Wall St., etc., etc. Relative Popularity¶ The following chart, produced using Stack Overflow Trends, shows one measure of the relative popularity of Python The figure indicates not only that Python is widely used but also that adoption of Python has accelerated significantly since 2012. We suspect seek. Other features - A multiparadigm language, in that multiple programming styles are supported (procedural, object-oriented, functional, etc.). -, list comprehensions, etc. - Machine learning and data science - Astronomy - Artificial intelligence - Chemistry - Computational biology - Meteorology - etc., etc. Its popularity in economics is also beginning to rise. This section briefly showcases some examples of Python for scientific programming. - All of these topics will be covered in detail later on. 2.706168622523819e-16 The number you see here might vary slightly but it’s essentially zero. (For older versions of Python and NumPy you need to use the np.dot function). - Plots, histograms, contour images, 3D, bar charts, etc., etc. - Output in many formats (PDF, PNG, EPS, etc.) - LaTeX integration Example 2D plot with embedded LaTeX annotations Example contour plot Example 3D plot More examples can be found in the Matplotlib thumbnail gallery. Other graphics libraries include. Can easily create tables of derivatives, generate LaTeX output, add it to figures, etc., etc. Other Useful Statistics Libraries¶ - statsmodels — various statistical routines - scikit-learn — machine learning in Python (sponsored by Google, among others) Networks and Graphs¶ Python has many libraries for studying graphs. One well-known example is NetworkX - Standard graph algorithms for analyzing network structure, etc. - Plotting routines - etc., etc. Here’s some example code that generates and plots a random graph, with node color determined by shortest path length from a central node. import networkx as nx import matplotlib.pyplot as plt %matplotlib inline np.random.seed(1234) # Generate a random graph p = dict((i, (np.random.uniform(0, 1), np.random.uniform(0, 1))) for i in range(200)) g = nx.random_geometric_graph(200, 0.12, pos=p) pos = nx.get_node_attributes(g, 'pos') # Find node nearest the center point (0.5, 0.5) dists = [(x - 0.5)**2 + (y - 0.5)**2 for x, y in list(pos.values())] ncenter = np.argmin(dists) # Plot graph, coloring by path length from central node p = nx.single_source_shortest_path_length(g, ncenter) plt.figure() nx.draw_networkx_edges(g, pos, alpha=0.4) nx.draw_networkx_nodes(g, pos, nodelist=list(p.keys()), node_size=120, alpha=0.5, node_color=list(p.values()), cmap=plt.cm.jet_r) plt.show() /home/ubuntu/anaconda3/lib/python3.7/site-packages/networkx/drawing/nx_pylab.py:579: MatplotlibDeprecationWarning: The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead. if not cb.iterable(width): Cloud Computing¶ Running your Python code on massive servers in the cloud is becoming easier and easier. A nice example is Anaconda Enterprise. See also - The Google App Engine (Python, Java, PHP or Go) Parallel Processing¶ Apart from the cloud computing options listed above, you might like to consider - The Starcluster interface to Amazon’s EC2. Other Developments¶ There are many other interesting developments with scientific programming in Python. Some representative examples include Learn More¶ - Browse some Python projects on GitHub. - Have a look at some of the Jupyter notebooks people have shared on various scientific topics. - Visit the Python Package Index. - View some of the questions people are asking about Python on Stackoverflow. - Keep up to date on what’s happening in the Python community with the Python subreddit.
https://python.quantecon.org/about_py.html
CC-MAIN-2019-43
refinedweb
718
51.24
Every: select left(name,25) name, type, type_desc from sys.server_principals AS logWHERE (log.type in ('U', 'G', 'S', 'R')) order by 3,1/*Results from previous queryname type type_desc------------------------- ---- ------------bulkadmin R SERVER_ROLEdbcreator R SERVER_ROLEdiskadmin R SERVER_ROLEprocessadmin R SERVER_ROLEpublic R SERVER_ROLEsecurityadmin R SERVER_ROLEserveradmin R SERVER_ROLEsetupadmin R SERVER_ROLEsysadmin R SERVER_ROLEsa S SQL_LOGINDBSVRXP\LocalUser1 U WINDOWS_LOGINHOME\Administrator U WINDOWS_LOGINNT AUTHORITY\SYSTEM U WINDOWS_LOGIN*/_LOGINtype_desc of WINDOWS_GROUP or WINDOWS_LOGIN are Windows groups or individual Windows users granted logins to SQL Server. The other entries with type_desc of SERVER_ROLE are fixed server roles discussed later in this chapter. represents a login created with SQL Server authentication. Logins with a. Note. Tip 'Report' 'Auto_Fix', 'Chris', NULL, 'p: SELECTleft(u.name,25) AS [Name],type,left(type_desc,15) as type_descFROMsys.database_principals AS uWHERE(u.type in ('U', 'S', 'G'))ORDER BY 1/*Results from previous queryName type type_desc------------------------- ---- ---------------dbo S SQL_USERDBSVRXP\LocalUser1 U WINDOWS_USERguest S SQL_USERINFORMATION_SCHEMA S SQL_USERsys S SQL_USER*/ The SELECT statement in this example returns five rows (that is, five users). This SELECT was run against the AdventureWorks2008 database, and the only user explicitly added to the database was the Windows user DBSVRXP\LocalUser1. The other users are special users who are added by default to each database. These users do not have corresponding server logins named the same. These users are discussed in the following sections. The dbo user is the database owner and cannot be deleted from the database. Members of the sysadmin server role are mapped to the dbo user in each database, which allows them to administer all databases. Objects owned by dbo that are part of the dbo schema can be referenced by the object name alone. When an object is referenced without a schema name, SQL Server first looks for the object in the default schema for the user that is connected. If the object is not in the user’s default schema, the object is retrieved from the dbo schema. Users can have a default schema that is set to dbo. Schemas and their relationship to users are discussed in more detail in the section “User/Schema Separation,” later in this chapter. The guest user is created by default in each database when the database is created. This account allows users that do not have a user account in the database to access the database. By default, the guest user does not have permission to connect to the database. To allow logins without a specific user account to connect to the database, you need to grant CONNECT permission to the guest account. You can run the following command in the target database to grant the CONNECT permission: GRANT CONNECT TO GUEST When the guest account is granted CONNECT permission, any login can use the database. This opens a possible security hole. The default permissions for the guestguest account, and all logins that use it will be granted those permissions. Generally, you should create new database users and grant permissions to these users instead of using the guest account. account are limited by design. You can change the permissions for the If you want to lock down the guest account, you can. You cannot drop the guest user, but you can disable it by revoking its CONNECT permission. The following example demonstrates how to revoke the CONNECT permission for the guest user: REVOKE CONNECT FROM guest If you decide to grant additional access to the guest account, you should do so with caution. The guest account can be used as a means for attacking your database. The INFORMATION_SCHEMA user owns all the information schema views installed in each database. These views provide an internal view of the SQL Server metadata that is independent of the underlying system tables. Some examples of these views include INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.CHECK_CONSTRAINTS. The INFORMATION_SCHEMA user cannot be dropped from the database. The sys account gives users access to system objects such as system tables, system views, extended stored procedures, and other objects that are part of the system catalog. The sys user owns these objects. Like the INFORMATION_SCHEMA user, it cannot be dropped from the database. If you are interested in viewing the specific objects owned by any of the special users discussed in these sections, you can use a SELECT statement like the following: --Find all objects owned by a given userSELECT name, object_id, schema_id, type_descFROM sys.all_objectsWHERE OBJECTPROPERTYEX(object_id, N'OwnerId') = USER_ID(N'sys')ORDER BY 1 The SELECT in this example shows all the objects owned by the sys user. To change the user, you simply change the parameter of the USER_ID function in the SELECT statement from 'sys' to whatever user you want. The changes to schema security introduced in SQL Server 2005 have been carried forward to SQL Server 2008. Versions of SQL Server before SQL Server 2005 had schemas, but they did not conform to the American National Standards Institute (ANSI) definition of schemas. ANSI defines a schema as a collection of database objects that one user owns and that forms a single namespace. A single namespace is one in which each object name is unique and there are no duplicates. So, for example, if you have two tables named customer, they cannot exist in the same namespace. To fully understand the user/schema changes in SQL Server 2008, you need to understand how schemas were used in prior versions of SQL Server. In SQL Server 7.0 and 2000, a default schema was created for each user, and it had the same name as the user. For example, if you created a new user named Rachael, a corresponding schema named Rachael would be created as well. There was no option in those releases to change the default schema for a user, and each user was forever bound to a schema with the same name. When the user created new objects, the objects were created by default in that user’s schema, which is always the name of the user. So, if Rachael created an object named customer, it was placed in the Rachael schema, and the object was owned by Rachael. When Rachaeldatabase.owner.object. If a linked server was used, according to the SQL Server 2000 documentation, the object in the linked server could be referenced with the four-part name linked_server.catalog.schema.object. (for example myserver.AdventureWorks2008.Rachael.Customer). You can see that the schema name is used prior to the object name when the object is outside the local server. The bottom line is that the schema and owner were basically the same thing in SQL Server 7.0 and 2000. wanted to reference the object, she could use a three-part name with the format With SQL Server 2005 and SQL Server 2008, the owner and schema have been separated. This is made possible in part by allowing a database user to have a default schema different from the name of the user. For example, our sample user Rachael could be assigned the default schema Sales. When Rachael creates objects in the database, her objects are created, by default, in the Sales schema. If Rachael wants to reference an object that she created, she can reference the table in a number of different ways. She can use the full four-part name (server.database.schema.object) that includes the Sales schema name to reference the object via a linked server. She can simply refer to the object with the object name alone, and the Sales schema will be searched first for the object. She can also use a three-part name or a two part name. If the object name is not found in the Sales schema, the dbo schema will be searched. This concept is illustrated in the following sample SELECT statements that all retrieve the same rows from the Region table that was created by Rachael in the Adventureworks2008 database. select * from regionselect * from sales.regionselect * from AdventureWorks2008.Sales.Region The important point to remember is that owners and schemas are different from one another in SQL Server 2008. For example, you can have a customer table created in the Sales schema, and that table can be owned by a user named Chris. The object should be referenced with the schema name qualifier, such as Sales.Customer, not Chris.Customer. This has the distinct advantage of allowing object ownership to change without affecting the code that references the object. The reason is that database code that references an object uses the schema name instead of the object owner. The schema enhancements in SQL Server 2008 go well beyond the user/schema separation. Schemas are an integral part of all the database objects that exist in SQL Server. As we delve into more details about SQL Server security and the assignment of permissions, you will see that schemas play a very important part.
http://mscerts.programming4.us/sql_server/sql%20server%202008%20%20security%20and%20user%20administration%20-%20managing%20principals%20(part%201)%20-%20users.aspx
CC-MAIN-2014-42
refinedweb
1,475
62.78
Accelerometer Dice With 123D Circuits Introduction:. Here's how it works - pick up the die, shake it, watch while the numbers change until it stops on a number between 1 and 6. It's that simple... It's just like a real die except it's huge and has circuitry and a 3D printed enclosure. So I'll admit - it's a little more involved than a tiny plastic die, but it's way cooler. But don't take my word for it - You can make one too, the files are online. Keep reading for the links. Step 1: The Online Simulation If you need help we have this getting started instructable. Once you're in the viewer you can scroll around and zoom in and out. If you want to start the simulation or make changes you first need to make this circuit your own. Click this link to open the Accelerometer Dice circuit in the 123D Citcuits editor. Once you're in press "Fork" to make a copy for you to have fun with. Don't worry about screwing it up when you add your own stuff, our original will remain unchanged. Step 2: More Power, Scotty! The breadboard view from the previous step is a nice simulation of the die and you can learn a lot from it - but to build this circuit using the larger 7-segment display we're going to need a slightly different design to accommodate its need for a lot more power, Scotty. The next steps dig deeper into that design... The really large 7-segment display draws a lot more current than an Arduino can provide per pin and drops upwards of 12.4 volts so the whole circuit needs a more capable power supply and uses discrete transistors to stop and start the flow of current through the segments. The Arduino is still there, it's just acting more like the brain than the brawn. We're using two 9 volt batteries in series, the 18 volts gives us some headroom and ensures that as the batteries drain over time the die will shine bright for a a while. For those interested - here's a link to the large 7-segment datasheet. Step 3: Parts List Here is what' on the inside and what you'll need. There are three pictures on this step. Bill Of Materials (BOM) 1 Arduino UNO (could be any Arduino that takes a standard shield) 1 circuit board designed in 123D Circuits () 1 triple axis accelerometer breakout - MMA7361 from Sparkfun 1 extra huge 6.5" tall 7-segment display from Sparkfun 1 on/off switch (spst) 1 barrel connector for DC power - size "M" batteries in series (you'll want at least 14 volts, here we're using 18 volts) battery holders wire Parts list for the Arduino shield designed in 123D Circuits are here. Press "Fork" and all of a sudden the circuit is yours. I'll cover this in more detail on the next step. Tools solder or soldering paste soldering iron multi meter wire strippers tweezers computer with usb cable to program the Arduino Optional box or enclosure, we 3D printed one double-sided sticky foam tape - to hold things together screws, glue, or epoxy - to hold things inside the inclosure Step 4: The Arduino Code 1) The Arduino code for the breadboard version is in the 123D Circuits project, just single-click on the Arduino then click on "Arduino Code Editor" 2) The Arduino code for the larger more powerful version is on this page - scroll down. Here's a link to the accelerometer's library. #include <AcceleroMMA7361.h> //should be in Documents/Arduino/Libraries (on a Mac) //download it here //mapping of the Arduino board to the large 7-segment from Sparkfun, letter is segment, number is Aruino Digital Output // // a // f b // g // e c // d int a = 0; int b = 6; int c = 5; int d = 4; int e = 3; int f = 1; int g = 2; //mapping of the accelerometer board from sparkfun, these are Arduino outputs // int st = 8; //self test (output from Arduino) int gsel = 9; //g-force range, +-1.5g and +-6g (output from Arduino) int zg = 10; //zero g (input to Arduino) int slp = 11; //sleep (output from Arduino) AcceleroMMA7361 accelero; //create the accelero object // the setup routine runs once when you press reset button on Arduino or power up: void setup() { // initialize the digital pin as an output. pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); pinMode(d, OUTPUT); pinMode(e, OUTPUT); pinMode(f, OUTPUT); pinMode(g, OUTPUT); writeDigit(-1); // turn off all segments // Serial.begin(9600); //uncomment this line for debugging, it will otherwise mess with the numbers! accelero.begin(slp, st, zg, gsel, A0, A1, A2); //config the accelero to use the pins from above and to read analog values from A0, A1, A2 accelero.setARefVoltage(5); //telling accelero that the AREF voltage is 5V (to get higher resolution you'd set this to 3.3 and blue-wire it on the board) accelero.setSensitivity(LOW); //sets the sensitivity to +-1.5G accelero.calibrate(); //you need to do this for brake light, probably not for dice. } void writeDigit(int digit) { //calling this function sets the segments to look like an intiger 0-9, we never show 0, or 9. -1 is all off. Serial.print("digit: "); Serial.print(digit); Serial.print("\n"); switch(digit) { case 0: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, HIGH); digitalWrite(g, LOW); break; case 1: digitalWrite(a, LOW); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); break; case 2: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, LOW); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, LOW); digitalWrite(g, HIGH); break; case 3: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, HIGH); break; case 4: digitalWrite(a, LOW); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, HIGH); digitalWrite(g, HIGH); break; case 5: digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, LOW); digitalWrite(f, HIGH); digitalWrite(g, HIGH); break; case 6: digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, HIGH); digitalWrite(g, HIGH); break; case 7: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); break; case 8: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, HIGH); digitalWrite(g, HIGH); break; case 9: digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, LOW); digitalWrite(f, HIGH); digitalWrite(g, HIGH); break; case -1: digitalWrite(a, LOW); digitalWrite(b, LOW); digitalWrite(c, LOW); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); break; } } int get_g() { //gets the length of the g force vectors int x = accelero.getXAccel(); int y = accelero.getYAccel(); int z = accelero.getZAccel(); int gf = abs(sqrt(x*x+y*y+z*z)-100); // the "-100" is roughly subtracting out gravity if (gf > 50) { Serial.print("g: "); Serial.print(gf); Serial.print("\n"); } return gf; } int digit = 0; int count = 0; // counter int count2 = 0; // another counter int state = 0; // 0 = idle // 1 = shaking // 2 = show_result int sum = 0; int cur = 0; int res; // the loop routine runs over and over again forever: void loop() { cur = get_g(); sum += cur; if (sum < 0) sum = 0; switch(state) { case 0: // idle state, if cur is >70 then go to state 1 if (cur > 70) { state = 1; count = 0; count2 = 0; } break; case 1: // actively shaking, if (count2 == 10) { // 10 is 100ms writeDigit(sum % 6 + 1); // show a random number every 100ms. Sum is a random number depending on how long the code is running and how you shake the die. count2=0; } else { count2++; } if (cur > 55) { // from here until the break it is checking how long it has been since shaking stopped, if over 250ms without seeing g>55 go to state 2 state = 1; count = 0; } else { if (count > 25) { state = 2; count = 0; } else { count ++; } } break; case 2: // showing the result, the delay times are in ~ centi-seconds if (count == 0) writeDigit(sum % 6 + 1); if (count == 10) writeDigit(sum % 6 + 1); if (count == 25) writeDigit(sum % 6 + 1); if (count == 45) writeDigit(sum % 6 + 1); if (count == 70) writeDigit(sum % 6 + 1); if (count == 100) writeDigit(sum % 6 + 1); if (count == 135) { // from here to close of {} it is showing the final result, slowing down as it goes res = sum % 6 + 1; writeDigit(res); } if (count == 185) writeDigit(-1); if (count == 235) writeDigit(res); if (count == 285) writeDigit(-1); if (count == 335) { writeDigit(res); state = 0; count = 0; } count++; break; } delay(10); //uncomment out this small loop to test that all segments are working. (comment out the other "void loop" lines) //void loop() { // writeDigit(8); // delay(10); } Step 5: The Arduino Shield Here's the list of parts for the Arduino shield itself. Quantity Description 1 MMA7361 three axis accelerometer breakout board from Sparkfun 24 1k ohm resistors, 0805 package 8 NPN transistors, SOT23 package 1 1x9 0.1" header Step 6: Schematic / Layout The schematic and layouts are best viewed inside the 123D Circuits editor - but I've included them here for reference. More instructables on how to use 123D Circuits. Step 7: Wiring the 7-segment to the Arduino Shield The easiest way to explain the wiring is the picture. Notice how The wires are all in a row from top to bottom EXCEPT the wire that connects the 7-segment display directly to Battery Voltage - this wire is in the center on the 7-segment and on the end closest to the accelerometer on the 123D Circuits designed board. Note: this photo is taken with the whole project rotated 180 degrees from the 123D Circuits orientation. Step 8: The 3D Printed Enclosure This could be done any number of ways... and until we release a way to design the enclosure from within 123D Circuits I'll keep this brief: We used Inventor. I will revisit this in the future! The large 7-segment display has loose tolerances... each one is different. To get it to fit the box snugly we put it on a scanner (face down) and traced the resulting scan in Illustrator - creating vectors that lined up with the segments and the perimeter. I added about 2mm of space just incase. We then laser cut the vector file to see if it fit the 7-segment component well. It did. Using the vector file we imported it into Inventor and built a box around it. You could also use Tinkercad, it will allow you to import vectors, extrude them (here's a video explaining that process), and build a box around everything. Everyone has their favorite tools, use what works for you. I suggest Tinkercad. Once the 3D Model was ready we printed it on an Objet Connex 500 with multimaterials, clear and white. 12 hours later it was ready for cleaning and sanding. Once the box was ready I popped in the electronics, they're all stuck to the 7-segment component which I knew would fit based on the laser cut test. A few globs of epoxy later and the electronics were held firmly in place. Nice k can Nice project! Hint: you can find the MMA7361 and other sensors for cheap on this website:... They ship from Canada.
http://www.instructables.com/id/Accelerometer-Dice-with-123D-Circuits/
CC-MAIN-2017-43
refinedweb
1,945
55.58
Hi, I've looked every where for several GUI for Python, but couldn't seem to start any of them (for Windows XP). SPE seemed to be promising though.(looking at the screenshots) I've installed: 1) Python 2.32 2) wxPythonWIN32-2.5.1.5-Py23.exe 3) SPE-0[1].4.2.a-wx2.4.2.4.-bl2.28c.exe 4) boa-constructor-0.2.3.win32.exe For items 3 and 4 (which suppose to be GUI's) I found that the instructions doesnt even tell me to start the GUI.(?) Basically; I don't see an EXE file that starts an interface. If I browse to the directories I see only py files, an clicking on them start a dos prompt, and shuts it down again. When I try to start SPE in a dos prompt I get: //------------------------------------------------- C:\Python23\Lib\site-packages\spe>spe_.py Starting Spe v0.4.2.a ... If spe fails to start: - type "python SPE_.py --debug" at the command prompt - send the error report to s_t_a_n_i@yahoo.com Importing modules... Traceback (most recent call last): File "C:\Python23\Lib\site-packages\spe\SPE_.py", line 20, in ? import framework.wxMDIParentFrame1 as wxMDIParentFrame1 File "C:\PYTHON23\Lib\site-packages\spe\framework\wxMDIParentFrame1.py", line 21, in ? import parentInit File "C:\PYTHON23\Lib\site-packages\spe\framework\parentInit.py", line 22, in ? import dropTarget,help File "C:\PYTHON23\Lib\site-packages\spe\framework\dropTarget.py", line 11, in ? from wxPython.wx import wx ImportError: cannot import name wx //------------------------------------------------- Help appreciated greetings Patrick PS some background: I am experienced in PHP. Javascript/actionscript and a bit of VB.
http://forums.devshed.com/python-programming-11/getting-python-ide-running-newbie-136903.html
CC-MAIN-2015-11
refinedweb
275
71.61
>>)" Use More Manageable Types (Score:4, Informative) Clearly, if your code has new operations, delete operations, and pointer arithmetic all over the place, you are going to mess up somewhere and get leaks, stray pointers, etc. This is true independently of how conscientious you are with your allocations: eventually the complexity of the code will overcome the time and effort you can afford. It follows that successful techniques rely on hiding allocation and deallocation inside more manageable types. He goes on to give detailed examples and recommendations on how to avoid using garbage collection. C++ very expressive indeed (Score:2, Troll) So please tell me what typedef vector::const_iterator Iter; (or rather vector::const_iterator) is supposed to mean. I suppose vector is a templated class, but how does ::const_iterator come up with a type name - Re:C++ very expressive indeed (Score:3, Informative) Not necessarily. If you have multiple types of containers and you can write a single sort that can sort all those types then why implement it in all of them instead of just once. Here [] is an article that deals with the question which functions should be members and which shouldn't. It uses the std::string as an example which has a lot, Re:The wonders of moderation (Score:1) Re:The wonders of moderation (Score:2) I'm afraid you just mentioned a few standard issue rants about C++ (all of which, as you can tell from the replies, are actually pretty groundless). The tone of your post wasn't clear -- I thought you were trolling initially as well -- so just put it down to bad luck, I guess. Re:C++ very expressive indeed (Score:3, Interesting) No, classes can have types too. In this case, a vector::const_iterator is an iterator over the vector type that can point to anything in the container (the vector) but cannot change anything in it. A read-only pointer, Re:C++ very expressive indeed (Score:1) I'm tired of people confusing any constraining in a language with being handcuffed. They are used so much to be loose that anything else looks like too tight to them. I know nothing about music, but when you learned you accepted the pentagram paradigm and language for describing music, didn't you? Do you need pointers and templates for music? seems like a single language, single paradigm to me. In the end if you don't like just don't use it. Re:C++ very expressive indeed (Score:1) I didn't say anything about being handcuffed. Sure, Java and other OO languages are Turing complete. You can write anything you want in them. Whether you should or not is another matter. Basically, you should always, as much as possible, use the right tool for the job. Sometimes, heck, even a lot of times, OO works well. But there are sometimes where it doesn't and for those times you're much better off using a langu Re:C++ very expressive indeed (Score:1) Re:C++ very expressive indeed (Score:2) It's awfully verbose. Namespaces don't help, because of irritating practical restrictions on the use of "using namespace" in header files. Its support for functional constructs is very limited. In particular, the lack of type inference and proper lambdas makes functional code painful to write. C++ is Re:C++ very expressive indeed (Score:2) But oh well, that code is really ugly A good book about it (despite the missleading title) is: Generative Programming from Ulrich Eisenecker (sorry, and another guy who has a to long/strange name to memorize, but that one is also a real coryphaea) angel'o'sphere Re:C++ very expressive indeed (Score:1) Re:C++ very expressive indeed (Score:1) That is actually being addressed by the Boost library [boost.org]. Boost is basically a testing ground for future additions to the language so if it works out there it's a good chance it will get added to the standard in a few years as an add on library, similar to the STL. For lambdas, take a look at The Boost Lambda Library [boost.org], especially the examples [boost.org]. Other st Don't Free Memory Unless You Have To (Score:2) I looked at Stroustrup's two examples. It looks like his first example does not involve freeing any memory at all. Am I right? His second example seems to use auto_ptr to assure that an object is freed when the function where it's allocated returns. Is that all it's doing? I would expect the situations where people get memory leaks to be more complex than auto_ptr could handle. Anyway, he never mentions garbage collection; just easier "explicit" management. (I put "explicit" in quotes, because malloc Re:Don't Free Memory Unless You Have To (Score:2, Informative) Re:Don't Free Memory Unless You Have To (Score:1) In case you missed it, here it is again: } I remember racing C code with (compiled) Scheme once, and the two were pretty close for the kind of task I was doing. However, when my problem size reached a certain point, GC would have to kick in and scheme was suddenly relegated to the vastly-slower-than-C camp, with so many other languages that otherwise would have plenty of merits. So I admit that gave me an instant ant-GC bias. (That and the _disaster_ Objects freed at end of function (Score:2) OK, now I understand. Basically he's saying that if you follow a certain discipline, allocated memory will be freed when the function returns. But the same could be said of explicitly freeing at the end of the function, and having goto's at places where you would otherwise return early. The second example bumps it up exactly one level. However, for objects that get passed around between more than two functions, you still need to keep track of what must be freed. Regarding Scheme performance, check out Re:Objects freed at end of function (Score:2) I think perhaps you're still misunderstanding slightly. The idea is that you wrap the resources in an automatic variable -- something that *will* be destroyed automatically when it goes out of scope. You cannot forget this, because the language does it for you. Now, have the destructor for that automatic variable release the resource it manages and bingo, you can never forget to release the resource. The idiom is known as "resource acquisition is initialisation", BTW, if you want to look it up. not as powerful as garbage collection (Score:2) I don't think I'm misunderstanding. I understand you have a mechanism that destroys the object a variable is bound to when that variable goes out of scope. That's only useful if you aren't putting the object in a data structure or otherwise planning on using the object outside of the block where that variable is in scope. Basically, it's only useful in trivial cases. I'm not saying it's worthless; I can see it has some advantage over explicitly freeing all the objects. It's just not anything near as po Re:not as powerful as garbage collection (Score:2) I still think you're misunderstanding the significance of this. :-) In well-written C++, almost all objects are automatic variables, or ultimately contained within objects that are automatic variables). It's also far more common to pass by value or pass a reference than it is to start throwing ownership around using pointers. You don't write: SomeType *st = new SomeType(); all over the place as in something like Java. You just write: SomeType st; under most circumstances. Typically, a data structu Re:Objects freed at end of function (Score:1) Language shootout - if that's the one I'm thinking of it promotes the use of unidiomatic, deliberately perverse code to make Perl look 2 times slower than it really is. However, it might not be the same shootout, so I'll google as soon as I click send. (But take that as a caveat that any language can be made slo subtl Re:Use More Manageable Types (Score:2) First of all, he is against GC, and thats why he finds ways to avoid it and arguments for its unnecessarity. However there two points which make his argumentation weak: a) you need to know a far big deal of "how the standard library works" and about c++ in general to apply his hints. If you had GC b) all the arguments *against* GC, are in fact arguments *for* GC. All the work and the burdon the ordinary programmer is freed fr:Certainly.. (Score:2) Re:Certainly.. (Score:2) Re:Certainly.. (Score:2) This is what destructors are for, so you can explicitly (in the destructor) free resources that haven't yet been freed. Simplifies dealing with exceptions, especially where an exception may take control out of the scope of the object. Sure, explicitly free your descriptors and whatnot -- that makes the code clearer -- but also do it in the destructor (wrapped in a suitable check so you don't do it twice, of course) as a back up. Re:Certainly.. (Score:2) You can just rely on the GC to clean up other system resources as well as memory, but most of them are alot finickier than memory - if you open a file, you want to close it when you're done, not when GC runs. Re:Certainly.. (Score:2) Actually, I'd argue that most of the time, you shouldn't be releasing anything directly. If you find yourself writing my_file.close(), consider whether you've got the my_file object at the right scope in the first place. What does it mean to refer to my_file after the close() call anyway? In most cases, the a Re:Certainly.. (Score:2) Re:Certainly.. (Score:2) Why? The whole point of deterministic destruction is that you can rely on destructors to clean things up, and in C++, the accepted idiom for resource management does just that. If the destruction is happening at the "wrong time", it's probably a symptom of a design flaw (see my other post in this subthread). Re:Certainly.. (Score:2) Like the other guy, I want to know when your destructors get called? Plus not every system allows you to override global new and delete operators (e.g. the Symbian cell phone OS). Re:Certainly.. (Score:2) Re:Certainly.. (Score:2) Personally, I think GC is over rated. GC should be left to langauges like Java where it is built in, and a lot of design consideration was put in to adding it to the langauge. At the bear minimum I think everyone should have to manage their own memory for a while in order to learn what's going and why it's going on. Re:Certainly.. (Score:2) GC in OpenCM (Score:5, Informative) The Boehm-Weiser (BW) collector is not as portable as we had hoped. There are a number of platforms we wanted to run on where it just doesn't run at all. Relatively small changes to the target runtime can create a need to port it all over again. OpenBSD, in particular, was an ongoing hassle until we abandoned BW. Hans, I hasten to add, was quite encouraging, but he simply doesn't have time to adequately support the collector. The BW collector doesn't work in our application. OpenCM has a few very large objects. For reasons we don't really understand, this tends to cause a great deal of garbage retention when running the BW collector. Enough so that the OpenCM server crashed a lot when using it. Please note that this was NOT a bug involving falsely retained pointers, as later experience showed. Conservative collectors are actually too conservative. If you are willing to make very modest changes in your source code as you design the app, there prove to be very natural places in the code for collection, and the resulting collector is quite efficient. Independent of the collector, we also hacked together an exceptions package. This was also the right thing to do, but it's easy to trip over it in certain ways. The point of mentioning this is that once you do exceptions the pointer tracking becomes damned near hopeless and you essentially have to go to GC. I think the way to say this is: exceptions + GC reduces your error handling code by a lot. Instead of three lines of error check on every procedure call, the error checking is confined to logical recovery points in the program, and you don't have to mess around simulating multiple return values in order to return a result code in parallel with the actually intended return value. To provide malloc pluggability, we implemented an explicit free operation. This lets us interoperate compatibly with other libraries and do leak detection. Turns out to be very handy in lots of ways. Hybrid storage management works very well. For example, our diff routine explicitly frees some of its local storage (example [opencm.org]) [Sorry -- this link will go stale within the next few weeks because the OpenCM web interface will change in a way that makes it obsolete. If the link doesn't work for you, try looking for the same file in .../DEV/opencm/...] This is actually quite wonderful, as it lets us build certain libraries to be GC compatible without being GC dependent. One of the challenges in using a GC'd runtime in a library is compatibility with an enclosing application that doesn't use GC. We haven't tried it yet, but it looks like our gcmalloc code will handle this. Eventually, we gave up on the BW collector and wrote our own. Our collector is conceptually very similar to the collector that Keith Packard built for Nickle [nickle.org], though we've since built from there. A variant of the Nickle collector is also used as a debugging leak tracer for X11. The OpenCM GC system is reasonably well standalone. We need to document it, but others might want to look at it when we cut our next release. On the whole, I'ld say that GC for this app was definitely the right thing to do. Once you get into object caches it becomes very hard to locate all of the objects and decide when to free them. We were able to use a conservative approach with no real hassle, and heap size is fairly well bounded by the assisted GC approach we took. On the other hand, I would not recommend a pure conservative collector for a pro There's another way. (Score:5, Informative) - The obvious: CPU & memory overhead for the checking and tracking. I can't comment on the amount here, but it is a generalized solution, so you forego the optimization opportunities that you'd otherwise have. - The subtle: Memory allocation can become a major bottleneck in multithreaded systems. Garbage collection has similar issues. - The irritating: you don't know when your destructors are called. Another way: Smart Pointers. They're simple wrappers around the types that act like pointers, but they can make sure your objects live as long as you need and no longer. The big trick is knowing which kind of smart pointer you want. - Reference Counting Smart Pointer (RCSP for short): this type of smart pointer will keep of how many RCSPs are pointing to the same object. It'll delete the object when the last RCSP is destroyed. A good one is the boost shared_ptr. Available for free from. This type is great for general use. - Owning Smart Pointer (OSP): this type is specialized for those cases when the refcnt is never more than 1. When you assign one OSP (a) to another (b), the new OSP (a) gets ownership of the referred object, and the old one (b) is automatically set to null. When an OSP that isn't set to null is destroyed, it deletes the object it owns. It's great for parameter passing, return values, and objects you want dead at the end of the current scope, even if there's an exception. The STL comes with auto_ptr, which works this way. You can use an RCSP wherever you can use an OSP, but not the other way around. The STL containers are a great example. Sure it's not as easy as 'allocate and forget,' but you won't have the (sometimes very costly) expense of full-blown garbage collection. Also, you can optimize your smart pointers for individual types (through template specialization). A great example is to give the no-longer-needed object back to a pool for later reuse. This is really a quick, quick overview. For the meat & potatoes, go read Effective STL by Scott Meyers. I've tried really hard to be fair & polite. There's probably still a bias, but I'm really trying!! Re:There's another way. (Score:1) Re:There's another way. (Score:2) Re:There's another way. (Score:1):1) And then there's the problem of circular references, which will never be reclaimed. Of course, it's not that hard to avoid those situations most of the time, but with GC you don't have to care. Ref-counting can be safe if used in conjunction with other methods. Its flaw is not only in that circular references between objects can't be tracked down but also in the general assumption that you should stay alive in memory while at least someone holds a reference to you. Semantically that's not always fair, sin Re:There's another way. (Score:2) A mechanism that allows to invalidate a reference when an object dies of its own will complements reference counting. Yep, manually breaking the circularity solves the problem, but that's not always possible. Re:There's another way. (Score:1) When exactly it's not possible? You program destruction notification yourself, so why it shouldn't be possible? The only difficulty here is extra coding in both objects, the reference holder and the target. They should be somehow `aware' of this functionality, and most likely it means that it should be built into the very basic class of your hierarchy, like Gtk and VCL do. From my experience, this technique combined with 'smart' pointers even in huge and complex applications do quite well. Re:Umm... (Score:2) Re:There's another way. (Score:1, Interesting) Re:There's another way. (Score:2) You also have to consider cache lines to avoid stalling different threads. There's a dozen other factors as well. In the end even your best generational garbage collector is no match for a modern SMP malloc/free implementation like Hoard. Google on it. Thanks, I will. I'll freely admit that my knowledge of memory management schemes was state of the art circa 1998, but that changes in processor architecture (heavy memory caching, deep pipelines) and machine architecture (widespread SMP) could very well Re:There's another way. (Score:2) If a mutex is active and a thread blocks it will get put into the wait queue and not use CPU. The only ready processes will be new IO, then you are back to the GC code again. The only overhead is the actual scanning on a single CPU system. I agree that GC and SMP can get a bit harry (probably be best to divide the memory space N ways for an N processor system and seperate thread memory as much as possible). It's also true that GC w Re:Sorry (Score:2) Re:Sorry (Score:2) The SUN JRE is terrible on SMP. I've tried it and know how horrible it is. The newer JVMs are better from SUN, but anyone wi the key to it all (Score:1) >The reason is, of course, that you build the pooling based on your knowledge of the actual usage characteristics of the objects; knowledge that no general-purpose memory manager can possibly have. I find this in general... Garbage Collectors, not unlike VMs, do well when they know their problem domain well. So, it's common to use a Garbage Collecto GC costs (Score:5, Informative) There is another indirect cost pointed out by Linus Torvalds in a lengthy post to the gcc mailining list [gnu.org]. The executive summary is that (he thinks that) memory that is not to be used anymore should be freed immediately. Otherwise, the data in there will keep lying around in the data cache. Also, he claims that explicit ref-counting gives you advantages for optimization: Assume you have to make some modifications to a data structure, but you don't want other parts of the program to see the modifications. Without ref-counting, you have to copy all the data structure before modifying it. With ref-couting, you can omit the copying if you are the only one with access to the data structure. And finally, he thinks that GC makes it too easy to write pointer-chasing-heavy code---as that kind of code is bad for cache behaviour all the time. It is an ongoing discussion whether GC really has that bad effects on performance of GCC. But Linus Torvalds seems to have very good points. (And some of them certainly cannot be taken into account in a "GC cost is less than hand-written memory management"-paper.) Re:GC costs (Score:4, Interesting) Re:GC costs (Score:3, Insightful) GC and GCC (Score:2) Many people are not aware that GCC itself uses garbage collection as it runs. You can actually select which algorithm gets used at configure time, and tweak the GC parameters during runtime (via a growing set of command-line options that users never think to use). That aside: I've corresponded with Linus a couple times (on other subjects), and while he is the brilliant guy that /. thinks he is, he is a kernel expert, not a compiler expert. Entirely different problem domain, very differnt approaches to Re:GC costs (Score:2) After reading many of Linus Torvalds' posts, I think it's useful to remember where he's coming from. He's spent ten years writing a kernel, with some of the best programmers, where every line of code has been rewritten several times. Yes, in that environment, garbage collection won't a huge win. But you don't always have forever to work on one project; you don't always have a team of crack programmers on the job; and a lot of times, efficency is not of pri Re:There's another way. (Score:2) Costs in the OpenCM collector (Score:1) It turns out, however, that there are natural places to do GC, and a little help from the application can go a very long ways. In the OpenCM collector, we mark procedures that return pointers using a special GC_RETURN macro. This works because at the return from a procedure all of its local variables are known to be unreachable. The only surviving objects are the ones that are reachable fro Re:There's another way. (Score:1) Re:There's another way. (Score:2) So, if you have two RCSPs pointing at each other (or a whole daisy chain of them), and nothing else pointing to any of them, when do they get deleted? (They don't. That's the weakness of reference counting. You're fine so long as you never create any circular lists. (That's one reason you cannot create hard link Re:There's another way. (Score:1) I've read from multiple resources that smart pointers don't work with STL containers (due to the way the internal container handles memory) Re:There's another way. (Score:2) A bit off-topic, perhaps. (Score:3, Informative) A program variable is either a global variable, a stack variable, a class variable or an instance variable. Global and stack variables are held in lists. Class and instance variables are kept inside objects. Every class object has a global variable that always refers to it. Any object that is not, and that can not become referenced (directly or indirectly) by a global or stack program variable is garbage. Each object has a 'not-garbage' flag. For each global and stack variable, if the referenced object is not marked not-garbage, mark the referenced object as not-garbage, and recurse for that objects contained variables. Delete all objects that are not marked not-garbage. There are a few more twists, like handling return values on the stack, but this algorithm correctly handles self-referencing objects no matter the complexity.. Re:It's okay (Score:2) Re:It's okay (Score:1) If Boehm says to Knuth "but you shouldn't be doing that", then I think it's perfectly acceptable for Knuth to respond "but _you_ shouldn't be doing _that_". YAW. Memory Mapped Files (Score:1) I once wrote some classes to work with Memory Mapped Files (under Windows) in an almost transparent manner. It works great for making complex C++ object hierarchies persistant. writing pointers to disk (Score:1) Luckilly I don't need my head to type. I can no longer read the articles on slashdot... but that doesn't matter, I can still post. Boehm collector on large application (Score:2, Informative) The salient points: Destructors are not Called If an object is allocated in collectible memory, then its destructor will not be called when the object is collected. Therefore, destructors are pretty much useless and your code must be designed to work without them. Actually, if your object derives from class gc_cleanu Very happy... (Score:3, Insightful) ILOG Solver / Scheduler (Score:1) ILOG [ilog.com] Solver & Scheduler are mainstream commercial thrid party libraries in C++ based on the constraint programming paradigm. One of the major features is ILOG's automatic garbage collection heap, which is automatically deallocates memory (based on assumptions on program flow). To make this efficient, they skip all deallocations (using a longjump, rather than a return). At first this may look like an elegant way to get rid of complicated memory management & garbage collection without loosing efficie Qt has nice garbage collection (Score:1) Tom. Re:Qt has nice garbage collection (Score:2) Good Book on Garbage Collection (Score:3, Insightful) You need GC... (Score:1) (Granted, one could say that this would apply to the GC itself, but not necessarily so) The trick is, memory is a 'resource' and as such is subject to acquisition and release steps in order to maintain it properly. If the notion of ownership of memory is ambiguous, you need to normalize your data somehow so you get back to a 1:n relationship between owners and acquired resources. This happe Smart Pointers (Score:1) Automated Object Management in NewJ for C++ (Score:1) Instead, we developed our own automated object management facility based on reference objects, that is, "smart pointer" objects with these new capabilit GC has it's place ... just not something for me (Score:1) Re:your lesson for today (Score:1) First i'm not sure this post isn't a troll.. but whatever. While code organization could have a huge impact on the complexity of a program, this is simply not the reason's for most memory leaks in my experience. Most are because of stupid human mistakes. IE creating an array and only deletingthe first node. These are hard to catch because the Re:your lesson for today (Score:1) All a computer program is *is details*. Every single non-comment line is a crucial detail. Using C instead of assembly is because C takes care of details that I have no need of taking care of. My overall point here is that if you don Re:your lesson for today (Score:1) Programms are details, this does not mean programming has to be. Something like GC allows you to abstract a bit mo Re:your lesson for today (Score:1) Yes, GC is just shifting the responsibility, but the freeing-unused-memory pied-piper must be paid by something, no matter the language, no matter the os. And, when it comes right down to it, we are already developing more programmers n Re:your lesson for today (Score:1) but the freeing-unused-memory pied-piper must be paid by something, no matter the language, no matter the os. Paid for in what sense? I know from experience that I pay in programming time when doing manual memory management. If you mean paid for in CPU time, you should understand that malloc and free take a significant amount of time already. They are not free. GC does not add a great deal to that cost. And, when it comes right down to it, we are already developing Re:your lesson for today (Score:1) I know it's a very popular opinion here that details must be paid attention too. But when you have a language, tho p Re:your lesson for today (Score:1) "Seek and ye shall find." If you do *not* seek perfection, you will get just that, and when you say we you are really saying I. And to the legions of people who don't try harder, I say "cheers". Keep up the mediocre work. Re:your lesson for today (Score:1) bmac, have you read Structure And Interpretation Of Computer Programs (SICP) by Abelson, Sussman and Sussman (it's available online, as an MIT *introductory* CS course)? They use Scheme as their programming language and, in the space of ~600 pages they go from "let's write an expression in Lisp/Scheme" to "let's write a Scheme compiler". Lisp/Scheme uses GC. When they write the compiler, they provide a simple implementation of a GC in the pseudo-assembly they compile to. It's possible to use a language with Re:your lesson for today (Score:1) There is far more than only programming in computer sciense. Supposed you wanted to write a Go program Re:your lesson for today (Score:1) I actually disagree because we are really the only people on the planet who deal with iterations in the millions and billions. Being able to deal with those numbers (and, more importantly the Butterfly Effect) gives us a better understanding of the impact of billions of human b Re:your lesson for today (Score:2) Re:your lesson for today (Score:1) As far as your remarks about OS-level code go, people have experimented, successfully, with writing large portions of what might normally be regarded as "the kernel" in a garbage collected language. One example is the SPIN project at the U of Washin
http://developers.slashdot.org/story/03/09/16/0032242/experiences-w-garbage-collection-and-cc?sdsrc=prev
CC-MAIN-2015-14
refinedweb
5,155
61.56
Is it possible to convert std::FILE* to iostream ? no there is no readily available facility in the standard library to do this. however, the library is designed to be extensible: so we can easily write our own stream/streambuf derived classes. the Boost.Iostreams library does contain stream/streambuf derived classes which use a file descriptor/HANDLE. Boost is widely portable, so we could just use it instead of rolling out our own classes. #include <stdio.h> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #include <iostream> int main() { FILE* file = fopen( "/tmp/file.txt", "w" ) ; int fd = fileno(file) ; using namespace boost::iostreams ; file_descriptor_sink fdsink(fd) ; stream< file_descriptor_sink > ofstm( fdsink ) ; std::ostream& std_ostm = ofstm ; std_ostm << "FILE* " << file << " fd: " << fd << '\n' ; } note: link with libboost_iostreams. eg. >g++ -Wall -std=c++98 -pedantic -I /usr/local/include -L /usr/local/lib -lboost_iostreams stream_from_filestar.cc Is it possible to convert std::FILE*to iostream? Sure, using gnu's extension like it's described here : file-to-iostream (c++)/ short extract : FILE *f_pipe_in; // ... open the file, with whatever, pipes or who-knows ... // let's build a buffer from the FILE* descriptor ... __gnu_cxx::stdio_filebuf pipe_buf (f_pipe_in, ios_base::in); // there we are, a regular istream is build upon the buffer : istream stream_pipe_in (&pipe_buf); Please don't drag up 2 year old threads. And it should be noted that in standard C++ no there is not a way. Chris
https://www.daniweb.com/programming/software-development/threads/119979/file-and-iostream
CC-MAIN-2019-13
refinedweb
237
67.25
We've developed an extensible package that lets power users define their own views of the data. Now they want to print it, and for people who don't use the program (i.e., senior management), the quality of the printed output is critical. There are many different options for printing on Windows. We start by reviewing some common business needs and output formats. We then go on to look at three completely different techniques for printing: automating Word, using Windows graphics functions, and finally direct generation of Portable Document Format (PDF) files from Python. Doubletalk's obvious goal is to produce a complete set of management accounts. These will almost certainly include company logos, repeating page headers and footers, several different text styles, and charts and tables. It would be highly desirable to view the output onscreen and keep it in files. This makes for a faster development cycle than running off to the printer and means you can email a draft to the marketing department for approval or email the output to your customers. Most important, it should be possible for users (sophisticated ones, at least) to customize the reports. Everyone in business needs custom reports. Companies who buy large client/server systems often have to invest time and training in learning to use a report-design tool. Systems that don't allow custom reporting either fail to give their customers what they need, or (with better marketing) generate large revenues for the consulting divisions of their software houses to do things the customer could have expected for free. If we can find a general solution that works from Python, the users are automatically in charge of the system and can write their own report scripts. This is a compelling selling point for a commercial application. There are several different document models you might wish to support. They all end up as ink on paper, but suggest different APIs and tools for the people writing the reports: Graphics programming model The report designer writes programs to precisely position every element on the page. Word-processor model Elements flow down the page and onto the next. There may be some sort of header and footer than can change from section to section. Tables need to be broken intelligently, with repeating page headers and footers. Spreadsheet model A grid underlies the page, and this can produce sophisticated table effects. However, it starts to cause problems if you want more than one table on a page with different column structures. Database form model The same form is repeated many times with varying data, possibly covering an invoice run, a mailmerge, or bank statements for customers. Forms can exceed one page and include master-detail records and group headers and footers. Desktop-publishing model This is the most sophisticated document model in common use: the user specifies certain page templates and may have many pages of a given template. Within pages, there are frames within which objects can flow, and frames can be linked to successors. You need to keep your options open; don't expect all these to be provided, but look for technologies that can be adapted to a different model for a different project. We've been involved with several different reporting systems over the last few years, and all have had their shortcomings. It is instructive to run through some of their lessons. Project A involved a database of packaging designs, which could be understood only with diagrams showing the box designs laid out flat and semifolded. Report- ing was left until the last minute because the developers were not really interested; when time and budget pressures arose, customers got something very unsatisfactory thrown together with a database reporting tool. They were told that the tools just did not support the graphics and layout they really wanted. This situation is all too common. Project B involved extracting database data to produce 100-page medical statistical analyses; the reports were examples of a word-processor model and could include numerous multipage tables with precise formatting. A collection of scripts assembled chunks of rich text format (RTF) to build the document, inserting them into Word. It became clear that Python was the right tool to extract and organize all the data; however, RTF is complex to work with and isn't really a page-description language. Project C was a scientific application that captured and analyzed data from a device and produced a family of reports; including charts and statistical tables. The reports needed to be viewed onscreen and printable. They were written using Windows graphics calls. Previewing accurately is a pain in the neck to implement at first, but worth it afterwards. It soon became clear that you could share subroutines to produce all the common elements; thus, one routine did the customer logo on all pages, and the same table routine could be used throughout. Changes to a common element would be applied across the whole family of reports with accuracy. It became clear that writing graphics code was a powerful approach, well suited to object-oriented development and reuse. Project D involved a family of database reports produced using a graphic report writer (similar to the Report function in Access). A team of developers put these together. Although layout was initially easy, making a global change to all the reports was a nightmare. Furthermore, it became hard to know if calculations were done in the database or the report formulae themselves, leading to maintenance problems. Worst of all, testing involved going directly to the printer; there was no way to capture the output and email it to a colleague for scrutiny. Project E used a dedicated scripting language that could import fixed-width and delimited text files and that output in PostScript. This was suited to high volumes of data, allowed code sharing between reports, and generally worked extremely well. The language used did not allow any kind of object-oriented programming, however, which made it hard to build higher-level abstractions. Looking at all these experiences, the ideal solution would seem to have the following characteristics (apart from being written in Python): The Python script acquires the data from whatever sources it needs (databases, object servers, flat files) and validates it. The Python script uses a library to generate a suitable output format, preferably with all the right layout capabilities. The report library allows users to reuse elements of reports, building up their own reusable functions and objects over time. Now let's look at some of the possible output formats and APIs: Word documents Most Windows desktops run Word, and a free Word viewer is available. It's easy to automate Word and pump data into it, with good control over page appearance. As we will see, you can do a lot of work with templates, separating the programming from the graphic design. Unlike all other solutions discussed, Word handles document flow for you. It isn't at all portable, but Word documents allow the user to customize the output by hand if needed. Windows Graphical Device Interface (GDI) Windows provides a wide range of graphics functions that can output to a screen or to a printer. Essentially the same code can be aimed at both. This needs to be initiated differently for a multipage report as opposed to a single view on screen. GDI calls involve drawing on the page at precise locations; there is no concept of document flow. PostScript PostScript is a page-description language with advanced capabilities. It is the language of desktop publishing and has defined an imaging model that most other graphics systems try to follow. PostScript files can be sent directly to a wide variety of printers and viewed with free software on most platforms. PostScript is quite readable and easy to generate. This is a multiplatform solution, but it isn't commonly used as an output format on Windows. PostScript can be viewed with GhostView, a popular Open Source package, or converted to PDF with Adobe's Distiller product. Portable Document Format (PDF) PDF is an evolution of PostScript aimed at online viewing; conceptually, it's PostScript broken into page-sized chunks, with compression and various internal optimizations for rapid viewing. Acrobat Reader is freely and widely available for Windows and other systems, and allows people to view and print PDF files. PostScript Level 3 allows PDF documents to be sent direct to PostScript printers. PDF is much more complex than PostScript, but end users never need to look at the internals. Excel documents For invoices and other business forms and some financial reports, Excel offers a natural model. As we've seen, data can be pumped into it fast, and excellent charts can be generated in Excel itself. Care must be taken over the page size and zoom to get a consistent look across multipage documents, and there is little to help you with page breaking. Excel is highly useful if users want to play with the numbers themselves. HTML HTML is ubiquitous, and there are great tools for generating it from Python. The latest web browsers do a good job of printing it. However, it doesn't let you control page breaking or specify headers and footers, and there are no guarantees about how a web browser will print a page. As we will see later in this chapter, there are ways to incorporate HTML into your reports in other systems, which is an easy way to meet part of our requirements. SGML and XML SGML (Standard Generalized Markup Language) is a large and complex language used for marking up text in the publishing industry. It is well suited for the layout of a book, but not for precise graphics work. It has enormous capabilities but is quite specialized, and viewers are not widely available. XML (Extensible Markup Language) was derived from SGML and is touted by many as the Next Big Thing on the Weba possible successor to HTML and a foundation for electronic commerce. Python offers superb tools for working with XML data structures. It is a family of languages rather than a single one and doesn't necessarily have anything to do with page layout. The general concept is to describe the data (''this is a new customer header record'') and not the appearance ("this is 18 point Helvetica Bold"). Our feeling about XML is that (like Python data structures) it's a great way to move data from place to place, but it doesn't solve the problem of how to format it.* However, once we have a useful Python printing tool, it could be put to work with some kind of style-sheet language to format and print XML data. In general, these formats/APIs fall into three camps: Windows GDI is a C-level graphics API involving precise drawing on the page. Word and Excel are applications you can automate through COM to generate the right documents. Naturally, they have to be present to create and to view the documents. The others, including PostScript and PDF, are file formats. You can write pure Python class libraries to generate files in those formats. Like the Windows API (which borrowed heavily from PostScript), they offer precise page-layout control. Let's begin by automating Microsoft Word. Later in the chapter, we discuss Windows GDI, PostScript, and PDF, with a view to a unified API for all three. We haven't done a full set of management accounts for each, but we take them far enough that you can figure it out yourself. As noted previously, Word is an appealing alternative for many reasons. It has a powerful printing and formatting engine. It's on a lot of desktops; indeed it may be a standard throughout your company. A free Word viewer is also available from Microsoft. Finally, it's possible to post-process a document written in Word; you can generate a set of management accounts or a stack of letters, and users can add annotations as they wish. As discussed with Excel, there are two options: use Python to take control of Word, or have Word VB grab data from Python and format it. In Chapter 9, Integration with Excel, we mentioned some guidelines for choosing which application was on top. We've shown Python automating Word for the following reasons: There is a good chance that report production would be an automated step in the middle of the night; people won't be using Word as an interactive query engine in the same way as Excel. Python excels at formatting text and getting data into the right shape. The Word document model is easy to automate. We'll be adding chunks to the end of a document, and the details can be wrapped easily in reusable Python code. Reports change and evolve rapidly. It's easier to change a generic Python script than customize a Python COM server with new special-purpose methods. However, there's absolutely no technical barrier to doing it the other way around, and that may work for you in some circumstances. As with Excel, make sure you have the Word VB reference installed to document the object model, and install MakePy support for the Word object model. Let's start with the simplest possible example: from win32com.client import Dispatch MYDIR = 'c:\\data\\project\\oreilly\\examples\\ch12_print' def simple(): myWord = Dispatch('Word.Application') myWord.Visible = 1 # comment out for production myDoc = myWord.Documents.Add() myRange = myDoc.Range(0,0) myRange.InsertBefore('Hello from Python!') # uncomment these for a full script #myDoc.SaveAs(MYDIR + '\\python01.doc') #myDoc.PrintOut() #myDoc.Close() When you execute this function, Word starts, and your message is displayed. We've commented out the lines at the bottom, but you can choose to print, save, or close the document. It's fun to arrange the Python console and Word side-by-side and watch your text appearing, and a great way to learn the Word object model. You could hand-build a document and automate all the formatting, but that would be tedious.-Far better to use a Word template and just put in what you need from your Python code. For the next example, we've created a template called Pythonics.dot. This has a fancy header, page numbers, and borders. It could also contain section headings, a table of contents, standard text, or whatever you want. Using a template is a huge leap forward in productivity. Figure 10-1 shows ours. More important, a template allows you to separate the software development from the page layout. An artistically challenged developer could provide a basic template with the required elements, and turn it over to the marketing department to define the styles and boilerplate text. If she also delivers a Python test script containing example data, the marketing person can regularly test whether the program still runs while he is modifying the template. To create a document based on a template, you need to modify only one line: >>> myDoc = myWord.Documents.Add(template=MYDIR + '\\pythonics.dot') Note the use of keyword arguments. Many of the Office functions (like Documents.Add) take literally dozens of arguments, and entering them every time would be tedious. Fortunately, Python also supports named arguments. However, you need to watch the case: most Word arguments have initial capitals. Word offers too many choices for building a document: you can loop over a document's contents, search for elements such as words or paragraphs, and select any portion of the text to work with. We'll assume you want to build a document in order from beginning to end. Let's start with a Python class to help automate the production of documents. First we'll construct an object that has a pointer to a Word document, then add the desired methods one at a time. The class is called WordWrap and can be found in the module easyword.py. Here are some of its methods: class WordWrap: """Wrapper around Word 8 documents to make them easy to build. Has variables for the Applications, Document and Selection; most methods add things at the end of the document""" def __init__(self, templatefile=None): self.wordApp = Dispatch('Word.Application') if templatefile == None: self.wordDoc = self.wordApp.Documents.Add() else: self.wordDoc = self.wordApp.Documents.Add(Template=templatefile) #set up the selection self.wordDoc.Range(0,0) .Select() self.wordSel = self.wordApp.Selection #fetch the styles in the document - see below self.getStyleDictionary() def show(self): # convenience when developing self.wordApp.Visible = 1 def saveAs(self, filename): self.wordDoc.SaveAs(filename) def printout(self): self.wordDoc.PrintOut() def selectEnd(self): # ensures insertion point is at the end of the document self.wordSel.Collapse(0) # 0 is the constant wdCollapseEnd; don't want to depend # on makepy support. def addText(self, text): self.wordSel.InsertAfter(text) self.selectEnd() You work with the Selection object, which provides several methods for inserting text. When you call Selection.InsertAfter(text), the selection expands to include whatever you add; it also provides a Collapse method that can take various parameters; the one you need, wdCollapseEnd, happens to have a value of zero, and collapses the Selection to an insertion point at the end of whatever you've just inserted. If you are using MakePy, you can access the constant by name; since this is the only constant we'll use in this application, we looked up the value and used it directly to produce a script that works on all PythonWin installations. You can explicitly format text with precise font names and sizes by assigning them to the many properties of the Selection object, but it is less work and a better design to use predefined styles. It's far easier to change a style than to adjust 20 different reporting scripts. The first thing to do is add a paragraph in a named style. Word has constants for all the standard styles. If you used MakePy to build the support for Word, you could access the built-in styles like this: >>> from win32com.client import constants >>> mySelection.Style = constants.wdStyleHeading1 >>> Note that we set the Style property of the currentRange to the correct style constant. This doesn't work if youuse dynamic dispatch, or if you have your own custom template withstyles that aren't built into Word. However, you can query a document at runtime. The following method gets and keeps a list of all styles actually present in a document: def getStyleList(self): # returns a dictionary of the styles in a document self.styles = [] stylecount = self.wordDoc.Styles.Count for i in range(1, stylecount + 1): styleObject = self.wordDoc.Styles(i) self.styles.append(styleObject.NameLocal) The Style property of a Range or Selection in Word accepts either a constant or a string value, so you might as well use the names. Here's a useful method: def addStyledPara(self, text, stylename): if text[-1] <> '\n': text = text + '\n' Let's try: >>> import easyword >>> w = easyword.WordWrap() >>> w.show() >>> w.addStyledPara('What I did on Holiday', 'Heading 1') >>> w.addStyledPara('blah' * 50, 'Normal') >>> This should give you something that looks like Figure 10-2 Our wrapper class and Word's style features combine to make it easy to build a document. Word tables are sophisticated object hierarchies in their own right, and you can manipulate them to any level of detail. However, there's also an AutoFormat option for tables that works in a similar way to styles. Here's the full declaration: Table.AutoFormat(Format, ApplyBorders, ApplyShading, ApplyFont, ApplyColor, ApplyHeadingRows, ApplyLastRow, ApplyFirstColumn, ApplyLastColumn, AutoFit) All you have to do is insert a block of tab-delimited text with the table contents, and call the method to convert text to a table, then call the table's AutoFormat method. Fortunately, almost all the arguments are optional: def addTable(self, table, styleid=None): # Takes a 'list of lists' of data. # first we format the text. You might want to preformat # numbers with the right decimal places etc. first. textlines = [] for row in table: textrow = map(str, row) #convert to strings textline = string.join(textrow, '\t') textlines.append(textline) text = string.join(textlines, '\n') # add the text, which remains selected self.wordSel.InsertAfter(text) #convert to a table wordTable = self.wordSel.ConvertToTable(Separator='\t') #and format if styleid: wordTable.AutoFormat(Format=styleid) Unfortunately, to specify a style, you need to supply a numeric format constant instead of a name. If you are using MakePy, this is easy; an alternate approach is to use Word's VB editor to look up the constants. Be warned: some constants vary across different language editions of Word. Tables can be accessed through the Document.Tables collection. Adding be set to a valid range in the document, and it's then constrained to stay on the same page as the first paragraph in that range. You then have to choose a coordinate system with the RelativeHorizontalPosition and RelativeVerticalPosition properties, which say whether the location is measured relative to the current page, column or paragraph. Finally, you set the Left and Top properties to define the location in the given coordinate system. We managed to write some VBA code to position charts using these objects and properties, but found the behavior inconsistent. If you've ever struggled to position a screen shot in a document while it jumps around at random, imagine what it is like doing it in code from another application! With a large shape, Word would decide that the initial location or page was impossible before you had finished setting properties and give different behavior from Python and from VBA.* Finally we discovered the InlineShapes collection (not a name you would look for) that filled the bill. An InlineShape is conceptually part of the document; put it between two paragraphs, and it stays between them forever. The arguments to its constructor didn't work as advertised; the shapes always seemed to appear at the beginning of the document, but it was possible to cut and paste them into position. The following code finally did the job: def addInlineExcelChart(self, filename, caption=", height=216, width=432): # adds a chart inline within the text, caption below. # add an InlineShape to the InlineShapes collection #- could appear anywhere shape = self.wordDoc.InlineShapes.AddOLEObject( ClassType='Excel.Chart', FileName=filename ) # set height and width in points shape.Height = height shape.Width = width # put it where we want shape.Range.Cut() self.wordSel.InsertAfter('chart will replace this') self.wordSel.Range.Paste() # goes in selection self.addStyledPara(caption, 'Normal') The same routine can be easily adapted to place bitmaps. If you have a simpler solution, drop us a line! Now we can build a set of management accounts. The example applications include a Word template, an Excel spreadsheet with a prebuilt chart, and a test routine in easyword.py. Thanks to helper methods, this is simple: def test(): outfilename = MYDIR + '\\pythonics_mgt_accounts.doc' w = WordWrap(MYDIR + '\\pythonics.dot') w.show() # leave on screen for fun w. addStyledPara('Accounts for April', 'Title') #first some text w.addStyledPara("Chairman's Introduction", 'Heading 1') w.addStyledPara(randomText(), 'Normal') # now a table sections w.addStyledPara("Sales Figure s for Year To Date", 'Heading 1') data = randomData() w.addTable(data, 37) # style wdTableStyleProfessional w.addText('\n\n') # finally a chart, on the first page of a ready-made spreadsheet w.addStyledPara("Cash Flow Projections", 'Heading 1') w.addInlineExcelChart(MYDIR + '\\wordchart.xls', 'Cash Flow Forecast') w.saveAs(outfilename) print 'saved in', outfilename This runs visibly for fun, but would be much faster if kept off-screen. It produces the document in Figure 10-3. Word can import and export HTML. The following line inserts an entire file into the current document: >>> wordSelection.InsertFile(MYDIR + '\\tutorial.html') >>> Furthermore, some experiments revealed that you don't even need a full HTML document, just tagged text saved with the extension HTML. So if you want an easy way to pump large amounts of text into a Word document, generate the HTML and insert it. Python has an excellent package, HTMLgen, for generating sophisticated markup from code. Word can import HTML tables with reasonable success, and all of the standard HTML styles are marked as styles in Word. These days there is a need to produce both printed and online versions of documents. If you write code to generate the HTML, and then import it into a smart Word template with the right corporate header and footer, you have a complete solution. There is another approach for incorporating Word. You can use Python as the COM server and Word as the client. We discussed the pros and cons of this approach with Excel at the end of Chapter 9; the same design considerations apply. Using Word as a client, use Visual Basic for Applications to initialize a Python server and fetch the data. The most natural way to package this is to build a Word template that includes the code and the desired document elements. When a new document is created from the template, it connects to the Doubletalk COM server we built earlier, instructs it to load the data, fetches the tables of information it needs, and uses VBA code to place the data into the document. This approach has two advantages: VBA offers nice editing features like drop-down auto-completion, helping you to learn the Word object model quickly. Debugging is also easier (assuming you have separately tested your Python server, and the Word object model is what is giving you trouble). You can safely tie functions in your template to regions of text or tables in your template without needing to be too generic. Data preparation is Python's job; formatting is Word's Please note: Word is hard to work with. Even if you plan to write a controlling program in Python, you should sort the code you need in VBA and check that it all runs first to save time. The manuals and the product itself are buggy in places. It is also somewhat unstable during development; if you make lots of COM calls that cause errors, it tends to crash frequently. Once the code is correct, it seems to keep working without problems. Some other Python users have worked with very large documents and reported stability problems in making thousands of COM calls in a row while creating large documents. However, we do expect this situation to improve; Word 8.0 is the first version with VBA, whereas people have been automating Excel in real-time systems for years. Furthermore, we expect Word to handle XML in the future, which will allow more options for pumping in lots of data quickly. In conclusion, you have the technology to do almost anything with Word. However, it's a heavyweight solution. Whether it's the right format for you depends on several factors: Word documents are the output format you want. Your users have Word. Your reports fit a word-processor flow model. Whether it's important to protect the integrity of a finished report or let users tweak it afterwards. The next technique to look at is Windows printing. We start off with a minimal example, then discuss the principles behind it. Start by typing the following at a Python console: >>> import win32ui >>> dc = win32ui.CreateDC() >>> dc.CreatePrinterDC() >>> dc.StartDoc('My Python Document') >>> At this point, you'll see a printer icon in the System Tray. Double-click, and you see Figure 10-4. Now we'll print a few words and draw a line on the page: >>> dc.StartPage() >>> dc.TextOut(100,100, 'Python Prints!') >>> dc.MoveTo(100, 102) (0, 0) >>> dc.LineTo(200, 102) >>> dc.EndPage() >>> As soon as you type EndPage, your page should begin to print on your default printer. The Status column in the Printer window changes to look like Figure 10-5. Finally, tell Windows you've finished printing: >>> dc.EndDoc() >>> Hopefully, a few seconds later you will have a page with the words Python Prints near the top left and a horizontal line just above it. If you've ever done any Windows graphics programming, this will be familiar. The variable dc is an instance of the Python class PyCDC, which is a wrapper around a Windows Device Context. The Device Context provides methods such as MoveTo, LineTo, and TextOut. Device Contexts are associated with windows on the screen as well as with printers; the graphics code is identical, although the way you start and finish differs: windows don't have pages, for example. In Chapter 20, GUI Development, we cover PythonWin development in some detail, and the example application involves graphics calls of this kind. There is, however, one significant problem with your printout: the line on your page is probably rather tiny. The coordinates used were pixels. On the screen, you typically get about 100 pixels per inch; if you'd written the previous code for a window, the text would be an inch down from the top left of the window and about as long as the words. On a typical HPDeskJet printer, which has a resolution of 300 dots per inch, the line is just a sixth of an inch long; yet the text is still a sensible size (it will, in fact, be in the default font for your printer, typically 10-point Courier). For printed reports, you need precise control of text and graphics; numbers need to appear in the columns designed for them. There are several ways to get this. We will use the simplest, and choose a ready-made mapping mode, one of several coordinate systems Windows offers, based on twips. A twip is a twentieth of a point; thus there are 1440 twips per inch. Windows can draw only in integer units, so you need something fairly fine-grained such as twips. (Windows also provides metric and imperial scales, or lets you define your own.) In this coordinate system, the point (0, 0) represents the top left corner of the page, and y increases upwards; so to move down the page, you need negative values of y. To set up the scale, you need just one line: dc.SetMapMode(win32con.MM_TWIPS) To test it, we'll write a little function to draw a six-inch ruler. If it's right, you can call this function after setting the mapping mode and take out a real ruler and check it. Here's the ruler function and a revised script: import win32ui import win32con INCH = 1440 def HorizontalRuler(dc, x, y): # draws a six-inch ruler, if we've got our scaling right! # horizontal line dc.MoveTo(x,y) dc.LineTo(x + (6*INCH), y) for i in range(7): dc.MoveTo(x,y) dc.LineTo(x, y-INCH/2) x = x + INCH def print_it(): dc = win32ui.CreateDC() dc.CreatePrinterDC() # ties it to your default printer dc.StartDoc('My Python Document') dc.StartPage() dc.SetMapMode(win32con.MM_TWIPS) # text - near the top left corner somewhere dc.TextOut(INCH,-INCH, 'Hello, World') # 1inch in, 8 up HorizontalRuler(dc, INCH, - INCH * 1.5) dc.EndPage() dc.EndDoc() print 'sent to printer' del dc We've seen how to control precise page layout and also seen a reusable function that does something to a Windows device context. This is a first step in building your own graphics library. As everyone who's ever read a textbook on object-oriented programming knows, the natural approach is to make a class hierarchy of objects that can draw on the device context. Having shown you the basics, we'll move on, and return to the class library later. While working on this book, we tried to create a printing system that could handle multiple formats, including Windows and PDF. At the same time, several people in the Python newsgroup felt that it was a real pity everyone was using platform-specific code to draw charts and diagrams, and that it should be possible to come up with a common API that covered several output formats. A team of fourJoe Strout, Magnus Hetland, Perry Stoll, and Andy Robinsondeveloped a common API during the spring of 1999, and a number of backends and a test suite are available at press time. This has produced some powerful printing solutions, which we explore here. The API is known as Plug-In Drawing, Does Little Else (PIDDLE) and is available from. The package includes the basic API, test patterns, and as many backends as are deemed stable. The basic API defines classes to represent fonts and colors, and a base class called Canvas, which exposes several drawing methods. The base canvas doesn't produce any output and exists to define an interface; specific backends implement a canvas to draw on the relevant device or file format. Let's quickly run through the main features of the PIDDLE API. At the time of writing, backends are available for PDF, the Python Imaging Library (which lets you draw into BMPs, JPEGs, and a host of other image formatsuseful for web graphics), OpenGL, Macintosh QuickDraw, PostScript, Adobe Illustrator, Tkinter, wxPython, and PythonWin. Not all of these implement all features correctly, but things are evolving rapidly. When you get to Chapter 20, bear in mind that one Python graphics library can draw to all the GUI toolkits we cover. Each platform has a different font mechanism. PIDDLE defines a Font class to rise above this. A Font instance has attributes face, size, bold, italic, and underline. A standard set of font names are provided, and each backend is responsible for finding the best local equivalent. Color class instances are created with red, green, and blue levels between zero and one. The module creates a large number of colors based on the HTML standard, so the word red may be used to refer to a ready-made Color object. The PostScript default scale of 72 units per inch is used, but with the origin at the top left of the page and y increasing downwards. The Canvas class provides drawing methods and overall management functions. The graphics functions provided (we will skip the arguments) are drawLine, drawLines, drawString, drawCurve (which draws a Bezier curve), drawRect, drawRoundRect, drawEllipse, drawArc, drawPolygon, and drawFigure (which can manage an arbitrary sequence of line, arc, and curve segments). Each method accepts optional line and fill colors and may be used to draw an outline or a filled shape. At any time the Canvas has a current font, line width, line color, and fill color. Methods use the defaults unless alternatives are supplied as arguments. Thus drawLine(10,10,20,20) uses the current settings; drawLine(10,10,20,20, width=5, color=silver) does what it says but leaves the current settings unchanged. The drawString method is extremely versatile. It allows angled text (which forced some people to work hard at rotating bitmaps for their platforms, but they managed it), control of color, and printing of blocks of text with embedded new-lines. A stringWidth method allows string widths to be measured, making it feasible to align and wrap text accurately. PIDDLE can use the Python Imaging Library to handle image data; bitmaps in many formats can be loaded, and either placed at their natural size or stretched to fit a desired rectangle. As with all good Python packages, a test framework is provided that runs a group of standard test patterns against the bundled backends. Figure 10-6 shows a standard test pattern. A special canvas called VCRCanvas works as a recorder: when you execute graphics commands, it saves them for replay later. They are saved as text holding executable Python code. This makes it possible for a specialized graphics package to save a chart in a file, and for any other canvas to replay that file in the absence of the original package. Having discussed the base API, we now tackle two key output formats: PostScript and PDF. The PostScript language is the world's most famous page description language. It was developed by Adobe Systems in 1985 as a language for printer drivers and was perhaps the key technology in the desktop publishing revolution. It consists of commands for describing the printed page, including both text and graphics. A text file of these commands is sent to a PostScript printer, which prints them. Post- Script has some features other page description languages lack. For example, a font is a collection of subroutines to draw arbitrary curves and shapes; there's no difference in the way text and graphics are handled. This contrasts with Windows, where you can perform arbitrary scaling and translation of the lines in a chart, while watching all the labels stay right where they are in the same point size.* This section is relevant only if you are aiming at a fairly high-end printer. However, it's worth understanding something about PostScript since it's the base for PDF, which is relevant to everyone. PostScript printers used to be quite specialized; however, as power has increased, more printers are offering PostScript compliance, e.g., the LaserJet 5 series. PostScript printers are the standard for high-volume/high-quality printers. PostScript is generally produced by printer drivers or by graphics packages such as Illustrator, though masochists can do it by hand. PostScript is usually drawn on the printer. However, the public-domain package, GhostView, is available for rendering PostScript files on Windows and other platforms. GhostView lets you print to any printer, doing the best job it can with the local print technology. It also makes it possible to test Python code for generating PostScript without having a dedicated printer on hand. Let's have a quick look at a chunk of PostScript: % Example PostScript file - this is a comment 72 720 moveto 72 72 lineto /Helvetica findfont 24 scalefont setfont 80 720 moveto ('Hello World') show showpage Comments begin with %. Lines 2 and 3 find a font and specify a size. The coordinate system uses 72 points per inch and starts at the bottom left of the screen or page; thus, the commands draw a line one inch from the left of the page, running for most of its height, and the string ''Hello World'' near the top left corner. As you can see, PostScript is fairly readable; it's thus extremely easy to build a Python library to spit out chunks of PostScript. Furthermore, this can be done at very high speed; Python excels at text substitutions. That is what the piddlePS module does; when you make a call such as drawLine (10,10,50,100, width=5), piddlePS does some testing to see what needs changing, then substitutes the numbers into a template string and adds them to an output queue. Here is how it was implemented: def drawLine(self, x1, y1, x2, y2, color=None, width=None): self._updateLineColor(color) self._updateLineWidth(width) if self._currentColor != transparent: self.code.append('%s %s neg moveto %s %s neg lineto stroke' % (x1, y1, x2, y2)) PostScript offers many capabilities beyond the scope of this chapter. Specifically, it's a full-blown language, and you can write subroutines to align text, wrap paragraphs, or even draw charts. Another key ability is coordinate transformations; you can write a routine to draw a shape, then translate, rotate, and scale space to redraw it again elsewhere. The PostScript imaging model has been used or copied in most vector graphic formats since it was developed. PDF is a recent evolution of PostScript. Whereas PostScript was intended to be consumed by printers, PDF is designed for both online viewing and printing. It allows for features such as clickable links, clickable tables of contents, and sounds. It is intended as a final form for documents. You could possibly edit PDF if you had a few months to spare, but it isn't easy. It also remedies some basic problems with PostScript. (PostScript contains arbitrary subroutines that might generate pages in a loop or subject to conditions; so the only way to look at page 499 of a 500-page document, or even to know that there are 500 pages, is to execute the code and render it all.) For the average developer, PDF is compelling because the Acrobat Reader is freely and widely available on almost all platforms. This means you can produce a document that can be emailed, stored on the Web, downloaded, and printed at leisure by your users, on almost any platform. Furthermore, all they get is the document, not any attached spreadsheets or data they shouldn't, and you can be confident it won't be tampered with. For this reason, many companies are looking at PDF as a format for much of their documentation. PDF documents are generally created in two ways, both of which involve buying Adobe Acrobat. This includes PDFWriter, a printer driver that lets you print any document to a PDF file; and Distiller, which turns PostScript files into PDF files. These are excellent tools that fulfill many business needs. PDF is a published specification, and in the last two years, a C library and a Perl library have been written to generate PDF directly. This was too much of a challenge to resist, so we have done one in Python, too. Technically, PDF is a complex language. The specification is 400 pages long. If you don't want to know the details, skip to the section "Putting It Together: A High-Volume Invoicing System." If you do, it'd be a good idea to open one of the sample PDF files provided with this chapter; unlike most you will find on the Web, they are uncompressed and numbered in a sensible order. We've provided a brief roadmap to the PDF format as we feel that it offers many benefits, and you might want to add your own extensions in the future. The outer layer of the PDF format provides overall document structure, specifying pages, fonts used, and advanced features such as tables of contents, special effects, and so on. Each page is a separate object and contains a stream of page-marking operators; basically, highly abbreviated PostScript commands. The snippet of PostScript you saw earlier would end up like this: 72 720 m 72 72 l /F5 24 Tf 42 TL 80 720 Td ('Hello World') Tj Unfortunately this code, which can at least be decoded given time and you know where to look, can be compressed in a binary form and is buried inside an outer layer that's quite complex. The outer layer consists of a series of numbered objects (don't you love that word?) including pages, outlines, clickable links, font resources, and many other elements. These are delimited by the keywords obj and endobj and numbered within the file. Here's a Catalog object, which sits at the top of PDF's object model: 1 0 obj < /Type /Catalog /Pages 3 0 R /Outlines 2 0 R >> Every object is a dictionary of keys and values. The Catalog is at position 1 in the file. It has a Pages collection, found at location 3 in the file. The Pages collection might contain individual Page objects, or perhaps other Pages collections with subranges of the document. These form a balanced tree, so that an application like Acrobat Reader can locate the drawing code for page 3,724 in a 5,000 page document in one second flat. Once you get to a Page object, you'll find a declaration of the resources needed to draw the page, which includes a list of fonts used and might include graphics function sets to load into memory and a reference to a Contents object. A simple page and its associated small Contents object might look like this: 20 0 obj < /Type /Page /Parent 3 0 R /Resources < /Font < /F1 5 0 R % list of font declarations /F2 6 0 R % - font objects are described elsewhere /F3 7 0 R % in the file /F4 8 0 R /F5 9 0 R >> /ProcSet 3 0 R % reference to the sets of PostScript >> % drawing procedures to be loaded for page /MediaBox [0 0 612 792] % page in points - 8.5x11 US paper /Contents 21 0 R % reference to next object >> endobj 21 0 obj % beginning of contents object < /Length 413 >> % predeclare the stream length stream % line 2 units wide from 72, 72 to 72, 720 q 2 w 72 72 m 72 720 l S Q BT % begin text mode /F6 48 Tf 80 672 Td 48 TL % set font, position and size (48 pt) (PDFgen) Tj T* % display a line of text /F5 24 Tf24_TL % smaller font 80 640 Td % set text origin (Automatic PDF Generation) Tj T* % more text ET % end text mode endstream endobj Lurking near the bottom, between the stream and endstream keywords in the Contents object, you finally get to the page-marking operators. Note also that the length of the stream of contents operators is predeclared to allow it to be read quickly. Finally, typically at the end of the document, you find an index section that looks like this: xref 0 24 0000000000 65535 f 0000000017 00000 n 0000000089 00000 n 0000000141 00000 n <lines deleted to save space> 0000005167 00000 n trailer < /Size 24 /Root 1 0 R /Info 19 0 R>> startxref 7164 %%EOF When Acrobat Reader opens a file, it looks in the last few bytes for the keyword trailer. The trailer object on the following line tells us that there are 24 objects in the file; that the root is object number 1; and that information such as the document author and date are available at object number 19. It then tells us that the cross-reference table is found starting at byte 7164 in the file. The cross-reference table itself (beginning at xref in the first line) shows the positions of the objects; thus object 1, the root, is at byte 17 in the file, and object 24 is at byte 5167. This mechanism makes it possible to parse and process PDF documents quickly, but it made developing a PDF generator harder. With HTML or PostScript, you get instant gratification each time you output a well-formed chunk of code, and you can start in a small way; with PDF, you can't even look at it until you have correctly indexed the whole thing. The PDFgen.py module wraps and hides most of this from the user and constructs a well-formed document. Many advanced features are missing, but the documents do open cleanly. The module does this by having Python classes that mirror the PDF ones and by building up a list of objects in memory. When it writes the file, each returns a text representation of itself for the file, and the PDFDocument class measures the length of this. The module is thus able to build a valid index at the end. What it doesn't do is the drawing. The module presumes that something else feeds it a complete contents stream for each page. This is where the PIDDLE interface comes in. We won't go further into the implementation of the outer layer of the PDF library here. Instead we'll look at a few details of the current frontend. Once the PIDDLE API was stable, it was fairly straightforward to implement a PDFCanvas object to provide a simple API. Let's take a quick look at some of the methods of the PDFCanvas class and how they hook up with the backend: def __init__(self, filename): Canvas.__init__(self) self.filename = filename self.code = [] # list of strings to join later self.doc = pdfgen.PDFDocument() self.pageNumber = 1 # keep a count # various settings omitted When it starts up, the PDFCanvas instance creates a PDFDocument instance. This is the class that manages the overall document structure. It also creates an empty list, self.code, to hold strings of page-marking operators. The various drawing methods add the right operators to the list in the same way the PostScript snippets did earlier. If you compare the methods and output with the PostScript PSCanvas, it's easy to see the correspondence. When you ask for a new page with the showPage() method, this happens: def showPage(self): page = pdfgen.PDFPage() stream = string.join([self.preamble] + self.code, '\n') #print stream page.setStream(stream) self.doc.addPage(page) self.pageNumber = self.pageNumber + 1 self.code = [] # ready for more First, create a PDFgen object called PDFPage, which is responsible for generating the output later. Then make a big string of page-marking operators by joining a standard preamble (which does some work to set up coordinate systems, default fonts, and so forth) and the list of accumulated operators. This is stored in the PDFPage, which is then added to the PDFDocument. PDFgen takes care of the rest when asked to save itself to disk. Finally, the page number is incremented, and the list of strings is emptied, ready for some more output. Rather than repeating the management accounts we did in Word, we'll discuss a different situation. Imagine that Pythonics is now doing a large volume of consulting work and needs to bill customers by the hour on a weekly basis. An internal database keeps track of who works for how many hours on which project. At the end of each week, we need to raise correct invoices and simultaneously enter them into our accounts system. Although starting small, we'd like a system that will scale up in the future. We've built a tab-delimited text file called invoicing.dat that contains a list of the fields for each invoice; basically, the customer details, date, invoice number, number of hours worked, hourly rate, and so on. In a real application, this data might come from database queries, flat files, or already be available as an object model in memory. The script to generate the invoices is 200 lines long and is mostly graphics code; we'll show some excerpts. First, the main loop: def run() import os invoices = acquireData() # parse the data file print 'loaded data' for invoice in invoices: printInvoice(invoice) print 'Done' We'll skip the data acquisition. Note also that in a real financial application, you'd extract transaction objects from your invoice objects and save them in a BookSet at the point of printing. For each invoice, construct a PDFCanvas, call various drawing subroutines, and save it with an appropriate filename. In this case, the filename encodes the invoice number and client name: def printInvoice(inv): #first see what to call it filename = 'INVOICE_%d_%s.PDF' % (inv.InvoiceID, inv.ClientID) canv = pdfcanvas.PDFCanvas(filename) #make up the standard fonts we need and attach to the canvas canv.standardFont = pdfcanvas.Font(face='Helvetica',size=12) canv.boldFont = pdfcanvas.Font(face='Helvetica',bold=1, size=12) #now all the static repeated elements drawHeader(canv, filename) drawOwnAddress(canv) # now all the data elements drawGrid(canv, inv) drawCustomerAddress(canv, inv) drawInvoiceDetails(canv, inv) #save canv.flush() Here's one of the drawing functions, drawOwnAddress(). It's passed the canvas to draw on and the invoice; it does what you'd expect: def drawOwnAddress(canv): address = ['Village Business Centre', 'Thornton Hill', 'Wimbledon Village', 'London SW19 8PY', 'Tel +44-181-123-4567'] fnt = Font(face='Helvetica',size=12,italic=1) canv.drawStrings(address, INCH, INCH * 1.5, fnt) Other methods draw tables, format the numbers, and output them in the right places using methods of the PDFCanvas. Users don't need to worry about the details of the file format. In practice, you'd use a standard script handler so that the script could be run with a double-click. Here it's run interactively. Running the script generates one file for each customer, at a rate of several files per second: >>> invoicing.run() loaded data saved INVOICE_199904001_MEGAWAD.PDF saved INVOICE_199904002_MEGAWAD.PDF saved INVOICE_199904003_MEGAWAD.PDF saved INVOICE_199904004_NOSHCO.PDF Done >>> Figure 10-7 shows the output. Now, let's look at the benefits of this architecture from a business perspective: The report took only about two hours to assemble, including data acquisition. You have a simple script that can be run with a double-click or scheduled to go off at night: no need to launch applications manually. The output is filed with the correct names in an immutable format. If a dispute or problem arises in the future, you can instantly find the file and see exactly what was sent. The entries have been made in the accounts system at the same time. It's easy to add further steps to the logic, such as emailing invoices to suppliers. The system is fast and light; it runs well with tens of thousands of pages and can be moved from a desktop PC to a Unix server with no modifications. It's easy to customize. You don't need a lot of Python, and there is a simple drawing API. Power users could learn to customize it or write their own reports easily. Data can be acquired from anything with Python: files, databases, spread-sheets, or other Python applications. You aren't tied to a database engine. There are several more techniques and improvements we haven't added, but that could be easily accomplished if the need arose. This is Open Source, so if they sound useful, they probably will be done by somebody by the time you read this. Object-oriented graphics and page layout API The PIDDLE team is working on the "next layer up," which will hopefully be available by the time this book is printed. This consists of two ideas. First of all, frames identify regions on the page into which drawing may take place; users may specify one main frame per page, or as many as they wish. Second, we create a hierarchy of drawable objects, allowing a high level of reuse. These objects know their size and can wrap themselves to fit a frame if needed. They can be "poured into" a frame until it fills. A Table object might be initialized with an array of data and draw default table cells by itself; named styles allow quick and easy formatting of large tables. A Paragraph object, again tied to a list of styles, allows rapid formatting of text. Individual PIDDLE drawings can also constitute drawable objects and define their own coordinate systems for their contents. Volume optimizations The example script runs at about four pages per second, a lot faster than any printer, but nowhere near the speed limit. A large amount of processing is going into generating a text stream, which is almost the same for each page. You can generate the page once and substitute variables using Python's dictionary-substitution facility. This lets you generate documents as fast as the disk can write; however, it's applicable only for simple one-record-per-page forms. PDF provides a similar trick: you can create something called a PDF form, which is a content stream that can be reused within a document. The reusable parts of the page can be placed in a form and stored once, and only the numbers and text that change need to print. This reduces the size of a huge invoice print run by 90% or more and leads to faster printing on the right printers. Imported graphics A large number of graphics packages work with PostScript. You can design pages or graphic elements in a tool such as Adobe Illustrator. These elements can be distilled and the PDF page-marking operators lifted out into a library, with some parsing tools that would be straightforward to write in Python. This library combines the freedom of visual design tools with the discipline and speed of report programs. Onscreen views The testing cycle was pretty fastrun a script, load the document to Acrobat in less than two seconds. However, the PIDDLE API is not platform-specific. You can use it to provide a printing engine for graphical applications; the same code that drew charts on the screen using a Windows or Tkinter backend generates a PDF report for free. Plotting As discussed earlier, a key motivation for PIDDLE was to create plotting libraries that were not tied to one backend. The Graphite package () was developed alongside PIDDLE and is already capable of a wide range of plot types. Given Python's strong presence in the scientific world, we expect exciting developments here. Figure 10-8 is a sample from Graphite. Web and print versions One key application area is on the Web. Python web applications can produce both bitmaps and print-ready documents on the fly from a web server. Python supports many possible solutions for printing. We have looked at three: automating Word, using Windows graphics calls from PythonWin, and directly generating PDF documents. The recent evolution of a standard graphics API for Python with a variety of backends should provide more output formats in the future. The PDFgen/PIDDLE solution is lightweight (under 50 KB of code and font data), multiplatform, and scalable to large print runs; it follows the architecture of many high-volume corporate reporting systems, but with a much nicer language. Returning to Doubletalk, our users already had an extensible application that allowed them to create their own views of the data. They are now in a position to create their own reports easily with no limits on graphical capabilitieswhether as a back office job in itself, from another application, or on the Weband to store electronic copies where they want. Writing Word Macros by Steven Roman (O'Reilly) shows how to use VBA to automate many tasks in Word. Word 97 Annoyances by Leonhard, Hudspeth, and Lee (O'Reilly) is a great guide to how Word works and how to live with it. The Adobe PDF Specification (Version 1.3) is available from (5.5MB, 518 pages). PIDDLE can be found at. Graphite is at. The PDFgen package (also available in the PIDDLE distribution) is found at.
https://flylib.com/books/en/1.116.1.15/1/
CC-MAIN-2018-26
refinedweb
9,678
62.17
_ArrayInsert problem By nill, in AutoIt General Help and Support Recommended Posts Similar Content - By Burgs Greetings,. - By Jibberish Hello I am trying to insert or replace data in an existing 2D array. _ArrayInsert seems to always add a row when inserting the data to the specified column. This code is from the _ArrayInsert Function Reference, with only the modified sample I think I want to use... #include <Array.au3> Local $aArray_Base[10][3] For $i = 0 To 9 For $j = 0 To 2 $aArray_Base[$i][$j] = $i & " - " & $j Next Next _ArrayDisplay($aArray_Base, "2D - Original") ; Insert single item in defined column $aArray = $aArray_Base _ArrayInsert($aArray, 0, "True", 2) ; <- I want to add this data to Row 0, Column 3 but retain the data in Columns_ and 1. _ArrayDisplay($aArray, "2D - Defined column") If you run the above code you will see it adds a new row and inserts "True" into column 3. How can I do this without adding a row? -
https://www.autoitscript.com/forum/topic/188728-_arrayinsert-problem/
CC-MAIN-2019-13
refinedweb
161
57.71
Created on 2017-10-05 08:35 by srittau, last changed 2017-11-02 23:55 by srittau. This issue is now closed. Currently typing.Generator requires three arguments: Generator[YieldType, SendType, ReturnType]. At least for me, passing values to a generator is a very rare case. I suggest to allow only one argument to be passed to Generator: Generator[YieldType], where the other arguments default to None. This makes the common case more readable and is less error-prone. (I always forget the second and third argument, since that use case is so uncommon for me.) You can use Iterator type, for example this works in mypy (didn't test in other type checkers): def f() -> Iterator[int]: yield 42 In case you want annotate something specifically as Generator[int, None, None] (for example to use its .close() method), then you can create a generic alias: T = TypeVar('T') Gen = Generator[T, None, None] def f() -> Gen[int]: ... this is supported by mypy as well. Since there is no response for few weeks I assume this works for you. Sorry for not responding, but I didn't know what I could have added that I didn't already say in the opening post. Of course, you can use workaround like using the three-argument version or creating aliases. Using Iterator is of course not a real solution for the general case. I still believe that Generator should be usable with just one argument or typing should provide such an alias.
https://bugs.python.org/issue31700
CC-MAIN-2017-51
refinedweb
251
64.2
Using Celery on Heroku Last updated February 02, 2021 Table of Contents Using Celery on Heroku Celery is a framework for performing asynchronous tasks in your application. Celery is written in Python and makes it very easy to offload work out of the synchronous request lifecycle of a web app onto a pool of task workers to perform jobs asynchronously. Celery is fully supported on Heroku and just requires using one of our add-on providers to implement the message broker and result store. Architecture You deploy Celery by running one or more worker processes. These processes connect to the message broker and listen for job requests. The message broker distributes job requests at random to all listening workers. To originate a job request, you invoke code in the Celery library which takes care of marshaling arguments to the job and publishing the job request to the broker. You can flexibly scale your worker pool by simply running more worker processes which connect to the broker. Each worker can execute jobs in parallel with every other worker. Choosing a broker Heroku supports lots of great choices for your Celery broker via add-ons provided by our partner companies. Generally speaking, the broker engines with the best support within Celery include Redis and RabbitMQ. Others including Amazon SQS, IronMQ, MongoDB, and CouchDB are also supported, though some features may be missing when using these brokers. The way Celery abstracts away the specifics of broker implementations make changing brokers relatively easy, so if at some later point you decide a different broker better suits your needs, feel free to switch. Once you’ve chosen a broker, create your Heroku app and attach the add-on to it. In the examples we’ll use Heroku Redis as the Redis provider but there are plenty of other Redis providers in the Heroku Elements Marketplace. $ heroku apps:create $ heroku addons:create heroku-redis -a sushi Celery ships with a library to talk to RabbitMQ, but for any other broker, you’ll need to install its library. For example, when using Redis: $ pip install redis Choosing a result store If you need Celery to be able to store the results of tasks, you’ll need to choose a result store. If not, skip to the next section. Characteristics that make a good message broker do not necessarily make a good result store! For instance, while RabbitMQ is the best supported message broker, it should never be used as a result store since it will drop results after being asked for them once. Both Redis and Memcache are good candidates for result stores. If you choose the same result store as message broker, you do not need to attach 2 add-ons. If not, make sure the result store add-on is attached. Creating a Celery app First, make sure Celery itself is installed: $ pip install celery Then create a Python module for your celery app. For small celery apps, it’s common to put everything together in a module named tasks.py: import celery app = celery.Celery('example') Defining tasks Now that you have a Celery app, you need to tell the app what it can do. The basic unit of code in Celery is the task. This is just a Python function that you register with Celery so that it can be invoked asynchronously. Celery has various decorators which define tasks, and a couple of method calls for invoking those tasks. Add a simple task to your tasks.py module: @app.task def add(x, y): return x + y You’ve now created your first Celery task! But before it can be run by a worker, a bit of configuration must be done. Configuring a Celery app Celery has many configuration options, but to get up and running you only need to worry about a couple: BROKER_URL: The URL that tells Celery how to connect to the message broker. (This will commonly be supplied by the add-on chosen to be the broker.) CELERY_RESULT_BACKEND: A URL in the same format as BROKER_URLthat tells Celery how to connect to the result store. (Ignore this setting if you choose not to store results.) Heroku add-ons provide your application with environment variables which can be passed to your Celery app. For example: import os app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) Your Celery app now knows to use your chosen broker and result store for all of the tasks you define in it. Running locally Before running celery workers locally, you’ll need to install the applications you’ve chosen for your message broker and result store. Once installed, ensure both are up and running. Then create a Procfile which Heroku Local can use to launch a worker process. Your Procfile should look something like: worker: celery worker --app=tasks.app Now add a file named .env to tell Heroku Local which environment variables to set. For example, if using Redis with its default configuration for both the message broker and result store, simply add an environment variable with the same name as the one provided by the add-on: REDIS_URL=redis:// To start your worker process, run Heroku Local: $ heroku local Then, in a Python shell, run: import tasks tasks.add.delay(1, 2) delay tells Celery that you want to run the task asynchronously rather than in the current process. You should see the worker process log that it has received and executed the task. Deploying on Heroku If you already created a Procfile above and attached the appropriate add-ons for the message broker and result store, all that’s left to do is push and scale your app: $ git push heroku master $ heroku ps:scale worker=1 Of course, at any time you can scale to any number of worker dynos. Now run a task just like you did locally: $ heroku run python >>> import tasks >>> tasks.add.delay(1, 2) You should see the task running in the application logs: $ heroku logs -t -p worker Celery and Django The Celery documentation provides a good overview of how to integrate Celery with Django. Though the concepts are the same, Django’s reusable app architecture lends itself well to a module of tasks per Django app. You may want to leverage the INSTALLED_APPS setting in concert with Celery’s ability to autodiscover tasks: from django.conf import settings app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Celery will then look for a tasks.py file in each of your Django apps and add all tasks found to its registry. Celery best practices Managing asynchronous work Celery tasks run asynchronously, which means that the Celery function call in the calling process returns immediately after the message request to perform the task is sent to the broker. There are two ways to get results back from your tasks. One way is just to write the results of the task into some persistent storage like your database. The other way to get results back from a Celery task is to use the result store. The Celery result store is optional. Oftentimes it is sufficient to issue tasks and let them run asynchronously and store their results to the database. In that case you can safely ignore the result as saved by Celery. Choosing a serializer Everything that gets passed into a Celery task and everything that comes out as a result must be serialized and deserialized. Serialization brings with it a set of problems that are good to keep in mind as you design your Celery tasks. By default, Celery chooses to use pickle to serialize messages. Pickle has the benefit of “just working” out of the box, but it can cause many problems down the road. When code changes, in-flight serialized objects can cause problems when deserialized, still in their old form. Changing Celery to use JSON not only forces developers into good practices for task arguments; it also reduces the security risk that pickle’s arbitrary code execution can pose. To use JSON as the default task serializer, set an environment variable: CELERY_TASK_SERIALIZER=json Small, short-lived tasks In a celery worker pool, multiple workers will be working on any number of tasks concurrently. Because of this, it makes sense to think about task design much like that of multithreaded applications. Each task should do the smallest useful amount of work possible so that the work can be distributed as efficiently as possible. Because of the overhead involved in serializing a task, sending it over the network to the message broker, sending it back over the network to the worker, and deserializing the task is much higher than sending an message on an intra-process queue between threads, the bar for “useful” is of course higher as well. Issuing a task that does nothing but write a single row to a database is probably not the best use of resources. Making 1 API call rather than several in the same task, though, can make a big difference. Short-lived tasks make deploys and restarts easier. When stopping a dyno, Heroku will kill processes a short amount of time after asking them to stop. This could happen as a result of a restart, scale down, or deploy. As a result, tasks which finish quickly will fail less often than long running ones. Set task timeouts When running a task hundreds or thousands of times, occasionally a task can get stuck due to network activity and block your queue from handling more tasks. This can be easily be avoided by setting hard and soft timeouts for all of your tasks. You can read more about timeouts in the Celery documentation. Idempotent tasks Celery tasks can fail or be interrupted for a variety of reasons. Rather than trying to anticipate everything that could possibly go wrong in a distributed system, you should strive for idempotence when designing tasks. Try never to assume the current state of the system when a task begins. Change as little external state as possible. This is more of an art than a science, but the more tasks are re-runable without negative side-effects, the easier distributed systems can self-heal. For example, when an unexpected error occurs, idempotent tasks can simply tell Celery to retry the task. If the error was transient, idempotence allows the system to self-heal without human intervention. Using REMAP_SIGTERM When a running process on Heroku is terminated, it is sent a SIGTERM signal 10 seconds before it will be shut down. Starting in version >= 4, Celery comes with a special feature, just for Heroku, that supports this functionality out of the box: $ REMAP_SIGTERM=SIGQUIT celery -A proj worker -l info Using acks_late When celery workers receive a task from the message broker, they send an acknowledgement back. Brokers usually react to an ack by removing the task from their queue. However, if a worker dies in the middle of a task and has already acknowledged it, the task may not get run again. Celery tries to mitigate this risk by sending unfinished tasks back to the broker on a soft shutdown, but sometimes it’s unable due to a network failure, total hardware failure, or any number of other scenarios. Celery can be configured to only ack tasks after they have completed (succeeded or failed). This feature is extremely useful when losing the occasional task is not tolerable. However, it requires the task to be idempotent (the previous attempt may have progressed part of the way through) and short-lived (brokers will generally “reserve” a task for a fixed period of time before reintroducing it to the queue). Acks_late can be enabled task by task or globally for the Celery app. Custom task classes Even though a task may look like a function, Celery’s task decorator is actually returning a class which implements __call__. (This is why tasks can be bound to self and have other methods available to them like delay and apply_async.) The decorator is a great shortcut, but sometimes a group of tasks share common concerns which can’t be easily expressed purely functionally. By creating an abstract subclass of celery.Task, you can build a suite of tools and behaviors needed by other tasks using inheritance. Common uses for task subclasses are rate limiting and retry behavior, setup or teardown work, or even a common group of configuration settings shared by only a subset of an app’s tasks. Canvas primitives Celery’s documentation outlines a set of primitives which can be used to combine tasks into larger workflows. Familiarize yourself with these primitives. They provide ways to accomplish significant and complex work without sacrificing the design principles outlined above. Particularly useful is the chord, in which a group of tasks are executed in parallel and their results passed to another task upon completion. These, of course, require a result store.
https://devcenter.heroku.com/articles/celery-heroku
CC-MAIN-2021-10
refinedweb
2,150
60.95
View Complete Post Hell all, I have the Index action method calling a method that itself is an action method. Example : public ActionResult Index() { //do stuff ActionResult result = MethodB(); // ?? what to return here ?? } public ActionResult MethodB() { //do stuff return View("Index); } how can i return 401 error from a method return ActionResult?, I created an MVC 2 action which is supposed to return JSON. When i verified the output in jsonlint.com, the result was 'invalid JSON' The code used was; [HttpGet] public ActionResult MarketList() { var mkt = db.GetDailyList(); return Json(mkt, JsonRequestBehavior.AllowGet); } Is this correct? I also noticed that when i pasted the raw JSON feed from the URL into the jsonlint.com textbox, it was valid. What could be going on here? Thanks Hello...i have a e-commerce page which send data to last page for the payment... In this last page, the user confirm his intention to acquire products .... In this moment, i've created a sub which insert a new order in the database...all works!... The problem born when i try (and user could too) to manually refresh the page...the code will be processed again and a new (second) order will be inserted in the database.....it's not correct... This page make a postback after confirm button....so control page.ispostback will not resolve problem... How could i intercept manual refresh of this page in a secure way ? Thanks to all Anyone,). I have an iFilter for a memory map type piece of software. The iFilter works in 64-bit versions of Windows 7 and I was hoping to get it working with SharePoint. The iFilter consists of a dll that is registered with regsvr32 manually and another helper dll (not sure what this does exactly). I registered the dll on the windows server machine (single machine with server 2008R2 and SharePoint server 2010). I followed the same steps that are used to install the pdf iFilter - I put in a registry key for the file extension at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension\ and gave it's default value the CLSID of the iFilter. (If you've read the guides for sharepoint 2010 and pdf ifilter hopefully you understand this) This doesn't work. The pdf iFilter works, and when I do a crawl of the sharepoint sites I can see that the adobe ifilter DLLs are being used. My mind map dll filter dll is not being used. Has anyone got any guidance on custom iFilters with SharePoint 2010?, Hi All, I have an ActionResult method that displays records from a database table (below): namespace STD.Controllers { public class StudentController: Controller { StudentEntities stud; public StudentController() { stud= new StudentEntities (); } public ActionResult Index() { ViewData.Model = stud.StudentTable.ToList(); return View(); } } I want to design a method "ActionResult Student()" that accepts "Student ID" as a parameter and displays record for that particular student only. What do I need to do to make this happen? Could anyone please help me with this? Thanks in advance Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/14836-intercept-actionresult-specifically-when.aspx
CC-MAIN-2016-44
refinedweb
523
67.15
Hello, I am working with various log files, and I will be using the log file to extract certain criteria based on some condition. However, I need a program that will save a text file by today's date. Is there an easy way to accomplish this...maybe by calling a library? Below is just an example of outputting to a text file by manually putting today's date, however, I would rather automate that. Any insight/recommendations would be great. Thanks! Code:#include <iostream> #include <fstream> using namespace std; int main () { ofstream outF; outF.open ("20070709.txt"); outF << "Output Text Junk Here..."; outF.close(); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/91591-output-text-file-name-todays-date.html
CC-MAIN-2013-20
refinedweb
107
68.77
Today we’re going to learn how to package up small chunks of code for reuse using functions. Goal for this Tutorial: - Create our first function to execute code multiple times. range. In most of our programming, we won’t be working with a script that we’re going to run from top to bottom. Most of our time is going to be spent grouping code together in a way that makes sense to use and then combining the piece that we build up in order to create our final product. The simplest way we can package up our code is by using a function. Python Functions are Pretty Awesome Functions are the building block that virtually every programming language has in common, and are even the most important building block in some languages. Python functions aren’t the most important, but they are very powerful. I like to think of functions in programming in the way that you might learn about functions in mathematics. Let’s break down a math function and turn it into a Python function: f(x) = x + 1 Our function has the name of f and it requires a single variable x. We will define this function in Python using the def keyword: def f(x): We follow our function name and arguments with a : and then we will indent the actual logic of the function by 4 spaces. After the body of the function we’ll insert a blank line which will end the function. def f(x): x + 1 We’ve defined our function, now let’s take it for a spin: >>> f(1) >>> That’s not quite right. In our math function if we use 1 for x then the answer should be 2, but we didn’t get anything. Our function works this way because unlike mathematical functions which always produce an output, Python functions can take an action and then return nothing to us. To make this work like the math function we need to use the keyword return. def f(x): return x + 1 If we try to run the function again, we should get 2 back: >>> f(1) 2 >>> Beyond Math… Onto Fizz Buzz Figuring out how to represent a math function in Python is one thing, but that really doesn’t event scratch the surface of Python functions. Functions are not restricted to being a single line, so we can package up a series of expressions to execute. We’ll demonstrate this using a problem from programming interviews called “fizz buzz”. For “fizz buzz” we’re going to take a number and print from 1 to that number and for each number we will print one of the following: - “Fizz” if the number is divisible by 3 - “Buzz” if the number if divisible by 5 - “Fizz Buzz” if the number is divisible by 3 and 5 - The number itself if not divisible by 3 or 5 Here’s an example of one way we could write this function: def fizz_buzz(limit): for num in range(1, limit): output = "" if num % 3 == 0: output += "Fizz " if num % 5 == 0: output += "Buzz" print(output or num) This function combines loops, conditionals, strings, conditionals, printing, and even throws in something new: range. A range is a sequence of numbers, in our case it’s from 1 to whatever the passed in limit is, excluding the limit itself. Ranges are great for when you want to iterate through something a specific number of times or in our case where we want to do something with each number, but we don’t want to create a list ourselves. This is a fairly complex function, and now we can run it over whatever limit we want, as many times as we want. >>> fizz_buzz(17) 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz 16 >>> Fizz Buzz, but Better Our original example was a good example of creating a more complex function body, but there is more that we can do in the function declaration that can make it even better. For instance we can give limit a default (we’re going to call this fizz_buzz2 to keep them separate): def fizz_buzz2(limit=20): for num in range(1, limit): output = "" if num % 3 == 0: output += "Fizz " if num % 5 == 0: output += "Buzz" print(output or num) Now if we call fizz_buzz2 without any arguments it will automatically use 20 as the value for limit. Pretty neat! Let’s take this even one step forward and make the “fizz” and “buzz” messages configurable (this is fizz_buzz3): def fizz_buzz3(limit, fizz="Fizz", buzz="Buzz"): for num in range(1, limit): output = "" if num % 3 == 0: output += fizz + " " if num % 5 == 0: output += buzz print(output or num) This version of fizz buzz is the best we’re going to create. We’re now using multiple arguments, some with defaults and some without. Let’s look at some of the ways we can call this function: >>> fizz_buzz3(7, "Red", "Blue") 1 2 Red 4 Blue Red >>> fizz_buzz3(7, buzz="Boom!") 1 2 Fizz 4 Boom! Fizz In our first example we used all positional arguments, meaning the order we passed them in would be interpreted as the order we defined them. The second time we ran it though, we used what’s known as a keyword argument. We let fizz take its default value, but we explicitly set buzz to be Boom! Recap We’re finally getting into the more exciting parts of programming. Before today, most of what we’ve learned about were the small building blocks that we’ll use to build up an individual line of code, but with functions we’re learning the tools we need to write more complex programs. From here, there are only a few more broad topics that we’ll need to cover before we can start digging into the problem solving of programming.
https://coderjourney.com/getting-started-python-functions/
CC-MAIN-2021-25
refinedweb
993
60.18
In the Paint method of a JFrame I can call a method like drawRect( ) and it will work. But when I try to call a class method for drawing, it won't work. It creates the window but doesn't draw anything in it. Here is a simple example. It uses a class, Design, that just uses drawRect and drawOval. An applet can use the Design class and its methods just fine. Why can't the JFrame do the same? import java.awt.*; import javax.swing.*; public class DrawTest extends JFrame { Design d; public DrawTest( ) { super( "Drawing Test" ); setSize(100, 100 ); setVisible( true ); } public void init( ) { d = new Design( ); } public void paint( Graphics g ) { super.paint( g ); d.draw( g ); } public static void main( String args[] ) { DrawTest application = new DrawTest( ); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end of main } // end of DrawTest
http://www.codingforums.com/java-and-jsp/117805-drawing-jframe.html
CC-MAIN-2016-30
refinedweb
140
76.42
Archive your AWS data to reduce storage cost07 Aug 2020 AWS offers a variety of general purpose storage solutions. While DynamoDB is the best option when latency and a variety of access patterns matter most, S3 allows for cost reduction when access patterns are less complex and latency is less critical. This article describes the available options for archiving data, how to prepare that data for long term archival and how to let S3 transition data between storage tiers. Below you find a table comparing the prices and access latencies as of August 2020. All prices are for us-east-1. This article focuses on storage cost only. Prerequisites You should have an AWS account and gained first experience with DynamoDB or S3. The code snippets are written in Python and are intended to run on AWS Lambda. Moving Data As you’ve seen in the previous table, you can achieve significant storage cost reduction, by moving your data to a cheaper storage solution. There are 3 major paths when archiving data: - DynamoDB to S3 - S3 Storage Tiers - Final Archival with S3 Glacier The first path requires a lambda function, and the others can be achieved without additional glue code. We will however look at data aggregation for small objects, as infrequent access solutions are less suitable for small objects. DynamoDB to S3 When to move data from DynamoDB to S3 Moving data out of DynamoDB makes sense when that data is becoming stale, but remains interesting for future use cases. An example for this are performance metrics. We’re most interested in the recent weeks, but don’t look at data from months ago too much. We still want to keep those around for later analysis or troubleshooting. How to move data from DynamoDB to S3 To move data from DynamoDB to S3, we can use DynamoDB’s Time to Live (ttl) feature in combination with event streams. This approach requires four steps: - Specifying a ttl attribute on a DynamoDB table - Adding a timestamp to records which shall expire - Activating a stream that DynamoDB will emit deleted records to - Attaching a lambda to this stream, which checks for DELETEevents and writes the records into an S3 bucket The first three steps are covered in my article How to analyse and aggregate data from DynamoDB. The lambda function to transition records to S3 can be as short as the following snippet: from datetime import datetime import boto3 s3 = boto3.resource('s3') def handler(event, context): for record in event.get('Records', []): if record['eventName'] != 'DELETE': return payload = record['dynamodb']['NewImage'] # this assumes that there is a partition key called Id # which is a number, and that there is no sort key key = record['dynamodb']['Keys']['Id']['N'] date = datetime.now().isoformat() object_key = f"data-from-dynamodb/{date}/{key}" body = json.dumps(payload).encode() s3.Object('my_bucket', object_key).put(Body=body) This will store deleted records in the S3 bucket my_bucket. No data is lost, the DynamoDB table stays small and you get an instant 90% cost reduction on storage. S3 Storage Tiers If your data is accessed infrequently you can achieve further cost savings by picking the right storage tier. S3 Lifecycle Transitions allow us to move objects between storage tiers without them leaving the S3 bucket. We define rules where we specify which storage tier an object shall be moved to once it reaches a certain age. You can read all about the S3 lifecycle transitions on the official AWS documentation. When to move data between S3 tiers S3 Standard gives you the most reliability and fastest access speed. If you’re okay with 99.9% availability or you only access your data rarely (e.g. for regulatory checks), then the non-standard tiers can give you a cost advantage. The durability of your data is not affected (unless you pick the One-AZ tier). You also should aggregate data before moving it to a storage tier other than S3 Standard or S3 Intelligent-Tiering, as there is a minimum capacity charge per object. As a rule of thumb, aggregate your objects until the result is at least 1MB. How to move data between S3 tiers Due to the minimum capacity charge we will start by aggregating data. If all of your objects in S3 are already 1MB or more, then you can skip directly to the lifecycle rules. To aggregate objects we can use any compute service (EC2, Fargate, Lambda) to load objects from S3, aggregate them and write the aggregated data back. import simplejson as json import boto3 s3 = boto.client('s3') one_mb = 1024 * 1024 bucket = 'my_bucket' date_prefix = 'data-from-dynamodb/2020-07' print("Downloading data") objects = [] files_response = s3.list_objects(Bucket=bucket, Prefix=date_prefix) for obj_info in files_response.get('Contents', []): key = obj_info['Key'] obj = s3.Object(bucket, key).get() data = json.loads(obj['Body'].read().decode('utf-8')) objects.append({'key': key, 'data': data}) print("Aggregating data") aggregated_objects = [] size = 0 aggregator = {} for obj in objects: aggregator[obj['key']] = obj['data'] size += len(obj['data']) if size > one_mb: body = json.dumps(obj['data']).encode() s3.put_object(Body=body, Bucket=bucket, Key=f"aggregated/{date}") size = 0 aggregator = {} body = json.dumps(obj['data']).encode() s3.put_object(Body=body, Bucket=bucket, Key=f"aggregated/{date}") print("Deleting data") for obj_info in s3.list_objects(Bucket=bucket, Prefix=date_prefix).get('Contents', []): s3.delete_object(Bucket=bucket, Key=obj_info['Key']) print("Done") This code snippet uses boto3 and loads all records from the folder data-from-dynamodb/2020-07, aggregates them, deletes the old data and uploads the new data into the folder aggregated. Now that we’ve packaged our objects, let’s continue with lifecycle transitions. S3 can be configured to automatically move objects between storage tiers. In this article we will configure the lifecycle transitions through the AWS console. You can also use the CDK’s LifecycleRules and Transitions to build an Infrastructure as Code solution. To get started, open your S3 bucket in the AWS console and open the Management tab. Click on “Add lifecycle rule” to configure a lifecycle. By applying the lifecycle rule to the folder aggregated, we only transition data which has been packaged for archival. Specify a Transition to Standard-IA (Infrequent Access) after 30 days. We’re assuming here that data will be archived and therefore infrequently accessed, but you can increase this number however you like or pick another storage tier. Review and complete the lifecycle rule. After 30 days you should start see in your bill that some objects are now priced at a less expensive storage tier. If you picked S3 Infrequent Access, that’s another 45% you save for storage. Data on Ice with S3 Glacier While we’re only looking at Glacier here, you can apply the same principles for moving data to Intellingent-Tiering, One Zone-IA and Glacier Deep Archive. When to move data to Glacier S3 Glacier and S3 Glacier Deep Archive become interesting options, when you need to store data for a very long time (+5 years) and only access it very rarely (1-2 a year or less). How to move data to Glacier As we’ve previously aggregated our data, we can add additional lifecycle transitions to move the data from S3 Infrequent Access to S3 Glacier. Instead of the Infrequent Access tier, now pick a Glacier option and adjust the time before transition accordingly. That’s it. Your data is now on ice and we get an additional 68% cost reduction on storage. How to retrieve data from Glacier To access data that is stored in Glacier, you have to restore a copy of the object. The copy will be available for as long as you specified. The retrieval however can take up to 12 hours. Next Steps Do you have big DynamoDB tables? Figure out what data you can archive, and start moving it to S3 for a 90% cost reduction! Do you already have data in S3? Add a lifecycle transition to a lower tier and aggregate objects if needed. Further Reading - Pricing Pages for DynamoDB and S3 - Use Kinesis to move data from DynamoDB to S3 - A tool to concat files in S3, might be helpful to optimize aggregation - Use S3’s multipart upload to aggregate objects Enjoyed this article? I publish a new article every month. Connect with me on Twitter and sign up for new articles to your inbox!
https://bahr.dev/2020/08/07/archiving-data/
CC-MAIN-2020-50
refinedweb
1,400
53.92
Hello, I am making a site in React and when I click on a link, it goes to the right page that I coded but that page is scrolled on various places, it’s not on the top. Does anyone know how to fix this? Hello, Are you using react-router-dom? Well, I don’t understand what do you mean “scrolled on various places” DId you use? <Router exact path="/" component={myComponent}/> <Route path="/shop" exact component={Shop} /> I meant that when I go to a certain page, it is already scrolled up to a some point (end of the page actually), it’s doesn’t show the top of the page first but some point on it Well, there could be a possibility on your code. Can you show us the code? No one can help you if you don’t give the code for us to read. Main component: function App() { return ( <div> <Router> <DataProvider> <Header /> <Switch> <Route path="/" exact component={Main} /> <Route path="/product/:id" exact component={SingleItem} /> <Route path="/shop" exact component={Shop} /> </Switch> <Footer /> </DataProvider> </Router> </div> ); } Shop component: function Shop() { return ( <div className="main"> <DataProvider> <Item /> </DataProvider> </div> ); } Well, you only have one HTML page. So when you load more content in, you’re not going anywhere, it’s never a new HTML page, so you’re never going to get the default behaviour you get from a website with different HTML pages. There are multiple solutions to this, one is in the documentation here: React Router: Declarative Routing for React.js This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.
https://forum.freecodecamp.org/t/react-router-issue/455395
CC-MAIN-2022-27
refinedweb
276
66.78
CircuitPython comes 'with the kitchen sink' - a lot of the things you know and love about classic Python 3 (sometimes called CPython) already work. There are a few things that don't but we'll try to keep this list updated as we add more capabilities! All the usual if, elif, else, for, while work just as expected. import math will give you a range of handy mathematical functions. >>> dir(math) ['__name__', 'e', 'pi', 'sqrt', 'pow', 'exp', 'log', 'cos', 'sin', 'tan', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'copysign', 'fabs', 'floor', 'fmod', 'frexp', 'ldexp', 'modf', 'isfinite', 'isinf', 'isnan', 'trunc', 'radians', 'degrees'] CircuitPython supports 30-bit wide floating point values so you can use int and float whenever you expect. You can organize data in (), [], and {} including strings, objects, floats, etc. We use objects and functions extensively in our libraries so check out one of our many examples like this MCP9808 library for class examples. Yep! You can create function-functions with lambda just the way you like em: >>> g = lambda x: x**2 >>> g(8) 64 To obtain random numbers: import random random.random() will give a floating point number from 0 to 1.0. random.randint(min, max) will give you an integer number between min and max.
https://learn.adafruit.com/adafruit-feather-m4-express-atsamd51/circuitpython-built-ins
CC-MAIN-2019-43
refinedweb
207
68.5
Over the last several months, we shave been assembling a library of window-oriented tools to be used in the development of a communications program. Last month's column featured a text editor engine that allows you to collect user-entered, free-form text into a buffer through a window. This month we will surround that engine with a menu structure and add file-management and text-searching functions. First, though, we must complete the collection of window tools by adding the context-sensitive help feature. Most PC programs offer some type of on-line help to the user. This help usually takes the form of text windows that pop up and explain something the user needs to know. When the text automatically reflects the user's current position in the program, the help text is said to be "context-sensitive." The context-sensitive help feature for our C Programming project is implemented in two source files. These are Listing One, help.h, on page112, and Listing Two, help.c, on page 112. The code from previous months has included constructs to support the help functions. The data entry and menu functions in October provide for the identification of help windows to explain each menu selection and data entry field. The structures found in entry. h and menu.h already have places for the window mnemonics, and the getkeyfunction (window.c, September DDJ already watches for a help hot key and calls a help function. Help windows are described in an ASCII text file. Each window has a mnemonic and text. The mnemonic is from 1 to 8 characters, and the text can be up to 78 characters wide and 23 lines deep. Each mnemonic is surrounded by angle brackets, appears at the beginning of a line, and is the only entry. on the line. The text for a window follows its mnemonic and is terminated by the appearance of the next window mnemonic or the <end> file-terminating mnemonic. Listing Three, page 121, is twrp.hlp, a help text file that we will use in this month's expansion of the editor. Look at this listing now for an understanding of the idea. Later you might want to change the file to reflect changes you make to the editor commands when you customize the editor with your own preferred command set. The getkey function watches two global variables -the function pointer named helpfunc and the integer named helpkey. If a program wants to intercept a help keystroke, it can assign a function address and a keystroke value to these variables. Then, if getkey senses that the user has pressed the assigned help key, it calls the assigned function. The source file named help.c includes the function load_help, which an application program calls to load a help text file. The function assigns a help function key (F1 in our implementation) by initializing the helpkey integer and assigns its own help function (display_help) by initializing the helpfunc pointer. The file help.h contains a macro, set that allows an application function to name the mnemonic for a help window. With this macro, an application can maintain the proper current window for the help context of the program. The source files entry.h and menu.h from October define structures that an application program initializes to use the data entry and menu functions. The structures include pointers to character pointers, which, if initialized, provide the window mnemonics for help windows for menu selections and data entry fields. The display_help function senses that an application has used set-help to establish a help window, that the menu cursor is on a menu selection, or that a data entry field is being processed. The display_help function thus selects the appropriate window if the user presses the help key. With this help facility applied along with the other window functions, the applications programmer can employ context-sensitive help windows for menus, data entry screens, and other program modes. The system developer needs only to do the following things to implement the feature: The Tiny Word Processor I promised you an expanded text editor, one that will support the communications program. For this editor, we will use the window editor function from November, the data entry and menu functions from October, and the context-sensitive help window functions just described. We can call this expanded editor from applications programs just as we can the less well-endowed editor engine of last month. To provide an example of the expanded editor, I built a simple front end that uses the editor in the way that our utility program will use it --as a tiny word processor. With the front end, the program becomes a stand-alone editor package with minimum wordprocessing features and capabilities. This new program marks a milestone --I am using it to write this column. This drastic measure is a test to ferret out the hidden bugs. It is a risky endeavor because I stand to lose my work if this unproven editor crashes or fails to save my deathless prose correctly. For this reason I will be making lots of departures from typing to save the text and take a look at what was saved --the sanctity of my sanity included. This new program is the first time we use the tools in an actual application. As my own beta tester, I find things that need to be changed. The first modification I make is to the editor colors, making them more pleasing than the bland monochrome combinations in the window.h defaults. These selections are personal; you'll want to make your own. Next comes a pleasant discovery. Much of my work is done on airplanes, and I use a barebones Toshiba T1000 laptop MS-DOS computer --low cost, low weight, minimum capabilities. As it happens, these words are being written between Dallas and Phoenix. One of the drawbacks to this bottom-of-the-line machine is that it takes forever to load any of the full-functioned word processors from the single 3.5-inch diskette. But our new tiny word processor is a mere 30K and loads itself in a few seconds, thus solving a months old problem. Now I have to deal with another problem. Whenever I haul out the T1000, set it up on the tray table, and get deeply engrossed, my neighbor in the next seat gets interested in the cute little machine. This brings the inevitable tap on the arm and the subsequent unsolicited computer discussion in which I hear about the traveler's office computers and how he knows nothing about them (but his son is a whiz). People always ask where I got the T1000, what it cost, and what I use it for. My pal Bill Chaney would grumble something about keeping breeding records for pit bulls, none of which would be true, but he wouldn't be bothered anymore and could then work undisturbed. To build the tiny word processor, which I will now call TWRP (pronounced " twerp"), we surround the window text editor from last month with a menu shell and some file-management features. These features employ the menu and data entry functions from October. We want the editor to be available in two ways: as a stand-alone program and as a function that can be called from an application program. TWRP is built from two source files. Listing Four, page 122, is editshel.c. This file contains the menu shell and the advanced editor commands for file management and text searching. With editshel.c, an application program can link to the advanced editor features. Listing Five, page 124, is twrp.c, the outer layer that uses the advanced editor to build TWRP as a stand-alone program. Notice that twrp.c contains the call to load_help to load the help file for the editor. By isolating this call in the outer function, we reserve the ability for other programs that call the editor to have other, perhaps more complex, help files. editshel.c contains a set of expanded commands as case statements in a switch statement. The function that contains this switch is named editmenu. This function represents the technique we will use to add features to the editor as they are required. When editor.c encounters a key stroke that it does not recognize, it calls the function addressed in an external function pointer named edit_func. If the pointer is NULL the editor rings the bell to indicate that the command is invalid. By initializing that pointer, we can extend the command set. By putting a similar function pointer chain at the end of our extended command set, we can keep the door open for future extensions. It would be easier to add cases to the original editor's command-dispatching switch, but then we would need to publish a modified editor.c each time we added features to the editor. With this approach each extension is contained in the source module that has the extending code. Another advantage of our extension strategy is that it gives the editor multiple levels of functionality. The current level depends on the context in which the editor is executed. A program that uses the expanded editor can also use the simpler window editor to collect small amounts of text for other reasons. That invocation of the editor would not, for example, have file-management commands because the extension function pointer would be NULL for the duration of the editing session. Because we are discussing extended editor commands, we should consider what the big-time word processors do that TWRP cannot do. TWRP has no spelling checker or thesaurus, no keyboard macros, no fonts, no columns, no index or table of contents generator, no style sheets, no footnotes. It sounds a lot like the WordStar of yore. But wait, there's more --or less, depending on how you look at it. TWRP has no underscoring, boldface, or subscripting and superscripting; no pagination; no mail-merge; no headers and footers; no printing; no variable margins. So what good is it, and what does it do? TWRP is primarily a text-composition tool, supporting the most basic text entry activities needed by writers of everything from memos to manuscripts. You type the text in, and TWRP saves it for you. You can load and save text files; merge text from other files; form paragraphs; mark blocks; and move, copy, and delete blocks. TWRP is a lot like the popular desktop accessory notepad programs. It has, however, one unique and endearing quality --it can be linked into our pro grams as an in-line word processor, fully integrated with whatever else we have going on. What's more, the source code is ours and we can make it do whatever we like. This observation returns us to the subject of macros. TWRP has no keyboard macros in the style of many editors and word processors. Brief, the world class programmer's editor from Solution Systems, has a macro language that resembles Lisp. The ME editor from Magma Software Systems and its derivative, the New York Word Processor, have macro languages that resemble C. The new Microsoft Editor uses compiled C extensions for advanced macros. Borland's Sprint word processor has a procedural macro language. So does XyWrite from XyQuest. All these editors and word processors have compiled or interpreted macro languages, some of which resemble C. In that spirit, therefore, TWRP is, by declaration and acclamation, blessed with a macro language that not only resembles C, it is C. If you want to add a macro, you add an extension function in the manner described previously, write the procedure as a C function, and recompile and link TWRP. What better way for a C programmer to add a complex macro to an editor? The MAKE Files Listing Six, page 124, is twrp.prj, the Turbo C project make file for the Turbo C environment compiler. Use the compact- memory model with all error checking enabled. You will need source files from the September, October, November, and this month's C Programming column. C Tool Set Errata My use of the tools has uncovered a few minor problems that I will address here. When I moved to the compactdata model to support an 800-line edit buffer, a bug showed up in window.c (September DDJ). The writeline function has some nonportable pointer juggling that needs to be tightened up. Substitute these lines for the call to the _vram function: _vram(_vptr(x+wkw.lf-1, y+wkw.tp-1), (int far *) cl, (unsigned) ((int far *) cp - (int far *) cl)); The menu select function in menu.c failed to reset the global pointer named in to NULL before returning. Insert this statement before the return from menu select at the bottom of the function: mn = NULL; I will update the download versions of these files on CompuServe to reflect these corrections. Turbo C2.O All the window tools from the C Programming columns have been built with Turbo C, Version 2.0. This is a last minute development; 2.0 has not been out long. The big news is the integrated debugger in the Turbo C environment; everyone has been waiting for that well-rumored feature for a long time, and Turbo C has now removed the last reason for feeling inferior to QuickC. I have spent a lot of time using the debugger and can say without reservation that you will be delighted with it. I am especially impressed by its seamless integration with the editor and compiler environment. Our small TWRP project is by no means an exhaustive test of the compiler, so this endorsement is preliminary but enthusiastic. Turbo C has a new pop-up utility program named THELP that uses the Turbo on-line help file. This is a significant addition to the package. You know how Ctrl-Fl works in the TC environment- it pops up a context-sensitive help window about Turbo C. Now you can have those same language and compiler help displays from within your personal text editor (including TWRP). The THELP hot key pops up the Turbo help windows over whatever you happen to be doing. If the cursor is on a Turbo keyword -a library function name, perhaps -the help window related to that particular word is displayed. TesSeRact THELP was built from the TesSeRact shareware memory-resident program library. This library is available in files you can download from CompuServe in the CL and Borland libraries and from other BBSs. Source code is available to registered users. TesSeRact is said to be the answer to a terminate-and-stay-resident (TSR) programmer's prayer, able to make any program a well-behaved TSR capable of running in harmonious accord with other programs, TSR and otherwise. I don't completely believe this, but if you want to write TSRs without understanding how they work, this is a good way to go. The documentation explains how to use the libraries, which are available for C, assembly language, and Pascal. To use the libraries in programs that you distribute, you must register your use and keep the TesSeRact signature in the code. That's how I figured out that ThELP is a TesSeRact program. The developers of TesSeRact are experts in the black art of TSR programming. The development team is what remains of the Ringmaster project, a failed industry attempt to settle on a standard for TSRs. Given a lack of enthusiasm among private software publishers to sign up to such a standard, some of the team splintered off and took the shareware approach. The libraries that resulted provide a reasonably safe way to get a TSR program running with a minimum of fuss. Having researched, developed, and written extensively about TSR programs, I am convinced that there is no way to write one that can be guaranteed to work in all PC hardware environments and in the company of all other programs and systems. MS-DOS just wasn't meant to be used that way, and all those successful TSRs are the legacy of a generation of hackers who figured out ways around the limitations of DOS --even if a lot of the programs don't work with one another. TSRs, working or not, will be with us as long as MS-DOS is with us, and that is going to be a long time. A Crotchet: The Trouble with Programming The trouble with programming is that it isn't getting any easier. Quite the opposite, programming is getting a lot harder. In recent months I have been looking at new or different software development environments. In a recent column I told of my first exposure to C++ and object-oriented programming, a most humbling experience. Another venture into the unknown (to me, that is) was my excursion into the Macintosh. Someone observed that it takes a good programmer at least a year to become a competent Mac programmer in C or any other language. Now I am unfolding the OS/2 Software Development Kit (SDK) from Microsoft. Seventy-five pounds of manuals and diskettes and eight videotapes comprise this formidable beast. At first glance it appears that unraveling what manuals contain what information is itself a monumental effort, not to mention the learning process that follows. I have only just begun, and I am wondering how many blue moons will pass before I see an OS/2 screen group displaying my very own "Hello, world" message. No, programming isn't getting any easier. Remember the promise of application generators and fourth-generation languages that were going to put system design and programming within the reach of Everyman? A new wave of dBase and NOMAD pseudo-programmers were going to put us all out of business. Not to worry. The complexity of these new software development platforms ensures a place for hackerlevel talent for years to come. The best part of this gradual evolution to more complicated programming is that we don't need to learn a new language. C is surviving and is still that overworked cliche, the "language of choice" -not that it will be easy to remember the 900+ OS/2 function calls, but at least their basis is in the syntax of the best programming language ever devised. It does, however, raise my C purist's hackles when I see the function declarations assigned the pascal type in their prototypes. It is fortunate that most of those blights are hidden away in header files. Indeed! A Book for All Seasons When you tackle OS/2, plan to spend some money at the bookstore. You will have to augment the 75 pounds of abstruse Microsoft manuals with a few more readable offerings from other authors. I have most of the books that have been written about OS/2, and one stands out as the essential first book to read. Its title is Inside OS/2, and its author is Gordon Letwin. Do not confuse this book with another one with the same title. This one is published by Microsoft Press, and to its credit, Microsoft includes a copy of it with the SDK. Inside OS/2 is not the only book you will need, but it is the first. Read it even before you watch the videotapes. That way, if you sleep through something important, chances are Letwin has already explained it. Inside OS/2 is an excellent description of the underlying design principles for OS/2. It will help if you already know a little bit about operating system theory. An understanding of the concepts explained in this work is essential for the design of programs that would effectively use the advanced features of OS/2. I like this book. (The little old lady in the next seat is eyeing my T1000. Soon she'll be tapping me on the arm. Where are you, Bill Chaney, when I need you?) _C PROGRAMMING COLUMN_ by Al Stevens [LISTING ONE] <a name="0233_000c"> /* ------------ help.h -------------- */ void load_help(char *); void display_help(void); extern char *help_window; #define set_help(s) help_window=s <a name="0233_000d"><a name="0233_000d"> <a name="0233_000e">[LISTING TWO] <a name="0233_000e"> /* --------- help.c ----------- */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h> #include "window.h" #include "menu.h" #include "entry.h" #include "help.h" #define MAXHELPS 25 static struct helps { char hname [9]; int h, w; long hptr; } hps [MAXHELPS+1]; extern FIELD *fld; extern MENU *mn; static int hp = 0; static FILE *helpfp; static char hline [80]; char *help_window; /* ----------- load the HELP! definition file ------------ */ void load_help(char *hn) { extern void (*helpfunc)(void); extern int helpkey; char *cp; helpfunc = display_help; helpkey = F1; hp = 0; if ((helpfp = fopen(hn, "r")) == NULL) return; if ((fgets(hline, 80, helpfp)) == NULL) return; while (1) { if (hp == MAXHELPS) break; if (strncmp(hline, "<end>", 5) == 0) break; if (*hline != '<') continue; hps[hp].h = 2; hps[hp].w = 23; strncpy(hps[hp].hname, hline+1, 8); hps[hp].hname[8] = '\0'; cp = strchr(hps[hp].hname, '>'); if (cp) *cp = '\0'; hps[hp].hptr = ftell(helpfp); if (fgets(hline, 80, helpfp) == NULL) strcpy(hline, "<end>"); while (hline[0] != '<') { hps[hp].h++; hps[hp].w = max(hps[hp].w, strlen(hline)+2); if (fgets(hline, 80, helpfp) == NULL) strcpy(hline, "<end>"); } hp++; } } /* ---------- display the current help window ----------- */ void display_help() { int hx, hy, i, xx, yy, ch; extern int helpkey, hsel; char *save_help; static int inhelp = 0; extern struct wn wkw; if (inhelp) return; inhelp++; save_help = help_window; if (fld != NULL) help_window = fld->fhelp; else if (mn != NULL) help_window = (mn+hsel-1)->mshelp [wkw.wy-1]; if (help_window != NULL) { for (ch = 0; ch < hp; ch++) if (strcmp(help_window, hps[ch].hname) == 0) break; if (ch < hp) { xx = wherex(); yy = wherey(); hidecursor(); hx = ((80-hps[ch].w) / 2)+1; hy = ((25-hps[ch].h) / 2)+1; establish_window(hx, hy, hx+hps[ch].w-1, hy+hps[ch].h, HELPFG, HELPBG, TRUE); fseek(helpfp, hps[ch].hptr, 0); for (i = 0; i < hps[ch].h-2; i++) { gotoxy(2,2+i); fgets(hline, 80, helpfp); cprintf(hline); } gotoxy(2,2+i); cprintf(" [Any key to return]"); hidecursor(); getkey(); delete_window(); if (mn == NULL || fld != NULL) { textcolor(FIELDFG); textbackground(FIELDBG); gotoxy(xx, yy); } } } help_window = save_help; --inhelp; } <a name="0233_000f"><a name="0233_000f"> <a name="0233_0010">[LISTING THREE] <a name="0233_0010"> <editor> TINY WORD PROCESSOR (TWP) COMMANDS -------Cursor Movement------ ---------Page Movement-------- arrows = move text cursor Ctrl-Home = Beginning of File Ctrl-T = Top of Window Ctrl-End = End of File Ctrl-B = Bottom of Window PgUp = Previous Page Ctrl -> = Next Word PgDn = Next Page Ctrl <- = Previous Word Home = Beginning of Line ---------Editor Control------- End = End of Line Alt-A = Auto Paragraph Reform Shift-Tab = Back tab --------Block Controls------ ---------Edit Commands-------- F2 = Form Paragraph Alt-Q or Esc = Done F5 = Mark Block Beginning Ins = Insert Mode F6 = Mark Block End Del = Delete Char F3 = Move Block <-- = Rubout F4 = Copy Block Ctrl-D = Delete Word F8 = Delete Block Alt-D = Delete Line F9 = Unmark Block F7 = Find Alt-F7 = Find again <load> Load a new file into TWP, replacing the existing file. <save> Save the file from the edit buffer. <merge> Merge a file into the edit buffer at the line where the cursor is pointed. <new> Clear the edit buffer and create a new file. <quit> Exit from TWP, returning to DOS <move> Move the block to the line where the cursor points. This is an insert move. <copy> Copy the block to the line where the cursor points. This is an insert copy. <delete> Delete the block closing the space it occupies. <hide> Turn off the block markers. <formpara> Form a paragraph. This makes a paragraph from a marked block, or, if no block is marked, to the next blank or indented line. <markbeg> Mark the beginning line of a block for move, copy, delete, or paragraph. <markend> Mark the ending line of a block for move, copy, delete, or paragraph. <find> Find a specified string in the edit buffer. Move the cursor to the location where the string was found. <findagn> Find the next occurrence of the string most recently specified. <auto> Turn on/off the automatic paragraph forming feature. <insert> Turn on/off the character insert mode. (insert/overstrike toggle) <filename> Enter the path and file name. The path is optional but must be fully qualified if entered. <findstr> Enter the string to be searched by the Find command. <end> <a name="0233_0011"><a name="0233_0011"> <a name="0233_0012">[LISTING FOUR] <a name="0233_0012"> /* --------- editshel.c ------------ */ #include <stdio.h> #include <string.h> #include <conio.h> #include <stdlib.h> #include <mem.h> #include <alloc.h> #include <ctype.h> #include "window.h" #include "menu.h" #include "entry.h" #include "editor.h" #include "help.h" int MAXLINES; /* maximum number of editor lines */ #define EDITWIDTH 78 /* length of an editor line */ #define BUFLEN (EDITWIDTH*MAXLINES) /* --------- alt keys returned by getkey() --------- */ #define ALT_A 158 #define ALT_L 166 #define ALT_M 178 #define ALT_N 177 /* -------- configured advanced editor commands --------- */ #define FIND F7 #define FIND_AGAIN ALT_F7 #define LOAD_FILE ALT_L #define SAVE_FILE ALT_S #define MERGE_FILE ALT_M #define NEW_FILE ALT_N #define EDITOR_MENU F10 #define REFORM ALT_A /* ---------- editor menu tables --------- */ static char *fselcs[] = { "Load [Alt-L]", "Save [Alt-S]", "Merge [Alt-M]", "New [Alt-N]", "Quit [Alt-Q]", NULL }; static char *filehelp[] = { "load", "save", "merge", "new", "quit" }; static char *eselcs[] = { "Move [F3]", "Copy [F4]", "Delete [F8]", "Hide [F9]", "Paragraph [F2]", "Mark Beg [F5]", "Mark End [F6]", "Find [F7]", "Find Again [Alt-F7]", NULL }; static char *edithelp[] = { "move", "copy", "delete", "hide", "formpara", "markbeg", "markend", "find", "findagn", }; static char *oselcs[] = { "Auto Paragraph Reformat [Alt-A]", "Insert [Ins]", NULL }; static char *opthelp[] = { "auto", "insert" }; void fileedit(char *); static int edit(int,int); static void editmenu(int); static int get_filename(char *, int); static int write_file(void); static int load_file(int,int); static int save_file(int,int); static int merge_file(int,int); static int new_file(int,int); static void editkeys(int); static void statusline(void); static int findstring(void); static char *find(char *, unsigned); static int read_file(char *, char *, int, int, int); static int bufferok(char *); static void notice(char *); void (*edit_extend)(void); static char fkeys[] = {LOAD_FILE,SAVE_FILE, MERGE_FILE,NEW_FILE,QUIT}; static char forced[] = {MOVE_BLOCK,COPY_BLOCK, DELETE_BLOCK,HIDE_BLOCK, PARAGRAPH,BEGIN_BLOCK, END_BLOCK,FIND,FIND_AGAIN}; static char options[] = {REFORM,INS}; static int (*ffuncs[])() = {load_file,save_file,merge_file,new_file,edit}; static int (*efuncs[])() = {edit,edit,edit,edit,edit,edit,edit,edit,edit}; static int (*ofuncs[])() = {edit,edit,edit}; MENU emn [] = { {"File", NULL, fselcs, filehelp, fkeys, ffuncs, 0}, {"Edit", NULL, eselcs, edithelp, forced, efuncs, 0}, {"Options", NULL, oselcs, opthelp, options, ofuncs, 0}, {NULL} }; /* ------ filename data entry template and buffer ------- */ static char filename[65]; static char savefn [65]; static char filemask[65]; FIELD fn_template[] = { {2,14,1,filename,filemask,"filename"}, {0} }; /* ------- text find data entry template and buffer ------ */ static char findstr[71]; static char findmask[71]; FIELD find_template[] = { { 2,8,1,findstr,findmask,"findstr"}, {0} }; extern int forcechar; extern struct edit_env ev; static void editkeys(int c) { switch(c) { case REFORM: ev.reforming ^= TRUE; break; case NEW_FILE: new_file(1,1); break; case LOAD_FILE: load_file(1,1); break; case SAVE_FILE: save_file(1,1); break; case MERGE_FILE: merge_file(1,1); break; case FIND: if (!findstring()) break; case FIND_AGAIN: ev.nowptr++; ev.nowptr = find(ev.nowptr, ev.lstptr-ev.nowptr); if (ev.nowptr != NULL) { ev.curr_x = (ev.nowptr-ev.topptr) % ev.wwd; if (ev.nowptr >= ev.bfptr+ev.wwd*ev.wdo->ht) ev.bfptr = ev.nowptr - ev.curr_x; ev.curr_y = (ev.nowptr - ev.bfptr) / ev.wwd; } else error_message("Not found ..."); break; case ALT_F: editmenu(1); break; case ALT_E: editmenu(2); break; case ALT_O: editmenu(3); break; case EDITOR_MENU: editmenu(0); break; default: if (edit_extend) (*edit_extend)(); else putch(BELL); break; } } static void editmenu(n) { menu_select(emn, n); } static int edit(hs,vs) { forcechar = emn[hs-1].mskeys[vs-1] & 255; return TRUE; } /* ---------- edit a file -------------- */ void fileedit(char *file) { char *bf, *mb; extern void (*editfunc)(); extern void (*status_line)(); setmem(filename, 64, ' '); setmem(filemask, 64, '_'); setmem(findmask, 70, '_'); setmem(findstr, 70, ' '); establish_window(1,2,80,24,TEXTFG,TEXTBG,TRUE); editfunc = editkeys; status_line = statusline; mb = display_menubar(emn); statusline(); if ((bf = malloc(BUFLEN)) != NULL) { setmem(bf, BUFLEN, ' '); strcpy(filename, file); filename[strlen(filename)] = ' '; if (*file) read_file(" Loading ... ",bf,0,FALSE,FALSE); while (TRUE) { text_editor(bf, MAXLINES, EDITWIDTH); if (bufferok("quit")) break; } free(bf); } restore_menubar(mb); delete_window(); } /* ---------- load a file --------------- */ static int load_file(hs,vs) { if (bufferok("reload")) strcpy(savefn, filename); if (get_filename(" Load what file? ", TRUE) != ESC) { setmem(ev.topptr, BUFLEN, ' '); read_file(" Loading ... ",ev.topptr,0,FALSE,TRUE); forcechar = BEGIN_BUFFER; ev.text_changed = FALSE; } else strcpy(filename, savefn); return TRUE; } /* ---------- merge a file into the edit buffer -------- */ static int merge_file(hs,vs) { strcpy(savefn, filename); if (get_filename(" Merge what file? ", TRUE) != ESC) { if (read_file(" Merging ... ", curr(0, ev.curr_y), lineno(ev.curr_y), TRUE, TRUE)) { forcechar = REPAINT; ev.text_changed = TRUE; } } strcpy(filename, savefn); return TRUE; } /* --------- save the file -------------- */ static int save_file(hs,vs) { if (get_filename(" Save as what file? ", FALSE) != ESC) if (write_file()) ev.text_changed = FALSE; return TRUE; } /* ---------- start a new file ------------- */ static int new_file(hs,vs) { if (bufferok("erase")) if (get_filename(" Build as what file? ",TRUE)!=ESC){ setmem(ev.topptr, BUFLEN, ' '); forcechar = BEGIN_BUFFER; ev.text_changed = FALSE; } return TRUE; } /* -------- read a file name ------------- */ static int get_filename(char *ttl, int clear) { int rtn; establish_window(1,23,80,25,ENTRYFG,ENTRYBG,TRUE); window_title(ttl); gotoxy(3,2); cputs("File name:"); rtn = data_entry(fn_template, clear, 1); delete_window(); return rtn; } /* --------- write a file ------------ */ static int write_file() { FILE *fp; int ln, i, ln1; char *cp, buf[EDITWIDTH+1]; if ((fp = fopen(filename, "w")) == NULL) { error_message(" Can't write that file! "); return FALSE; } notice(" Writing file ... "); /* ----- find the last significant line ----- */ for (ln = MAXLINES-1; ln > -1; --ln) { cp = ev.topptr + ln * EDITWIDTH; for (i = 0; i < EDITWIDTH; i++) if (*(cp + i) != ' ') break; if (i < EDITWIDTH) break; } for (ln1 = 0; ln1 <= ln; ln1++) { movmem(ev.topptr + ln1 * EDITWIDTH, buf, EDITWIDTH); i = EDITWIDTH-1; cp = buf; while (i >= 0 && *(cp + i) == ' ') --i; if (i == -1 || *(cp + i) != ' ') i++; *(cp + i) = '\n'; *(cp + i + 1) = '\0'; fputs(cp, fp); } fclose(fp); delete_window(); return TRUE; } /* -------------- read (load or merge) a file ----------- */ static int read_file(char *nt,char *ln,int lines,int merging,int needed) { FILE *fp; char ibf[120]; char *cp; int x; if ((fp = fopen(filename, "r")) != NULL) { notice(nt); while (fgets(ibf, 120, fp) && lines < MAXLINES) { lines++; if (merging) { movmem(ln,ln+EDITWIDTH, BUFLEN-lines*EDITWIDTH); setmem(ln,EDITWIDTH,' '); } cp = ibf, x = 0; while (*cp && *cp != '\n') { if (*cp == '\t') x += TAB-(x%TAB); else *(ln+x++) = *cp; cp++; } ln += EDITWIDTH; } fclose(fp); delete_window(); return TRUE; } else if (needed) error_message("No such file can be found"); return FALSE; } /* ----------- display a status line ----------- */ static void statusline() { char stat[81], *st; int cl[81], *cp; static char msk[] = "Line:%3d Column:%2d %-9.9s %-21.21s F1:Help \ F10:Menu "; unsigned y = 1; unsigned x = 1; unsigned attr = ((MENUFG | (MENUBG << 4)) << 8); if (ev.wwd) { y = (unsigned) (ev.nowptr-ev.topptr) / ev.wwd + 1; x = (unsigned) (ev.nowptr-ev.topptr) % ev.wwd + 1; } sprintf(stat,msk,y,x, (ev.edinsert ? "Insert" : "Overwrite"), (ev.reforming ? "Auto Paragraph Reform" : " ")); for (st = stat, cp = cl; *st; st++) *cp++ = (*st & 255) | attr; __vram(__vptr(1,25),cl,80); set_help("editor"); } /* -------- get a string to find --------- */ static int findstring() { char *cp = findstr+60; int ans; establish_window(1,23,80,25,ENTRYFG,ENTRYBG,TRUE); gotoxy(2,2); cputs("Find?"); ans = data_entry(find_template, TRUE, 1); delete_window(); if (ans == ESC) return FALSE; while (*--cp == ' ') ; if (*cp) *(cp+1) = '\0'; return TRUE; } /* -------- find a string in the buffer -------------- */ static char *find(char *bf, unsigned len) { char *cp; for (cp = bf; cp < bf+len-strlen(findstr); cp++) if (strncmp(cp, findstr, strlen(findstr)) == 0) return cp; return NULL; } /* ---------- test for buffer changed ----------- */ static int bufferok(char *s) { int c = 'Y'; if (ev.text_changed) { establish_window(23,11,56,13,ERRORFG,ERRORBG,TRUE); gotoxy(2,2); cprintf("Text has changed, %s? (y/n)", s); hidecursor(); do putch(BELL), c = getkey(); while (toupper(c) != 'Y' && toupper(c) != 'N'); delete_window(); } return toupper(c) == 'Y'; } /* -------- small message ------------ */ static void notice(char *s) { int lf = (80-strlen(s))/2-1; int rt = lf+strlen(s)+2; establish_window(lf,11,rt,13,HELPFG,HELPBG,TRUE); gotoxy(2,2); cputs(s); } <a name="0233_0013"><a name="0233_0013"> <a name="0233_0014">[LISTING FIVE] <a name="0233_0014"> /* ----------- twrp.c ------------ */ #include <conio.h> #include "window.h" #include "editor.h" #include "help.h" void main(int, char **); void fileedit(char *); void main(int argc, char **argv) { extern int inserting, MAXLINES; MAXLINES = 800; load_help("twrp.hlp"); clear_screen(); fileedit(argc > 1 ? argv[1] : ""); clear_screen(); inserting = FALSE; insert_line(); } <a name="0233_0015"><a name="0233_0015"> <a name="0233_0016">[LISTING SIX] <a name="0233_0016"> trwp (window.h, editor.h, help.h) editshel (editor.h, menu.h, entry.h, help.h, window.h) editor (editor.h, window.h) entry (entry.h, window.h) menu (menu.h, window.h) help (help.h, window.h) window (window.h)
http://www.drdobbs.com/cpp/c-programming/184408046
CC-MAIN-2015-14
refinedweb
5,489
63.7
What you can do is create an IInitializableModule that attaches to the contentEvent PublishedContent You can then check the type of the content expirying and then clear your cache public class ClearCacheEvents : IInitializableModule { public void Initialize(InitializationEngine context) { var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>(); contentEvents.PublishedContent += ClearCache; } private void ClearCache(object sender, EPiServer.ContentEventArgs e) { if (e.Content is SomeContent) { //Logic to clear cache } } } I don't think there is a nice solution for that. What "content" are you caching? Is it possible to check for expired content when you get that cache? You could check the StopPublish on the cached item. If the StopPublish date is changed, I believe your cache is invalidated. Hi Andreas A simple fix could be to just set the expiration date and time of your cached object, to the known StopPublish property value (if it is not null). As Tomas points out, if an editor changes the StopPublish date to something earlier it would be removed from cache anyway. Then next time someone requests it, it is cached again with the new StopPublish value. This way you don't need to implement any custom content event handlers, at all. I can use IContentCacheKeyCreatorto create a cache key for some content, and then cache a item using ISynchronizedObjectInstanceCache. If I would change that content via the admin interface, the cached item would be invalidated. However, if the same content would expire (StopPublish is passed) - the cached item is not invalidated. Does anyone know how to handle this?
https://world.optimizely.com/forum/developer-forum/CMS/Thread-Container/2019/11/cache-dependencies-and-content-expiration/
CC-MAIN-2022-33
refinedweb
252
56.15
Unity Interfaces – Getting Started Lately, I’ve realized that many Unity developers have never programmed outside of Unity projects. While there’s nothing wrong with that, it does seem to leave some holes in the average Unity developers skill set. There are some great features and techniques that aren’t commonly used in Unity but are staples for typical c# projects. That’s all fine, and they can be completely productive, but some of the things I see missing can really help, and I want to make sure to share those things with you. Because of this, I’ve decided to write a few articles covering some core c# concepts that can really improve your code if you’re not using them already. The first in this series will cover c# interfaces. If you google c# interfaces, you’ll come across the msdn definition Personally, I prefer to use an example to explain them though, so here’s one from an actual game. The ICanBeShot interface In Armed Against the Undead, you have guns and shoot zombies.. But you can also shoot other things like Ammo pickups, Weapon unlocks, Lights, etc. Shooting things is done with a standard raycast from the muzzle of the gun. Any objects on the correct layer and in range can be shot. If you’ve used Physics.Raycast before, you’ll know that it returns a bool and outputs a RayCastHit object. The RayCastHit has a .collider property that points to the collider your raycast found. In Armed, the implementation of this raycast looks like this: private bool TryHitEnvironment(Ray ray) { RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, _weaponRange, LayerMask.GetMask("EnvironmentAndGround")) == false) return false; ICanBeShot shootable = hitInfo.collider.GetComponent<ICanBeShot>(); if (shootable != null) shootable.TakeShot(hitInfo.point); else PlaceBulletHoleBillboardOnHit(hitInfo); return true; } Here you can see that we do a raycast on the EnvironmentAndGround layer (where I place things you can shoot that aren’t enemies). If we find something, we attempt to get an ICanBeShot component. That component is not an actual implementation but rather an Interface which is on a variety of components. It’s also very simple with a single method named TakeShot defined on it as you can see here: public interface ICanBeShot { void TakeShot(Vector3 hitPosition); } If you’ve never used an interface before, it may seem a little strange that there’s no actual code or implementation. In the interface, we only define how the methods look and not the implementation. We leave that part to the classes implementing our interface. How the Interface is used So now that I have my interface, and I have a method that will search for components implementing that interface, let me show you some of the ways I’m using this interface. Implementation #1 – Ammo Pickups public class AmmoBox : MonoBehaviour, ICanBeShot { public void TakeShot(Vector3 hitPosition) { PickupAmmo(); if (_isSuperWeaponAmmo) FindObjectOfType<Inventory>().AddChargeToSuperWeapon(); else FindObjectOfType<Inventory>().AddAmmoToWeapons(); } } This ammo script is placed on an Ammo prefab. Notice the box collider that will be found by the raycast in TryHitEnvironment above (line 5). In the case of the AmmoBox, the TakeShot method will add ammo to the currently equipped weapon. But an AmmoBox isn’t the only thing we want the player to shoot at. Implementation #2 – Weapon Unlocks public class WeaponUnlocker : MonoBehaviour, ICanBeShot { public void TakeShot(Vector3 hitPosition) { WeaponUnlocks.UnlockWeapon(_weaponToUnlock); PlayerNotificationPanel.Notify(string.Format("<color=red>{0}</color> UNLOCKED", _weaponToUnlock.name)); if (_particle != null) Instantiate(_particle, transform.position, transform.rotation); Destroy(this.gameObject); } } Compare the AmmoBox to the WeaponUnlocker. Here you see that we have a completely different implementation of TakeShot. Instead of adding ammo to the players guns, we’re unlocking a weapon and notifying the player that they’ve unlocked it. And remember, our code to deal with shooting things didn’t get any more complicated, it’s still just calling TakeShot. This is one of the key benefits, we can add countless new implementations, without complicating or even editing the code to handle shooting. As long as those components implement the interface, everything just works. Implementation #3 – Explosive Boxes These are crates that when shot will explode and kill zombies. Implementation #4 – Destructible Lights In addition to everything else, the lights can also take a shot (in which case they explode and turn off the light source component) Recapping Again to make the benefits of Unity interfaces clear, re-examine our code in TryHitEnvironment. ICanBeShot shootable = hitInfo.collider.GetComponent<ICanBeShot>(); if (shootable != null) shootable.TakeShot(hitInfo.point); We simply look for any collider on the right layer then search for the ICanBeShot interface. We don’t need to worry about which implementation it is. If it’s an ammo box, the ammo box code will take care of it. If it’s a weapon unlock, that’s covered as well. If we add a new object that implements the interface, we don’t need to touch our current code. Other Benefits While I won’t cover everything that’s great about interfaces in depth here, I feel I should at least point out that there are other benefits you can take advantage of. - Unit Testing – If you ever do any unit testing, interfaces are a key component as they allow you to mock out dependencies when you write your tests. - Better Encapsulation – When you code to interfaces, it becomes much more obvious what should be public, and your code typically becomes much better encapsulated. - Loose Coupling – Your code no-longer needs to rely on the implementations of methods it calls, which usually leads to code that is more versatile and changeable.
https://unity3d.college/2016/09/04/unity-and-interfaces/
CC-MAIN-2020-34
refinedweb
934
55.54
this is my code: and this is my error:and this is my error:Code:#include <iostream> using namespace std; int primedivisor ( int original) { int vr; int collective = 1; int n = 2; while (n != collective) { if (0 = original % n) { vr = n; original /= n;} else {n++;} } return vr; } int main() {int x; cin >> x; cin.ignore(); cout << primedivisor (x); cin.get(); return 0;} a.cpp<12> : error C2106: '=' : left operand must be l-value I tried making pointers and sticking them in, putting 1 instead of "original", switching it around, and making all sorts of different types of variables (char, float, etc.) nothing can take away the message.
http://cboard.cprogramming.com/cplusplus-programming/70052-l-value-complaint-compiler.html
CC-MAIN-2014-15
refinedweb
107
71.65
Math optimization in C# I))); } Answers. If it's for an activation function, does it matter terribly much if the calculation of e^x is completely accurate? For example, if you use the approximation (1+x/256)^256, on my Pentium testing in Java (I'm assuming C# essentially compiles to the same processor instructions) this is about 7-8 times faster than e^x (Math.exp()), and is accurate to 2 decimal places up to about x of +/-1.5, and within the correct order of magnitude across the range you stated. (Obviously, to raise to the 256, you actually square the number 8 times -- don't use Math.Pow for this!) In Java: double eapprox = (1d + x / 256d); eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; Keep doubling or halving 256 (and adding/removing a multiplication) depending on how accurate you want the approximation to be. Even with n=4, it still gives about 1.5 decimal places of accuracy for values of x beween -0.5 and 0.5 (and appears a good 15 times faster than Math.exp()). P.S. I forgot to mention -- you should obviously not really divide by 256: multiply by a constant 1/256. Java's JIT compiler makes this optimisation automatically (at least, Hotspot does), and I was assuming that C# must do too. Have a look at this post. it has an approximation for e^x written in Java, this should be the C# code for it (untested): public static double Exp(double val) { long tmp = (long) (1512775 * val + 1072632447); return BitConverter.Int64BitsToDouble(tmp << 32); } In my benchmarks this is more than 5 times faster than Math.exp() (in Java). The approximation is based on the paper "A Fast, Compact Approximation of the Exponential Function" which was developed exactly to be used in neural nets. It is basically the same as a lookup table of 2048 entries and linear approximation between the entries, but all this with IEEE floating point tricks. EDIT: According to Special Sauce this is ~3.25x faster than the CLR implementation. Thanks! - Remember, that any changes in this activation function come at cost of different behavior. This even includes switching to float (and thus lowering the precision) or using activation substitutes. Only experimenting with your use case will show the right way. - In addition to the simple code optimizations, I would also recommend to consider parallelization of the computations (i.e.: to leverage multiple cores of your machine or even machines at the Windows Azure Clouds) and improving the training algorithms. UPDATE: Post on lookup tables for ANN activation functions UPDATE2: I removed the point on LUTs since I've confused these with the complete hashing. Thanks go to Henrik Gustafsson for putting me back on the track. So the memory is not an issue, although the search space still gets messed up with local extrema a bit. At 100 million calls, i'd start to wonder if profiler overhead isn't skewing your results. Replace the calculation with a no-op and see if it is still reported to consume 60% of the execution time... Or better yet, create some test data and use a stopwatch timer to profile a million or so calls. If you're able to interop with C++, you could consider storing all the values in an array and loop over them using SSE like this: void sigmoid_sse(float *a_Values, float *a_Output, size_t a_Size){ __m128* l_Output = (__m128*)a_Output; __m128* l_Start = (__m128*)a_Values; __m128* l_End = (__m128*)(a_Values + a_Size); const __m128 l_One = _mm_set_ps1(1.f); const __m128 l_Half = _mm_set_ps1(1.f / 2.f); const __m128 l_OneOver6 = _mm_set_ps1(1.f / 6.f); const __m128 l_OneOver24 = _mm_set_ps1(1.f / 24.f); const __m128 l_OneOver120 = _mm_set_ps1(1.f / 120.f); const __m128 l_OneOver720 = _mm_set_ps1(1.f / 720.f); const __m128 l_MinOne = _mm_set_ps1(-1.f); for(__m128 *i = l_Start; i < l_End; i++){ // 1.0 / (1.0 + Math.Pow(Math.E, -value)) // 1.0 / (1.0 + Math.Exp(-value)) // value = *i so we need -value __m128 value = _mm_mul_ps(l_MinOne, *i); // exp expressed as inifite series 1 + x + (x ^ 2 / 2!) + (x ^ 3 / 3!) ... __m128 x = value; // result in l_Exp __m128 l_Exp = l_One; // = 1 l_Exp = _mm_add_ps(l_Exp, x); // += x x = _mm_mul_ps(x, x); // = x ^ 2 l_Exp = _mm_add_ps(l_Exp, _mm_mul_ps(l_Half, x)); // += (x ^ 2 * (1 / 2)) x = _mm_mul_ps(value, x); // = x ^ 3 l_Exp = _mm_add_ps(l_Exp, _mm_mul_ps(l_OneOver6, x)); // += (x ^ 3 * (1 / 6)) x = _mm_mul_ps(value, x); // = x ^ 4 l_Exp = _mm_add_ps(l_Exp, _mm_mul_ps(l_OneOver24, x)); // += (x ^ 4 * (1 / 24)) #ifdef MORE_ACCURATE x = _mm_mul_ps(value, x); // = x ^ 5 l_Exp = _mm_add_ps(l_Exp, _mm_mul_ps(l_OneOver120, x)); // += (x ^ 5 * (1 / 120)) x = _mm_mul_ps(value, x); // = x ^ 6 l_Exp = _mm_add_ps(l_Exp, _mm_mul_ps(l_OneOver720, x)); // += (x ^ 6 * (1 / 720)) #endif // we've calculated exp of -i // now we only need to do the '1.0 / (1.0 + ...' part *l_Output++ = _mm_rcp_ps(_mm_add_ps(l_One, l_Exp)); } } However, remember that the arrays you'll be using should be allocated using _aligned_malloc(some_size * sizeof(float), 16) because SSE requires memory aligned to a boundary. Using SSE, I can calculate the result for all 100 million elements in around half a second. However, allocating that much memory at a time will cost you nearly two-third of a gigabyte so I'd suggest processing more but smaller arrays at a time. You might even want to consider using a double buffering approach with 100K elements or more. Also, if the number of elements starts to grow considerably you might want to choose to process these things on the GPU (just create a 1D float4 texture and run a very trivial fragment shader). FWIW, here's my C# benchmarks for the answers already posted. (Empty is a function that just returns 0, to measure the function call overhead) Empty Function: 79ms 0 Original: 1576ms 0.7202294 Simplified: (soprano) 681ms 0.7202294 Approximate: (Neil) 441ms 0.7198783 Bit Manip: (martinus) 836ms 0.72318 Taylor: (Rex Logan) 261ms 0.7202305 Lookup: (Henrik) 182ms 0.7204863 public static object[] Time(Func<double, float> f) { var testvalue = 0.9456; var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1e7; i++) f(testvalue); return new object[] { sw.ElapsedMilliseconds, f(testvalue) }; } public static void Main(string[] args) { Console.WriteLine("Empty: {0,10}ms {1}", Time(Empty)); Console.WriteLine("Original: {0,10}ms {1}", Time(Original)); Console.WriteLine("Simplified: {0,10}ms {1}", Time(Simplified)); Console.WriteLine("Approximate: {0,10}ms {1}", Time(ExpApproximation)); Console.WriteLine("Bit Manip: {0,10}ms {1}", Time(BitBashing)); Console.WriteLine("Taylor: {0,10}ms {1}", Time(TaylorExpansion)); Console.WriteLine("Lookup: {0,10}ms {1}", Time(LUT)); } Off the top of my head, this paper explains a way of approximating the exponential by abusing floating point, (click the link in the top right for PDF) but I don't know if it'll be of much use to you in .NET. Also, another point: for the purpose of training large networks quickly, the logistic sigmoid you're using is pretty terrible. See section 4.4 of Efficient Backprop by LeCun et al and use something zero-centered (actually, read that whole paper, it's immensely useful). F# Has Better Performance than C# in .NET math algorithms. So rewriting neural network in F# might improve the overall performance. If we re-implement LUT benchmarking snippet (I've been using slightly tweaked version) in F#, then the resulting code: - executes sigmoid1 benchmark in 588.8ms instead of 3899,2ms - executes sigmoid2 (LUT) benchmark in 156.6ms instead of 411.4 ms More details could be found in the blog post. Here's the F# snippet JIC: #light let Scale = 320.0f; let Resolution = 2047; let Min = -single(Resolution)/Scale; let Max = single(Resolution)/Scale; let range step a b = let count = int((b-a)/step); seq { for i in 0 .. count -> single(i)*step + a }; let lut = [| for x in 0 .. Resolution -> single(1.0/(1.0 + exp(-double(x)/double(Scale)))) |] let sigmoid1 value = 1.0f/(1.0f + exp(-value)); let sigmoid2 v = if (v <= Min) then 0.0f; elif (v>= Max) then 1.0f; else let f = v * Scale; if (v>0.0f) then lut.[int (f + 0.5f)] else 1.0f - lut.[int(0.5f - f)]; let getError f = let test = range 0.00001f -10.0f 10.0f; let errors = seq { for v in test -> abs(sigmoid1(single(v)) - f(single(v))) } Seq.max errors; open System.Diagnostics; let test f = let sw = Stopwatch.StartNew(); let mutable m = 0.0f; let result = for t in 1 .. 10 do for x in 1 .. 1000000 do m <- f(single(x)/100000.0f-5.0f); sw.Elapsed.TotalMilliseconds; printf "Max deviation is %f\n" (getError sigmoid2) printf "10^7 iterations using sigmoid1: %f ms\n" (test sigmoid1) printf "10^7 iterations using sigmoid2: %f ms\n" (test sigmoid2) let c = System.Console.ReadKey(true); And the output (Release compilation against F# 1.9.6.2 CTP with no debugger): Max deviation is 0.001664 10^7 iterations using sigmoid1: 588.843700 ms 10^7 iterations using sigmoid2: 156.626700 ms UPDATE: updated benchmarking to use 10^7 iterations to make results comparable with C UPDATE2: here are the performance results of the C implementation from the same machine to compare with: Max deviation is 0.001664 10^7 iterations using sigmoid1: 628 ms 10^7 iterations using sigmoid2: 157 ms Note: This is a follow-up to this post. Edit: Update to calculate the same thing as this and this, taking some inspiration from this. Now look what you made me do! You made me install Mono! $ gmcs -optimize test.cs && mono test.exe Max deviation is 0.001663983 10^7 iterations using Sigmoid1() took 1646.613 ms 10^7 iterations using Sigmoid2() took 237.352 ms C is hardly worth the effort anymore, the world is moving forward :) So, just over a factor 10 6 faster. Someone with a windows box gets to investigate the memory usage and performance using MS-stuff :) Using LUTs for activation functions is not so uncommon, especielly when implemented in hardware. There are many well proven variants of the concept out there if you are willing to include those types of tables. However, as have already been pointed out, aliasing might turn out to be a problem, but there are ways around that too. Some further reading: - NEURObjects by Giorgio Valentini (there's also a paper on this) - Neural networks with digital LUT activation functions - Boosting neural network feature extraction by reduced accuracy activation functions - A New Learning Algorithm for Neural Networks with Integer Weights and Quantized Non-linear Activation Functions - The effects of quantization on high order function neural networks Some gotchas with this: - The error goes up when you reach outside the table (but converges to 0 at the extremes); for x approx +-7.0. This is due to the chosen scaling factor. Larger values of SCALE give higher errors in the middle range, but smaller at the edges. - This is generally a very stupid test, and I don't know C#, It's just a plain conversion of my C-code :) - Rinat Abdullin is very much correct that aliasing and precision loss might cause problems, but since I have not seen the variables for that I can only advice you to try this. In fact, I agree with everything he says except for the issue of lookup tables. Pardon the copy-paste coding... using System; using System.Diagnostics; class LUTTest { private const float SCALE = 320.0f; private const int RESOLUTION = 2047; private const float MIN = -RESOLUTION / SCALE; private const float MAX = RESOLUTION / SCALE; private static readonly float[] lut = InitLUT(); private static float[] InitLUT() { var double TestPerformancePlain() { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10; i++) { for (float x = -5.0f; x < 5.0f; x+= 0.00001f) { Sigmoid1(x); } } sw.Stop(); return sw.Elapsed.TotalMilliseconds; } public static double TestPerformanceLUT() { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10; i++) { for (float x = -5.0f; x < 5.0f; x+= 0.00001f) { Sigmoid2(x); } } sw.Stop(); return sw.Elapsed.TotalMilliseconds; } static void Main() { Console.WriteLine("Max deviation is {0}", TestError()); Console.WriteLine("10^7 iterations using Sigmoid1() took {0} ms", TestPerformancePlain()); Console.WriteLine("10^7 iterations using Sigmoid2() took {0} ms", TestPerformanceLUT()); } } First thought: How about some stats on the values variable? - Are the values of "value" typically small -10 <= value <= 10? If not, you can probably get a boost by testing for out of bounds values if(value < -10) return 0; if(value > 10) return 1; - Are the values repeated often? If so, you can probably get some benefit from Memoization (probably not, but it doesn't hurt to check....) if(sigmoidCache.containsKey(value)) return sigmoidCache.get(value); If neither of these can be applied, then as some others have suggested, maybe you can get away with lowering the accuracy of your sigmoid... Soprano had some nice optimizations your call: public static float Sigmoid(double value) { float k = Math.Exp(value); return k / (1.0f + k); } If you try a lookup table and find it uses too much memory you could always looking at the value of your parameter for each successive calls and employing some caching technique. For example try caching the last value and result. If the next call has the same value as the previous one, you don't need to calculate it as you'd have cached the last result. If the current call was the same as the previous call even 1 out of a 100 times, you could potentially save yourself 1 million calculations. Or, you may find that within 10 successive calls, the value parameter is on average the same 2 times, so you could then try caching the last 10 values/answers. Idea: Perhaps you can make a (large) lookup table with the values pre-calculated? This is slightly off topic, but just out of curiosity, I did the same implementation as the one in C, C# and F# in Java. I'll just leave this here in case someone else is curious. Result: $ javac LUTTest.java && java LUTTest Max deviation is 0.001664 10^7 iterations using sigmoid1() took 1398 ms 10^7 iterations using sigmoid2() took 177 ms I suppose the improvement over C# in my case is due to Java being better optimized than Mono for OS X. On a similar MS .NET-implementation (vs. Java 6 if someone wants to post comparative numbers) I suppose the results would be different. Code: public class LUTTest { private static final float SCALE = 320.0f; private static final int RESOLUTION = 2047; private static final float MIN = -RESOLUTION / SCALE; private static final float MAX = RESOLUTION / SCALE; private static final float[] lut = initLUT(); private static float[] initLUT() { float[] long sigmoid1Perf() { float y = 0.0f; long t0 = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { for (float x = -5.0f; x < 5.0f; x+= 0.00001f) { y = sigmoid1(x); } } long t1 = System.currentTimeMillis(); System.out.printf("",y); return t1 - t0; } public static long sigmoid2Perf() { float y = 0.0f; long t0 = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { for (float x = -5.0f; x < 5.0f; x+= 0.00001f) { y = sigmoid2(x); } } long t1 = System.currentTimeMillis(); System.out.printf("",y); return t1 - t0; } public static void main(String[] args) { System.out.printf("Max deviation is %f\n", testError()); System.out.printf("10^7 iterations using sigmoid1() took %d ms\n", sigmoid1Perf()); System.out.printf("10^7 iterations using sigmoid2() took %d ms\n", sigmoid2Perf()); } } I realize that it has been a year since this question popped up, but I ran across it because of the discussion of F# and C performance relative to C#. I played with some of the samples from other responders and discovered that delegates appear to execute faster than a regular method invocation but there is no apparent peformance advantage to F# over C#. - C: 166ms - C# (delegate): 275ms - C# (method): 431ms - C# (method, float counter): 2,656ms - F#: 404ms The C# with a float counter was a straight port of the C code. It is much faster to use an int in the for loop. You might also consider experimenting with alternative activation functions which are cheaper to evaluate. For example: f(x) = (3x - x**3)/2 (which could be factored as f(x) = x*(3 - x*x)/2 for one less multiplication). This function has odd symmetry, and its derivative is trivial. Using it for a neural network requires normalizing the sum-of-inputs by dividing by the total number of inputs (limiting the domain to [-1..1], which is also range). A mild variation on Soprano's theme: public static float Sigmoid(double value) { float v = value; float k = Math.Exp(v); return k / (1.0f + k); } Since you're only after a single precision result, why make the Math.Exp function calculate a double? Any exponent calculator that uses an iterative summation (see the expansion of the ex) will take longer for more precision, each and every time. And double is twice the work of single! This way, you convert to single first, then do your exponential. But the expf function should be faster still. I don't see the need for soprano's (float) cast in passing to expf though, unless C# doesn't do implicit float-double conversion. Otherwise, just use a real language, like FORTRAN... There are a lot of good answers here. I would suggest running it through this technique, just to make sure - You're not calling it any more times than you need to. (Sometimes functions get called more than necessary, just because they are so easy to call.) - You're not calling it repeatedly with the same arguments (where you could use memoization) BTW the function you have is the inverse logit function, or the inverse of the log-odds-ratio function log(f/(1-f)). (Updated with performance measurements)(Updated again with real results :) I think a lookup table solution would get you very far when it comes to performance, at a negligible memory and precision cost. The following snippet is an example implementation in C (I don't speak c# fluently enough to dry-code it). It runs and performs well enough, but I'm sure there's a bug in it :) #include <math.h> #include <stdio.h> #include <time.h> #define SCALE 320.0f #define RESOLUTION 2047 #define MIN -RESOLUTION / SCALE #define MAX RESOLUTION / SCALE static float sigmoid_lut[RESOLUTION + 1]; void init_sigmoid_lut(void) { int i; for (i = 0; i < RESOLUTION + 1; i++) { sigmoid_lut[i] = (1.0 / (1.0 + exp(-i / SCALE))); } } static float sigmoid1(const float value) { return (1.0f / (1.0f + expf(-value))); } static float sigmoid2(const float value) { if (value <= MIN) return 0.0f; if (value >= MAX) return 1.0f; if (value >= 0) return sigmoid_lut[(int)(value * SCALE + 0.5f)]; return 1.0f-sigmoid_lut[(int)(-value * SCALE + 0.5f)]; } float test_error() { float x; float emax = 0.0; for (x = -10.0f; x < 10.0f; x+=0.00001f) { float v0 = sigmoid1(x); float v1 = sigmoid2(x); float error = fabsf(v1 - v0); if (error > emax) { emax = error; } } return emax; } int sigmoid1_perf() { clock_t t0, t1; int i; float x, y = 0.0f; t0 = clock(); for (i = 0; i < 10; i++) { for (x = -5.0f; x <= 5.0f; x+=0.00001f) { y = sigmoid1(x); } } t1 = clock(); printf("", y); /* To avoid sigmoidX() calls being optimized away */ return (t1 - t0) / (CLOCKS_PER_SEC / 1000); } int sigmoid2_perf() { clock_t t0, t1; int i; float x, y = 0.0f; t0 = clock(); for (i = 0; i < 10; i++) { for (x = -5.0f; x <= 5.0f; x+=0.00001f) { y = sigmoid2(x); } } t1 = clock(); printf("", y); /* To avoid sigmoidX() calls being optimized away */ return (t1 - t0) / (CLOCKS_PER_SEC / 1000); } int main(void) { init_sigmoid_lut(); printf("Max deviation is %0.6f\n", test_error()); printf("10^7 iterations using sigmoid1: %d ms\n", sigmoid1_perf()); printf("10^7 iterations using sigmoid2: %d ms\n", sigmoid2_perf()); return 0; } Previous results were due to the optimizer doing its job and optimized away the calculations. Making it actually execute the code yields slightly different and much more interesting results (on my way slow MB Air): $ gcc -O2 test.c -o test && ./test Max deviation is 0.001664 10^7 iterations using sigmoid1: 571 ms 10^7 iterations using sigmoid2: 113 ms TODO: There are things to improve and ways to remove weaknesses; how to do is is left as an exercise to the reader :) - Tune the range of the function to avoid the jump where the table starts and ends. - Add a slight noise function to hide the aliasing artifacts. - As Rex said, interpolation could get you quite a bit further precision-wise while being rather cheap performance-wise. There are a much faster functions that do very similar things: x / (1 + abs(x)) – fast replacement for TAHN And similarly: x / (2 + 2 * abs(x)) + 0.5 - fast replacement for SIGMOID Compare plots with actual sigmoid Doing a Google search, I found an alternative implementation of the Sigmoid function. public double Sigmoid(double x) { return 2 / (1 + Math.Exp(-2 * x)) - 1; } Is that correct for your needs? Is it faster? 1) Do you call this from only one place? If so, you may gain a small amount of performance by moving the code out of that function and just putting it right where you would normally have called the Sigmoid function. I don't like this idea in terms of code readability and organization but when you need to get every last performance gain, this might help because I think function calls require a push/pop of registers on the stack, which could be avoided if your code was all inline. 2) I have no idea if this might help but try making your function parameter a ref parameter. See if it's faster. I would have suggested making it const (which would have been an optimization if this were in c++) but c# doesn't support const parameters. If you need a giant speed boost, you could probably look into parallelizing the function using the (ge)force. IOW, use DirectX to control the graphics card into doing it for you. I have no idea how to do this, but I've seen people use graphics cards for all kinds of calculations. I've seen that a lot of people around here are trying to use approximation to make Sigmoid faster. However, it is important to know that Sigmoid can also be expressed using tanh, not only exp. Calculating Sigmoid this way is around 5 times faster than with exponential, and by using this method you are not approximating anything, thus the original behaviour of Sigmoid is kept as-is. public static double Sigmoid(double value) { return 0.5d + 0.5d * Math.Tanh(value/2); } Of course, parellization would be the next step to performance improvement, but as far as the raw calculation is concerned, using Math.Tanh is faster than Math.Exp. Need Your Help What exactly is a reentrant function? c++ c recursion thread-safety reentrancyMost of the times, the definition of reentrance is quoted from Wikipedia:
http://www.brokencontrollers.com/faq/412019.shtml
CC-MAIN-2019-47
refinedweb
3,852
57.67
guizero is a Python 3 library for creating simple GUIs. It is designed to allow new learners to quickly and easily create GUIs for their programs. from guizero import App, Text, PushButton app = App(title="guizero") intro = Text(app, text="Have a go with guizero and see what you can create.") ok = PushButton(app, text="Ok") app.display() If you can download and unzip a file, you can install guizero - no special permissions or administrator rights are required. If you have administrator rights and are connected to the internet, you can use pip to install guizero. Comprehensive documentation can be found at lawsie.github.io/guizero including: The aim of guizero is to make the process of creating simple GUIs quick, accessible and understandable for new learners. Contributions are very welcome - please see lawsie.github.io/guizero/contributing for notes, build and deployment instructions. All issues should be raised on github.com/lawsie/guizero/issues The authors of guizero have written a book for beginners which you can buy in print or download as a free PDF. Easy to install and easy to use. Hopefully there will be new widgets in the future but as it stands I would rate this as an outstanding tool to use. Documentation in a PDF format would really be cool to see. I have been through the excellent book available from this site or on the MagPi site and only wish more were available.
https://openbase.com/python/guizero
CC-MAIN-2021-39
refinedweb
240
57.37
IJ and CL to draft a proposal to address this issue. (No clear direction from 14 May 2004 minutes, but there was discussion about whether the content was "designed for presentation".) Write a draft finding on the benefits and limitations of the media type mechanism. Propose additional text regarding separation of content and presentation that includes more about tradeoffs. Propose three examples for section 3.3.2. Rewrite story at beginning of 3.3.1. See resolution to delete "Note..." to end of the paragraph. Draft text to explain that there's a tradeoff in this situation. Propose editorial response. Implemented: Did not implement: "Sect 4 is entitled 'Data Formats', and Sect 1, 3rd bullet has 'Formats'. Would suggest that both should be changed to 'Representation' in keeping with the 3 bases articulated in the Abstract (identification, interaction, representation). This shift in gears from representation to data formats is potentially confusing. Maybe within the section one could talk of data formats (as a more concrete realization of the abstraction 'representation'), but I think the section (and bullet) are better labeled at the more generic/abstract level." Rationale: We used to have that and then chose the current organization instead." Did not implement: "Almost all the Story examples seem to make use of HTTP URIs. Any chance of sneaking in some other URI schemes just here and there just to reinforce that the fact that this is a democrarcy not a monarchy? Perhaps even just a mailto, or urn, or something more exotic?" Rationale: "We have examples of other schemes. No need to use exotic schemes if not motivated by story. Did not implement: "Sect 2.4, 3rd para, 1st sentence, 'While the Web architecture...' - change 'is costly' to 'can be costly'?". Rationale: Not sure about this change. Did not implement: "Sect 2.4, 3rd para, 3rd sentence, 'Introducing a new URI scheme...' - change 'requires' to 'may require'?" Rationale: Not sure about this change. Did not implement: "Sect 2.4, last para, last sentence - 'When an agent does not handle a new URI scheme, it cannot retrieve a representation.' This seems prejudicial, as if the only intersting operations are retrieval. An agent can already make use of the identitiy afforded by a URI and comparison of URIs in applications such as merging of RDF graphs or of merging Topic Maps which identify resources by means of URIs." Rationale: Nonetheless, the statement is true. Did not implement: "Sect 3, last para ('Note') before Sect 3.1. I would strongly query the sentence 'Informally, a resource is "on the Web" when it has a URI and an agent can use the URI to retrieve a representation of it ...'. I would rather say that a resource is "on the Web" when it is referenced by means of a URI. That would seem to me to be a full and sufficient condition. A resource referenced by a URI participates within the Web information space and assertions can be made about that resource." Rationale: The TAG did not agree to that definition. Did not implement: "Sect 3.6.2, 1st para. Should clarify here that 'URI persistence' actualy refers to persistence of the referenced resource, not to the URI. (That point is made in the [Cool] reference entry but should be made here and not in the refrence section.)" Rationale: Having reread the sentence, I don't believe that's necessary. It's defined clearly. Did not implement: "Sect 4.5.5, 1st para, 2nd sentence. 'A qualified name is a pair consisting of a URI,..., and a local name...' Surely the qualified name itself consists of a 'prefix' which represents the URI (i.e. is a URI placeholder), and a local name?" Rationale: I think that's a qname rather than a qualified name. Propose editorial response. In section 2.1, changed title of constraint to URI multiplicity. Incorporate TAG resolution. Deleted the "URI multiplicity" constraint from the beginning of 2.1. This text was moved (as an ordinary sentence) to the new subsection: URI/Resource Relationships. Ask reviewer if satisfied. Propose editorial response. Incorporated all of reviewer's suggestions. Incorporated editorial suggestions. Substitute "namespace representation" for "namespace document". The TAG discussed this edit briefly at their 12 May 2004 ftf meeting. There was no resolution, but the editor suspects that the change will be undone in subsequent drafts along with other changes regarding "information resources". New proposal First two paras edited so description of XML Namespaces has changed. Ask the commenter if the definition in context (in section 3.1) explains the way we use the terms to his satisfaction. [Empty] Inform reviewer of TAG's decision. [Empty] Inform reviewer of TAG's decision. Changed "unreliable" to "unpredictable" in 3.6 story. At their 13 May 2004 ftf meeting, the TAG discussed the use of both terms (unreliable and unpredictable) but did not come to a clear (revised) resolution. Updated proposal 404 example included; both "reliable" and "unpredictable" used. Inform reviewer of TAG's decision. Created subsection 3.5.1 to distinguish topics of safe interaction and paper trail. The TAG asked the Editor to edit this section to say that: Respond to reviewer's comment that HTTP PUT/POST/DELETE do not work with URIs with fragment identifiers since HTTP does not give access to the secondary resource. In section 3.3.1, included "Note also that since dereferencing a URI (e.g., using HTTP) does not involve sending a fragment identifier to a server or other agent, certain access methods (e.g., HTTP PUT, POST, and DELETE) cannot be used to interact with secondary resources." At their 13 May 2004 ftf, the TAG rejected the proposed text and asked the Editor to remove the sentence from the document. Fix grammatical error in definition of "secondary resource" in section 5. Fixed grammatical error. Propose editorial response. Agreed with reviewer; fixed text at beginning of section 2. Remove the middle bullet from 2.3. No more large number discussion. Left in mid/cid as examples where there is hierarchical delegation. Note the rationale for establishing uri/social entity relationship: "It is useful for a URI scheme to...". Not sure if that is sufficient.... Propose editorial response. Adopted reviewer's suggested text in section 2.7.2 (third para). However, after 7 June 2004 teleconf, deleted the proposed paragraph. Propose editorial response. Adopted reviewer's suggestion to change "electronic data" to "data" in section 3.2. Propose editorial response. Eliminated unused concepts and reduced section 1.1.3. Reviewer satisfied. Propose editorial response. Did not change Error recovery GPN in section 1.2.3 per reviewer's suggestion, but text changed based on other comments. The TAG believes that distinguishing "error correction" (errors that can be corrected as though they never happened) from "error recovery" (situations where the agent cannot correct the error) will improve the text. IJ to incorporate that change. Incorporate change into text. Extended language: A+B. Extension: B Add a second paragraph to 1.2.4 explaining what TBL said about resilience as typical design goal in protocols. Modified first paragraph to talk more about large-scale protocols v. traditional software APIs. Propose editorial response. In section 4.1, changed text in second para to "Increasingly, internationalized textual data formats refer to the Unicode repertoire [UNICODE] for character definitions." Propose editorial response. Adopted reviewer suggestion in principle of section 3.4.1 (consistent with other changes regarding authoritative metadata). Reviewer satisfied. The TAG asked the Editor to compress sections 3.4 and 3.4.1 into a single section 3.4. The title of the section will be "Message semantics". Reviewer satisfied. Discussion of "authoritative metadata" removed in favor of limiting discussion to that about data/metadata inconsistencies. Reviewer's comment about protocol semantics may be captured by first para. Propose editorial response. Attempted to following reviewer's suggestions. Eliminated "resource owner" in favor of "URI owner". Similarly, changed "user agent" to "agent" in GPNs. Changed "author" to "content author", "server manager" to "representation provider", and "developer" to "software developer". In the GPNs, changed "language designer" and "format designer" to "Specification" (as the subject). Moved note about format v. language to section 1.1.1 and introduced phrase "specification designer" as an encompassing term. Reviewer satisfied. Propose editorial response. Created a summary; probably not quite what reviewer wants. Propose editorial response. Added forward reference in section 3.6.1 per reviewer suggestion. Moved story from beginning of section 3.5 to a few paragraphs in. Moved one sentence from 3.5 story to section 3.5.1 story. Incorporated other editorial suggestions except the definition of Link in section 5. Subsumed. The word "understood" has been deleted in the rewrite. Address reviewer's comments (see DC action). Added "One particularly useful mapping in the case of flat namespaces is to combine the namespace URI, a hash ("#"), and the local name; see the section on XML namespaces for more examples." Propose editorial response. Changed titles of GPNs that reviewer wished changed. Now only using principle, constraint, good practice (in that order). Also highlighted in abstract. Ask the reviewer to clarify the question. The TAG believe the reviewer has misunderstood the notion of "URI persistence". [Empty] Propose editorial response. No change. It is probably useful to have a URI for a resource where language is content-negotiated, but it is also useful to have a URI for the "resource in language L". Add some text that talks about content negotiation in addition to leaving the distinct URIs (one per language resource). Deleted the language-specific URIs since they do not identify the same resource. Deleted the example but augmented the discussion of content negotiation per the 14 May ftf meeting. Propose editorial response. In section 3.4, Added "or transformed dynamically to the hardware or software capabilities of the recipient". Add text to the document about media type limitations, versioning, and link to issue mediaTypeManagement-45. Added: "Internet media type mechanism does have its limitations. For instance, media type strings do not support versioning or other parameters. The TAG issue mediaTypeManagement-45 concerns the appropriate level of granularity of the media type mechanism." Include a reference to RFC2396 in the document. Inform reviewer of TAG's resolution. Included reference to RFC2396 definitions of primary and secondary resource. Respond to reviewer. Incorporate DC suggested tweak for section 2:"Formats that allow content authors to use URIs instead of local identifiers foster the "network effect": the value of these formats grows with the size of the deployed Web." Incorporated. Propose editorial response. Good practice note in section 1.2.3 no longer talks about "silent recover" but rather recovery "without user consent". Added text from finding: "Consent does not necessarily imply that the receiving agent must interrupt the user and require selection of one option or another. The user may indicate through pre-selected configuration options, modes, or selectable user interface toggles, with appropriate reporting to the user when the agent detects an error." Updated GPN in section 3.4.1 as well. Updated proposal Distinguish error correction from error recovery. Propose editorial response. Attempt to soften claim about cost of overloading by adding "often" in first paragraph of section 2.2. Updated proposal Issue may be subsumed and mooted by this draft. Propose editorial response. I believe that edits to section 3.4 may satisfy the reviewer's comments; that text has been removed. Propose editorial response. Edited sentence in section 2: "Formats that allow content authors to use URIs instead of local identifiers foster the "network effect": the value of these formats grows with the size of the deployed Web." Propose editorial response. In section 2.1.1, added last paragraph: "When a URI alias does become common currency, the URI owner should use protocol techniques such as server-side redirects to connect the two resources. The community benefits when the URI owner supports both the "unofficial" URI and the alias.". Propose editorial response. This draft addresses the reviewer's editorial comments. The Editor believes this question is answered by the draft. The Editor believes this question is answered by the draft: The string is compared character for character, and a URI string can include a fragment identifier. Propose editorial response. Removed contentious text from section 4.3. Text now reads: "Of course, it may not always be desirable to reach the widest possible audience. Designers should consider appropriate technologies for limiting the audience. For instance digital signature technology, access control, and other technologies are appropriate for controlling access to content." Incorporate TAG's resolution. Propose editorial response. This draft incorporates reviewer's editorial suggestions. Propose editorial response. Good practice note in section 1.2.3 no longer talks about "silent recover" but rather recovery "without user consent". Updated proposal Distinguish error correction from error recovery. Paste RFC2396 text in and ask the Schema WG to review. In section 3.3.2, Added some text from RFC2396 bis per 3 May teleconf. The new text does NOT say "don't use content negotiation". Delete "falling back to default behavior." Deleted "falling back to default behavior" in section "Extensibility" Insert a story in the section on extensibility about protocol extensibility. Propose editorial response. Per 22 March teleconf, deleted "that can be understood in any context" from section 4.5.3. Incorporate changes per resolution. Propose editorial response. Adopted reviewer's proposal in section 4.5.3 to use "xsi:type". Make changes to point to XML Schema spec (possibly with the xsi ns URI in text). Para now starts: "The type attribute from the W3C XML Schema Instance namespace "" ([XMLSCHEMA], section 4.3.2) is an example of a global attribute. It can be used by authors of any vocabulary to make an assertion in instance data about the type of the element on which it appears. As a global attribute, it must always be fully qualified. " Propose editorial response. Adopted reviewer's proposal in section 4.5.3: "An attribute that is "global," that is, one that might meaningfully appear on elements of any type, including elements in other namespaces, should be explicitly placed in a namespace. Local attributes, ones associated with only a particular element type, need not be included in a namespace since their meaning will always be clear from the context provided by that element." Clarify that this is an open issue. In section 4.5.6, added note: "The TAG expects to continue to work with other groups to help resolve open questions about establishing "ID-ness" in XML formats." Also added fourth bullet per reviewer's suggestion. Adopt text per TAG resolution. New fourth bullet: "In practice, applications may have independent means (such as those defined in the XPointer specification, [XPTRFR] section 3.2) of locating identifiers inside a document." Propose editorial response. Adopted editorial suggestions except: Propose editorial response. Adopted editorial suggestion. Might be subsumed. Might be subsumed by new text in 2 and 2.1 Might be subsumed. Might be subsumed by new text in 2 and 2.1 Revise the text of section 3.3.2 per the resolution. The editor notes that the future of the GPN in that section is uncertain. Replace constraint at beginning of section 2 with a new principle and constraint: Improve text regarding responsibility for inconsistent frag id semantics (looking at new RFC2396 text). Add text from RFC2396. In section 3.3.1 added text from RFC2396. Also deleted: "On the other hand, it is considered an error if the semantics of the fragment identifiers used in two representations of a secondary resource are inconsistent." Incorporate TAG resolution. Incorporate resolution into section 3.6.2 Incorporate resolution. Third bullet changed to: "The semantics of combining RDF documents containing multiple vocabularies is well-defined." Create new section 4.6 New section created: "Data Formats Used to Build New Information Space Applications" Edit "Parties that draw...." to be about drawing conclusions from syntactic analysis. Adopt reviewer proposal. GPN now reads: "A data format specification SHOULD provide for version information." Delete "As part of defining ..." sentence. Deleted "As part of defining an extensibility mechanism, specification designers should set expectations about agent behavior in the face of unrecognized extensions." Comment addressed by this draft. Comment addressed by this draft. Merge sections 2 and 2.1 Deleted the example since these two URIs identify two different resources. This was part of a series of other changes to these early subsections of section 2. However, see section 3.3.2 for additional information on content negotiation. Send TAG a draft of a response to Hammond review in light of TAG's discussion. Inform reviewer of TAG's decision. Send TAG a draft of a response to reviewer in light of decision. Propose text on tradeoffs for section 4.2.2. Write some text to address schema14 (e.g., by reviewing finding). The TAG agreed with the proposal to add "necessarily". Respond to Tom Worthington, talking about arch doc / findings balance, and pointing out that we are not creating a point-form architectural thesis. [Empty] [Empty] Respond to MD, acknowledging the dependency between arch doc and RFC2396bis. See Reply from MD Propose text for this issue. There is general support for a visibility principle. Propose to the TAG a reponse to P. Stickler's message. [Empty] Respond to DB on TAG's choice of agent - the status quo..
http://www.w3.org/2001/tag/2003/lc1209/actions_owner.html
CC-MAIN-2016-30
refinedweb
2,892
52.97
One of my friends wanted to know "How to calculate the time complexity of a given algorithm". My obvious answer to him was... "Why do YOU want to calculate it?. There are tools available that do it for you!!" (E.g. Analyze menu in VS Team Suite, NDepend are a few). Well... I don't want to say what his answer was, but he wanted to know :-) In my personal view, it's a good to know "cool" thing, but not really required for ALL. With that note, let me write a small program and calculate the time complexity for it. Here is a sample code to remove an invalid character from an array. 1: namespace TimeComplexity 2: { 3: class Program 4: { 5: static void Main(string[] args) 6: { 7: char[] arr = { 'a', 'b', 'b', 'd', 'e' }; 8: char invalidChar = 'b'; 9: int ptr = 0, N = arr.Length; 10: for (int i = 0; i < n; i++) 11: { 12: if (arr[i] != invalidChar) 13: { 14: arr[ptr] = arr[i]; 15: ptr++; 16: } 17: } 18: 19: for (int i = 0; i < ptr; i++) 20: { 21: Console.Write(arr[i]); 22: Console.Write(' '); 23: } 24: Console.ReadLine(); 25: } 26: } 27: } Output for the above code will look like a d e Let's look at each loop one at a time. That's the key; you calculate the time complexity for each loop 1: for (int i = 0; i < N; i++) 3: if (arr[i] != invalidChar) 5: arr[ptr] = arr[i]; 6: ptr++; 7: } 8: } The above Code snippet contains a lot of basic operations which will be repeated. (That's why it's called a loop.. duh !!). The basic operations it contains are Note: I considered the worst case scenario and am calculating the Worst Case Time Complexity for the above code So the number of operations required by this loop are {1+(N+1)+N}+N+N+N = 5N+2 The part inside the curly braces is the time consumed by Loop alone (i.e.. for(int i =0;i<N;i++)), it is 2N+2. Keep this mind; it is usually the same (unless you have a non-default FOR loop) Now for the second loop 1: for (int i = 0; i < ptr; i++) 3: Console.Write(arr[i]); 4: Console.Write(' '); 5: } Remember, a loop takes 2N+2 iterations. So, here it will take 2ptr+2 operations. Again, considering the worst case scenario ptr will be N so the above expression evaluates to (again) 2N+2. Then there are these additional 2 operations of Console.Write with will be executed N times each (Again, worst case scenario). So the above code snippet will take {1+(N+1)+N}+N+N = 4N+2 Oh.. I almost forgot the other statements Note: The character array initialization will actually execute N times. This is because you are assigning one character at a time. So the rest of the code requires N+4 Adding everything up I get (N+4)+(5N+2)+(4N+2) = 10N+8 So the asymptotic time complexity for the above code is O(N), which means that the above algorithm is a liner time complexity algorithm. There you have it, now you know how to calculate the time complexity of a simple program.
http://blogs.msdn.com/b/nmallick/archive/2010/03/30/how-to-calculate-time-complexity-for-a-given-algorithm.aspx
CC-MAIN-2013-48
refinedweb
544
72.46
I recently became very interested in the Neo4j graph database:, as I'm working on data structures that are hierarchical and tricky to walk in a relational database. I came across an interesting video presentation on neo4j by Ian Robinson on the skillsmatter website -. He and colleagues have put together a database of facts from the Doctor Who British TV series. That's when I became aware that he, Jim Webber and some other colleagues created set of Neo4j koans available on github:. So I decided to tackle my first ever set of koans. Soon after, I discovered that while Jim Webber and crew put in a lot of time creating the neo4j koan tutorial, they seem to have to put in little time on how a newbie to koans can actually run them - at least as of November 2011 when I downloaded it. I don't understand why you would put hours into it and not put a few minutes into documenting what to do. Please provide a README on how to do things like this. If you go to all the effort of creating it, why wouldn't you? [Dec 2011 Update: There is now good starter info on the neo4j koan github site, so many thanks to Jim et al. for improving it!] So in case it helps anyone else, here is my version of how I fumbled around to do the neo4j koans. /* ---[ Getting the Koans Installed and Set up ]--- */ These instructions are targeted particularly for a Unix/Linux environment. My koan work was done on Linux (Xubuntu 11.10). I also tested them on Windows where I have Mingw32 that comes with the git download (and I have cygwin). [Dec 2011 Update: The neo4j koan github site now says it will work with cygwin on Windows - they actually say "sorry" about this, but being a Unix/Linux devotee my advice is that if you don't have cygwin yet, this is a good reason to get it and learn it. Consider it a bonus to learn a better way of doing things.] I'm also primarily a command line kind of guy, though I do also use Eclipse for many things. In this case, I went commando - so I didn't use Eclipse's JUnit integration or download the neoclipse plug in (which sounds cool -- need to try it someday). First download it from github (URL above). Be aware that the download is around 350 MB, so it may take a awhile if you have a lower-speed internet connection like me. Second, cd to the main directory (neo4j-tutorial) and type ant - this will run ivy and download half the known universe in good ivy/maven fashion (grrr...). After waiting about an hour (or less if you have a better internet connection than me), you can begin by wondering what to do next. First make sure the build ran to successful completion - happily the koans as unit tests all passed out of the box for me, so you want to make sure that is all working on your system before beginning. The authors provide a presentation in the presentation directory (for some reason in ppt and not converted to pdf for more general viewing), which can be helpful, but wasn't enough to really know how to do the koans. I recommend coming back to the presentation periodically and reviewing it for the section you are working on. Some of its visuals and notes are helpful, but mostly you'll just need to read the codebase and neo4j javadocs to really know how to get things done. Next run the tree command to get a look around (you may need to download tree - its a great Unix command line tool to see files/dirs in a compact tree structure). You'll see that the koans are in the src directory (output from the tree cmd): ├── src │ ├── koan │ │ └── java │ │ └── org │ │ └── neo4j │ │ └── tutorial │ │ ├── Koan01.java │ │ ├── Koan02.java │ │ ├── Koan03.java │ │ ├── Koan04.java │ │ ├── Koan05.java │ │ ├── Koan06.java │ │ ├── Koan07.java │ │ ├── Koan08a.java │ │ ├── Koan08b.java │ │ ├── Koan08c.java │ │ ├── Koan09.java │ │ ├── Koan10.java │ │ ├── Koan11.java and if you look into them, you'll see comments and snippet sections that say "your code here", but the come pre-filled in with the answers. However, if you go into the src/main/scripts directory you'll notice a a "release.sh" script, which extracts the relevant portion of the koans from the current github dir and copies it to a temp directory and runs the remove_snippets script. However I couldn't get it to work after 15 minutes of futzing with it and the documentation for it is basically useless. [Dec 2011 Update: I tried it again and it works now for me. Either I did something wrong the first time or Jim Webber tweaked it.] There is also a remove_snippets.sh. You can run that directly - you are supposed to do it from the top-level dir, not the scripts directory. Either way I got an error message. But it does work if you run it from the top level dir, despite the error message. Here's what I got: $ src/main/scripts/remove_snippets.sh sed: can't read : No such file or directory $ git st M src/koan/java/org/neo4j/tutorial/Koan02.java M src/koan/java/org/neo4j/tutorial/Koan03.java M src/koan/java/org/neo4j/tutorial/Koan04.java M src/koan/java/org/neo4j/tutorial/Koan05.java M src/koan/java/org/neo4j/tutorial/Koan06.java M src/koan/java/org/neo4j/tutorial/Koan07.java M src/koan/java/org/neo4j/tutorial/Koan08a.java M src/koan/java/org/neo4j/tutorial/Koan08b.java M src/koan/java/org/neo4j/tutorial/Koan08c.java M src/koan/java/org/neo4j/tutorial/Koan09.java M src/koan/java/org/neo4j/tutorial/Koan10.java M src/koan/java/org/neo4j/tutorial/Koan11.java (git st is aliased to git status -s on my machine) So it did modify the Koans and remove the parts I'm supposed to fill in. After doing this, I recommend doing git reset --hard to get back the filled in koans. Copy them to another directory, so you can peek at them when you are doing the koans in case you get stuck or want to compare your solution with the official one. Then run the remove_snippets.sh script again and do a git add and git commit. Now we are ready to start the koans (whew!). /* ---[ Doing the Koans ]--- */ The koans are unit tests. After you run the remove_snippets script, all the koan unit tests will fail (except for Koan01, which for some reason has no snippet for you to replace - it is a just a reading koan, not a doing koan, I guess). You need to fix the koans one by one and get each test passing. Unfortunately, I couldn't find a way to run each test separately, you have to do the full battery, plus the annoying-as-hell ivy checks. <rant>Speaking of which, you won't be able to run these tests while offline, even after you've download everything via ivy. This is my biggest complaint about the ivy/maven model. I frequently want to do offline working, so I curse setups that require everything to be done via ivy/maven.</rant> One way you can sift through all the noise of the output is to run this unit tests like this: $ ant | grep Koan11 Then you will just get the output of Koan11 (though you have to run everything unless you want to edit the Ant build.xml file), like this: $ ant | grep Koan11 [junit] Running org.neo4j.tutorial.Koan11 [junit] TEST org.neo4j.tutorial.Koan11 FAILED [junit] Tests FAILED BUILD FAILED /home/midpeter444/java/projects/neo4j-koans/neo4j-tutorial/build.xml:68: Build failed due to Koan failures I also found context lines and simple pattern matching to help, such as: $ ant | grep -C 4 Koan0[123] /* ---[ Only Running the Tests You Want ]--- */ As I said, there is no target in the ant file (or any helper scripts) to only run one test/koan at a time. And each one takes many seconds, so the whole thing can take well over a minute (depending on machine speed). To do the easiest thing that would work, I issued the following command (you could do it with sed if you don't have perl installed): find src/koan/java -name Koan*.java -print | xargs perl -pi -e "s/([@]Test)/\/\/\1/g" It just comments out all the @Test annotations in the Koan files. Run this once at the beginning. Then you can remove the comments from each test as you are working on them. So the ant file stills runs all the koans, but they don't take very long if you haven't uncommented them. /* ---[ Reading the error report output ]--- */ Don't make the same mistake I did spending lots of time going through target/koan/reports/TESTS-TestSuites.xml output. I later found that a nice html report is provided one more directory down. Open the target/koan/reports/output/index.html in your browser and refresh after each test - this is very nice! So the cycle is: 1. Edit the Koan test until you are ready to run (uncomment that one's @Test annotation) 2. Run: ant | grep -C 4 Koan0[34] (modify the numbers as needed) 3. Refresh target/koan/reports/output/index.html in your browser and refresh after each test. Note also that if you debug by printing to stdout, there is a link on the index.html output to view it - use that as needed. Finally, I wrote a little helper class that will print out all the properties and values of a Node - this is helpful in debugging. Here is the code: package org.neo4j.tutorial; import org.neo4j.graphdb.Node; public class NodePP { public static String pp(Node n) { String s = "Node: "; for (String k: n.getPropertyKeys()) { s += String.format("\n %s: %s", k, n.getProperty(k)); } return s; } } Complaints aside, I'm currently finishing Koan08c and I recommend them as a good way to learn neo4j and think in terms of graphs. And so far, I really like the cypher query language.... [Dec 2011 Update:] I've finished them all now. Since I only broke down and cheated once by looking at the pre-filled in version (Koan11 was a doozy), it took me a while, but I feel like I have a very good sense of how to use neo4j now. The koans provide great coverage of the approaches to using the database. Neo4j is a very promising database and I think it is a serious player in the NoSQL space. The next question for me is how to use it with one's domain model in POJOs. I see four options: - Serialize/deserialize POJOs to/from JSON and use the neo4j REST API. This will be less performant, but is the option if you are using a standalone database server. - Make your POJOs Neo-aware - have them wrap Nodes and Relationship and keep their attributes in neo Node/Relationship properties. This obviously tightly couples your domain to your persistance layer. - Use CQL (cypher query language) like you do SQL when not using an ORM. Cypher is very nice and well thought out. I wonder how hard it would be to construct a MyBatis-like mapper between Cypher and your POJOs. - Use the Spring Data Neo4j annotation bindings for neo4j. This looks promising. I've started looking at it, but no strong opinion yet. They do say that it will be less performant than directly using the direct neo4j API (such as the Traversal API), as there is metaprogramming (Java Reflection API usage) going on.
http://thornydev.blogspot.com/2011/11/
CC-MAIN-2017-22
refinedweb
1,966
72.16
link - link to a file #include <unistd.h> int link(const char *path1, const char *path2); The link() function shall create a new link (directory entry) for the existing file, path1. The path1 argument points to a pathname naming an existing file. The path2 argument points to a pathname naming the new directory entry to be created. The link() function shall atomically create a new link for the existing file and the link count of the file shall be incremented by one. If path1 names a directory, link() shall fail unless the process has appropriate privileges and the implementation supports using link() on directories. shall fail if: - [EACCES] - A component of either path prefix denies search permission, or the requested link requires writing in a directory that denies write permission, or the calling process does not have permission to access the existing file and this is required by the implementation. - [EEXIST] - The path2 argument resolves to an existing file or refers to a symbolic link. - [ELOOP] - A loop exists in symbolic links encountered during resolution of the path1 or path2 argument. - [EMLINK] - The number of links to the file named by path1 would exceed {LINK_MAX}. - [ENAMETOOLONG] - The length of. - [EPERM] - The file named by path1 is a directory and either the calling process does not have appropriate privileges or the implementation prohibits using link() on directories. - [EROFS] - The requested link requires writing in a directory on a read-only file system. - [EXDEV] - The link named by path2 and the file named by path1 are on different file systems and the implementation does not support links between file systems. - [EXDEV] - }. Creating a Link to a File The following example shows how to create a link to a file named /home/cnd/mod1 by creating a new directory entry named /modules/pass1.#include <unistd.h> char *path1 = "/home/cnd/mod1"; char *path2 = "/modules/pass1"; int status; ... status = link (path1, path2); Creating a Link to a File Within a Program In the following program example, the link() function links the /etc/passwd file (defined as PASSWDFILE) to a file named /etc/opasswd (defined as SAVEFILE), which is used to save the current password file. Then, after removing the current password file (defined as PASSWDFILE), the new password file is saved as the current password file using the link() function again.#include <unistd.h> #define LOCKFILE "/etc/ptmp" #define PASSWDFILE "/etc/passwd" #define SAVEFILE "/etc/opasswd" ... /* Save current password file */ link (PASSWDFILE, SAVEFILE); /* Remove current password file. */ unlink (PASSWDFILE); /* Save new password file as current password file. */ link (LOCKFILE,PASSWDFILE); Some implementations do allow links between file systems. Linking to a directory is restricted to the superuser in most historical implementations because this capability may produce loops in the file hierarchy or otherwise corrupt the file system. This volume of IEEE Std 1003.1-2001 continues that philosophy by prohibiting link() and unlink() from doing this. Other functions could do it if the implementor designed such an extension. Some historical implementations allow linking of files on different file systems. Wording was added to explicitly allow this optional behavior. The exception for cross-file system links is intended to apply only to links that are programmatically indistinguishable from "hard" links. None. symlink(), unlink(),: - An explanation is added of the action when path2 refers to a symbolic link. - The [ELOOP] optional error condition is added.
http://pubs.opengroup.org/onlinepubs/009604499/functions/link.html
CC-MAIN-2018-30
refinedweb
559
53.92
We've moved over to using Mercurial at work (thank god; life in a post-CVS world it good!) so I've been playing around with that. I've used Git before so it's not been too painless - in fact I think the Windows integration and TortoiseHg tool are pretty good (which is one of the claimed benefits of using Mercurial over Git in a Windows environment, apparently). I've had a work-related idea that I've been trying to hash out that I've been doing mostly at home but playing round a bit with at work too. The Mercurial web server we've set up is for internal use only so I thought I'd try stuffing a repository into my Dropbox folder - since I already use that for some casual file sharing between work and home. The plan was to work on a local clone at home and at work and push / pull to the Dropbox repo as required. I'm far from the first person to think of this and initial research looked promising: Mercurial (hg) with Dropbox Personal Version Control with Mercurial + Dropbox I've been happily using this for a couple of weeks, it's only me doing the work - from home and from the office; doing my commits locally and pushing up at the end of the day or whenever. Then pulling and updating from my other PC. But this morning the pull request failed at work; something about integrity errors. I did more some reading around and ran "hg verify" against the repository in Dropbox and got back a dozen errors along the lines of SomeFile.cs@?: rev 5 points to unexpected changeset 26 .. which didn't really mean a lot to me, to be honest. I tried to find out how easy it would or wouldn't be to recover but didn't make major inroads and in the end decided I'd wait until I got home and checked my local clone, the one that I was pushing from to the Dropbox clone. That should be fine, right? Happily (and logically, from what I understand), the local clone was absolutely fine and "hg verify" reported no issues. Happy days! As I look further into it, there is more information recommending against this Mercurial (or Git) with Dropbox combination.. Using Mercurial with Dropbox Mercurial (and, I guess GIT) with Dropbox: any drawbacks? If this was purely a personal project that I was happy to share with the world then I probably would have gone straight for BitBucket - I know one of the guys from work uses it for his personal bits & bobs - but knowing that GitHub doesn't support private accounts for free I presumed BitBucket was the same.. but they aren't! They'll let you have one free private repository with your account so once I'd checked the integrity of my local source I pushed it up to a new private BitBucket repository and that'll look after it from now on! In the long run - for this particular project - this is only going to be a short-term solution; either we'll pick up development at work or I'll decide that it wasn't as good an idea as I'd first thought. And I suppose I could have chucked it on a file share on one of the work servers since I can get VPN access.. but really I wanted to see if this Mercurial / Dropbox combo would be any good. And now I do know! :) Posted at 19:06 I've got something coming up at work soon where we're hoping to migrate some internal web software from VBScript ASP to .Net, largely for performance reasons. The basic structure is that there's an ASP "Engine" running which instantiates and renders Controls that are VBScript WSC components. The initial task is going to be to try to replace the main Engine code and work with the existing Controls - this architecture give us the flexibility to migrate in this manner, rather than having to try to attack the entire codebase all at once. References are passed into the WSC Controls for various elements of the Engine but also for ASP objects such as Request and Response. The problem comes with the use of the Request object. I want to be able to swap it out for a .Net COM component since access to the ASP Request object won't be available when the Engine is running in .Net. But the Request collections (Form, QueryString and ServerVariables) have a variety of access methods that are not particular easy to replicate - ' Returns the full QueryString content (url-encoded), Request.QueryString Request.QueryString.Count Request.QueryString.Keys.Count ' Loops over the keys in the collections For .. in Request.QueryString For .. in Request.QueryString.Keys ' Returns a string containing values for the specified key (comma-separated) Request.QueryString(key) Request.QueryString.Item(key) ' Loops over the values for the specified key For Each .. In Request.QueryString(key) For Each .. In Request.QueryString.Item(key) In the past I've made a few attempts at attacking this before - First trying a VBScript wrapper to take advantage of VBScript's Default properties and methods. But it doesn't seem possible to create a collection in VBScript that the For.. Each construct can work over. Another time I tried a Javascript wrapper - a returned array can be enumerate with For.. Each and I thought I might be able to add methods of properties to the returned array for the default properties, but these were returned in the keys when enumerated. I've previously tried to write a COM component but was unable to construct classes that would be accessible by all the above examples. This exact problem is described in a thread on StackOverflow and I thought that one of the answers would solve my problem by returning different data depending upon whether a key was supplied: here. Hooray! Actually, no. I tried using that code and couldn't get it to work as advertised - getting a COM exception when trying to access QueryString without a key. However, further down in that thread (here) there's another suggestion - to implement IReflect. Not an interface I was familiar with.. It turns out writing a class that implements IReflect and specifies ClassInterface(ClassInterfaceType.AutoDispatch) will enable us to handle all querying and invoking of the class interface from COM! The AutoDispatch value, as I understand it (and I'm far from an authority on this!), prevents the class from being used in any manner other than late binding as it doesn't publish any interface data in a type library - callers must always query the object for method, property, etc.. accessibility. And this will enable us to intercept this queries and invoke requests and handle as we see fit. It turns out that we don't even really have to do anything particularly fancy with the requests, and can pass them straight through to a .Net object that has method signatures with different number of parameters (which ordinarily we can't do through a COM interface). A cut down version of the code I've ended up with will demonstate: // This doesn't need to be ComVisible since we're never returning an instance of it through COM, only // one wrapped in a LateBindingComWrapper public class RequestImpersonator { public RequestDictionary Querystring() { // Return a reference to the whole RequestDictionary if no key specified } public RequestStringList Querystring(string key) { // Return data for the particular key, if one is specified } // .. code for Form, ServerVariables, etc.. } [ClassInterface(ClassInterfaceType.AutoDispatch)] [ComVisible(true)] public class LateBindingComWrapper : IReflect { private object _target; public LateBindingComWrapper(object target) { if (target == null) throw new ArgumentNullException("target"); _target = target; } public Type UnderlyingSystemType { get { return _target.GetType().UnderlyingSystemType; } } public object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { return _target.GetType().InvokeMember( name, invokeAttr, binder, _target, args, modifiers, culture, namedParameters ); } public MethodInfo GetMethod(string name, BindingFlags bindingAttr) { return _target.GetType().GetMethod(name, bindingAttr); } public MethodInfo GetMethod( string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { return _target.GetType().GetMethod(name, bindingAttr, binder, types, modifiers); } public MethodInfo[] GetMethods(BindingFlags bindingAttr) { return _target.GetType().GetMethods(); } // .. Other IReflect methods for fields, members and properties } If we pass a RequestImpersonator-wrapping LateBindingComWrapper reference that wraps one of the WSC Controls as its Request reference then we've got over the problem with the optional key parameter and we're well on our way to a solution! RequestDictionary is enumerable for VBScript and exposes a Keys property which is a self-reference so that "For Each .. In Request.QueryString" and "For Each .. In Request.QueryString.Keys" constructs are possible. It also has a default GetSummary method which returns the entire querystring content (url-encoded). The enumerated values are RequestStringList instances which are in turn enumerable so that "For Each .. In Request.QueryString(key)" is possible but also have a default property which combines the values into a single (comma-separated) string. I spent a lot of time trying to ascertain what exactly was required for a class to be enumerable by VBScript - implementing Generic.IEnumerable and/or IEnumerable didn't work, returning an ArrayList did work, implementing ICollection did work. Now I thought I was on to something! After looking into which methods and properties were actually being used by the COM interaction, it seemed that only "IEnumerator GetEnumerator()" and "int Count" were called. So I started off with: [ComVisible(true)] public class RequestStringList { private List<string> _values; // .. [DispId(-4)] public IEnumerator GetEnumerator() { return _values.GetEnumerator(); } public int Count { get { return _values.Count; } } } which worked great. This concept of Dispatch Ids (DispId) was ringing a vague bell from some VB6 component work I'd done the best part of a decade ago but not really encountered much since. These Dispatch Ids identify particular functions in a COM interface with zero and below having secret special Microsoft meanings. Zero would be default and -4 was to do with enumeration, so I guess this explains why there is a [DispId(-4)] attribute on GetEnumerator in IEnumerable. However, .. RequestStringList also works if we DON'T include the [DispId(-4)] and try to enumerate over it. To be completely honest, I'm not sure what's going on with that. I'm not sure if the VBScript approach to the enumeration is performing some special check to request the GetEnumerator method by name rather than specific Dispatch Id. On a side note, I optimistically wondered if I could create an enumerable class in VBScript by exposing a GetEnumerator method and Count property (implementing an Enumerator class matching .Net's IEnumerator interface).. but VBScript was having none of it, giving me the "object not a collection" error. Oh well; no harm, no foul. As mentioned above, RequestDictionary and RequestStringList have default values on them. The would ordinarily be done with a method or property with Dispatch Id of zero. But again, VBScript seems to have its own special cases - if a method or property is named "Value" then this will be used as the default even if it doesn't have DispId(0) specified. I wrote this to try to solve a very specific problem, to create a COM component that could be passed to a VBScript WSC Control that would appear to mimic the ASP Request object's interface. And while I'm happy with the solution, it's not perfect - the RequestDictionary and RequestStringList classes are not enumerable from Javascript in a "for (var .. in ..)" construct. I've not looked into why this this or how easy (or not!) it would be to solve since it's not imporant for my purposes. One thing I did do after the bulk of the work was done, though, was to add some managed interfaces to RequestDictionary, RequestStringList and RequestImpersonatorCom which enabled managed code to access the data in a sensible manner. Adding classes to RequestImpersonatorCom has no effect on the COM side since all of the invoke calls are performed against the RequestImpersonator that's wrapped up in the LateBindingComWrapper. After the various attempts I've made at looking into this over the years, I'm delighted that I've got a workable solution that integrates nicely with both VBScript and the managed side (though the latter was definitely a bonus more than an original requirement). The curent code can be found on GitHub at:. Posted at 10:20 Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :) In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it.
http://www.productiverage.com/Archive/8/2011
CC-MAIN-2017-13
refinedweb
2,128
51.18
Requirements - Raspberry Pi - Used in article: Model B Revision 1.0 with Raspbian (Debian GNU/Linux 7.6 (wheezy)) - I2C temperature sensor - Method to connect Raspberry Pi to internet - Use in article: Raspberry Pi wired directly to router - Google account to create and access sheets - NMOS or NPN transistor capable of handling the voltage and current requirements of the fan - Schottky diode - Small DC fan - Used in article: 12V/600mA fan Set Up the Hardware Temp sensor Follow the instructions in this article to connect a temperature sensor to the Raspberry Pi. Fan Follow the wiring diagram below to connect the Raspberry Pi to the temp sensor and to the fan through the transistor. The diode is there to prevent the fan from damaging the transistor due to potential voltage flyback when turning the fan off. A diode in this configuration is sometimes called a snubber. You have to cut the ground wire feeding the fan in order to put the transistor in series. The transistor is acting as a low-side switch in this configuration. The maximum current of the Pi GPIO output is 16mA. This means the transistor must have a high enough hFE to conduct the current needed to run the fan. Size the base resistor to limit the amount of current the Pi delivers to the transistor to avoid damage. I used 180 ohms which would give a base current of approximately (3.3-0.7)/180 = 14.4mA. The transistor I selected has an hFE of 150 when conducting 2A, so switching a 600mA load is no problem. Software I2C Follow the article here to setup I2C to communicate to the temp sensor. Installing GPIO capability Type the following in the Pi terminal to install GPIO capability: sudo apt-get install python-rpi.gpio Testing Connections Upload the following Python program to the Raspberry Pi in order to test the fan control from the GPIO. Run the script "turn_fan_on.py" or "turn_fan_off.py" in order to verify the connections. turn_fan_on.py import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) FAN_PIN = 23 GPIO.setup(FAN_PIN, GPIO.OUT) GPIO.output(FAN_PIN, True) turn_fan_off.py import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) FAN_PIN = 23 GPIO.setup(FAN_PIN, GPIO.OUT) GPIO.output(FAN_PIN, False) Controlling the fan based on temperature The following script implements some logic that turns on the fan when the temperature has risen above TEMP_THRESHOLD. The fan will stay on until the temperature drops below the threshold - TEMP_HYST. This way the fan doesn't rapidly turn on and off when the room is around the temperature threshold. import RPi.GPIO as GPIO import smbus import time #0 = /dev/i2c-0 #1 = /dev/i2c-1 I2C_BUS = 0 bus = smbus.SMBus(I2C_BUS) #7 bit address (will be left shifted to add the read write bit) DEVICE_ADDRESS = 0x48 TEMP_THRESHOLD = 78 TEMP_HYST = 2 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) FAN_PIN = 23 GPIO.setup(FAN_PIN, GPIO.OUT) while True: time.sleep(1) temp_F = temp_C * 9/5+32 print "Temp = %3.1f C -- %3.1f F" % (temp_C,temp_F) #control the fan based on the temp if(temp_F > TEMP_THRESHOLD): GPIO.output(FAN_PIN, True) if(temp_F < (TEMP_THRESHOLD - TEMP_HYST)): GPIO.output(FAN_PIN, False) In the video below, I'm using ice cubes in a plastic bag to simulate the room cooling down. When the ice cubes are applied to the temp sensor, the fan turns off. When I remove them, the temperature rises and the fan turns on. Give this project a try for yourself! Get the BOM. 2 CommentsLogin I built a fan controller using arduino mega. It controls 3 fans via pwm that ramps up fan speed based on temperature and has real time rpm reading. Fan speed can also be controlled manually via web interface. Does the fan work controlled by temperature sensor without using respberry pi and auduino?
https://www.allaboutcircuits.com/projects/raspberry-pi-project-control-a-dc-fan/
CC-MAIN-2018-17
refinedweb
647
58.69
Aerospike The Aerospike destination writes data to Aerospike. The destination can write to a single Aerospike node or to a cluster of Aerospike nodes. When you configure the destination, you define the Aerospike nodes to write to and configure the number of times the destination attempts to retry connections to Aerospike. You specify the Aerospike namespace and optional set to use. You also specify the key, or unique identifier, of the Aerospike record to write to. You then map fields in the Data Collector record to bins in the Aerospike record. Configuring an Aerospike Destination Configure an Aerospike destination to write data to Aerospike. - In the Properties panel, on the General tab, configure the following properties: - On the Aerospike tab, configure the following properties: - On the Mapping tab, configure the following properties:
https://streamsets.com/documentation/datacollector/3.7.0/help/datacollector/UserGuide/Destinations/Aerospike.html
CC-MAIN-2019-35
refinedweb
132
54.73
Documents on the Chinese androidWhat is Android? Android is a specialized set of software for mobile devices, which includes an operating system, middleware and some important applications. Beta version of the Android SDK provides the Android platform using the Java language for Android application development tools and API interfaces to be. Features application framework to support component reuse and replacement Dalvik virtual machine optimized for mobile devices Integrated browser based on open-source WebKit engine Optimized 2D graphics library, including custom graphics library, 3D graphics library based on OpenGL ES 1.0 (hardware acceleration optional) SQLite for structured data storage of multimedia support including common audio, video and still image formats (such as MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (accelerometer) (depends on hardware) Rich development environment including a device emulator, debugger, memory and performance analysis charts, and the Eclipse integrated development environment plug-ins Android Architecture The following diagram shows the main components of the operating system Android. Each part will be detailed in the following description. Applications Android application package together with a series of core release, the application package, including email client, SMS short messaging program, calendar, maps, browser, contact management procedures. All applications are written using the JAVA language. Application Framework Developers have full access to the core application framework used by the API. The application architecture design simplifies the reuse of components; any application can publish its functional blocks and any other applications can use the function block its release (but must follow the framework of security restrictions). Similarly, the application reuse mechanism allows the user to easily replace the component. Hidden behind each application is a series of services and systems, including; Rich and scalable view (Views), can be used to build applications, which includes a list (lists), grid (grids), text boxes (text boxes), Button (buttons), or even embedded in the web browser . Content provider (Content Providers) allows applications to access data from another application (such as the contact database), or to share their own data resource manager (Resource Manager) to provide access to non-code resources, such as local string graphics, and layout files (layout files). Notify the Manager (Notification Manager) makes application to the status bar to display custom message. Activities Manager (Activity Manager) to manage the application life cycle and provides common navigation rollback feature. For more details and how to write an application from scratch, see how to write an Android application. Library Android contains some C / C + + libraries, these libraries can be Android system in different components. Them through the Android application framework for developers to provide services. Here are some of the core library: System C library - a BSD inherited from the standard C system library (libc), which is designed for devices based on embedded linux custom. Media Library - based on PacketVideo OpenCORE; the library supports a variety of popular audio, video format playback and recording, while supporting a static image file. Encoding formats including MPEG4, H.264, MP3, AAC, AMR, JPG, PNG. Surface Manager - the management of the display subsystem, and for multiple applications of 2D and 3D layers to provide seamless integration. LibWebCore - a new web browser engine used to support the Android browser and an embeddable web view. SGL - the underlying 2D graphics engine 3D libraries - implementation based on OpenGL ES 1.0 APIs; the library can use the hardware 3D acceleration (if available) or use the highly optimized 3D software to accelerate. FreeType - bitmap (bitmap) and vector (vector) font. SQLite - a free for all applications, features strong lightweight relational database engine. Android Runtime Android includes a core library, the core library provides the JAVA programming language, most of the core library functions. Each Android application process in its own run, have a separate instance of Dalvik virtual machine. Dalvik is designed as a device can also efficiently run multiple virtual systems. Dalvik virtual machine implementation (. Dex) of Dalvik executable file, the format for the small memory usage is optimized. At the same time the virtual machine is based on the register, all the classes by the JAVA compiler, then SDK in the "dx" tool into. Dex format by the virtual machine execution. Dalvik virtual machine depends on the linux kernel features, such as memory management, threading mechanism and the underlying mechanism. Linux kernel Android's core system services rely on the Linux 2.6 kernel, such as security, memory management, process management, network protocol stack and driver model. Linux kernel at the same time as the hardware and software abstraction layer between the stacks. First, start the installation SDK This page describes how to install the Android SDK and how to set up your development environment. If you have not downloaded the SDK, you can click the link below to download and then read the follow-up documentation to learn how to install, configure, and use the SDK to create Android applications. Download SDK Upgrade? If you already use an earlier version of the development process, you can skip this page and read the SDK documentation upgrade. System and software requirements to use Android sdk code and tool development Android applications, you need for the development of computers and development environment, described as follows: Operating system requirements: Windows XP or Vista Mac OS X 10.4.8 or later (only support x86) Linux (Linux Ubuntu Dapper Drake version of test) The required development environment: Eclipse IDE Eclipse 3.3 (Europa), 3.4 (Ganymede) Eclipse JDT plug-in (most of the Eclipse IDE package included) WST (optional, but Android features editor needs, it is included in most Eclipse IDE packages in) JDK 5 or JDK 6 (only the JRE is not enough) Android Development Tools plugin (optional) Not compatible with GNU Java compiler (gcj) Other development environment or IDE JDK 5 or JDK 6 (not just JRE) Apache Ant 1.6.5 or later (Linux and Mac environments), 1.7 or later (Windows environment) Not compatible with GNU Java compiler (gcj) Note: If your computer has installed the jdk, make sure it is the version number listed above. Also to note that some linux versions may contain jdk 1.4 or the gnu java compiler, Adroid development is not supported in both versions installed SDK After downloading the SDK, the. Zip files to the appropriate location on your computer. By default, SDK files are extracted to android_sdk_ <platform> _ <release> _ <build> folder. This folder contains tools /, samples / and so on. Please note that the system in SDK folder after extracting the name and location - when you install the Android plug-in and use the SDK tools, you will need to refer to this folder. You can add the SDK tools folder to your path environment variable. As noted above, tools / folder in the SDK folder. Linux environment, modify the ~ /. Bash_profile or ~ /. Bashrc file. To find a place to set environment variables, adding tools / the absolute path. If you can not find the settings, you need to add new line: export PATH = $ (PATH): <your_sdk_dir> / tools Mac environment, in your home folder, look inside. Bash_profile, then and linux the same treatment. If you have not previously had. Bash_profile file, you can create a new one. Windows, right-click My Computer and select Properties. In the tab Advanced and click Environment Variables, when dialog box appears, double-click the System Variables section in Path (Path). And Tian Jia tools / folder full path. Add tools to your environment variables in, so you can run Android Debug Bridge (adb) and other tools under the command without the need to enter the full path name. Need to note is that if you upgrade your SDK, need to update your environment variables accordingly to the new location. Install Eclipse plug-in (ADT) If you want to use the Eclipse IDE as a development environment for Android applications, you can install support for Android projects and tools of universal plug-Android Development Tools (ADT). ADT plugin includes a powerful expansion that make creating, running and debugging Android faster, easier . If you do not use the Eclipse IDE, you do not have to download and install the ADT plug-ins to download and install the ADT plugin, follow these steps to install your respective versions of Eclipse. Eclipse 3.3 (Europa) Eclipse 3.4 (Ganymede) 1. Start Eclipse, then select Help> Software Updates> Find and Install .... 2. Dialog box appears, select Search for new features to install click Next. 3. Click the New Remote Site. 4. In the dialog box, enter the name of the remote site (eg Android Plugin), enter the site as follows: https: / / dl-ssl.google.com/android/eclipse / Click OK. 5. You can see the new sites added to the search list (and checking), click Finish. 6. In the following search results dialog box, select the check box for Android Plugin> Developer Tools. It will examine the characteristics: "Android Developer Tools", and "Android Editors". Android editor feature is optional, but we recommended to install it, if you choose to install, requires the previously mentioned WST plug-in. Click Next. 7. Read the license agreement, and then choose to accept the license agreement, click Next. 8. Click Finish. 9.ADT plug-in is not signed, you can click "Install All" to install everything. 10. Restart Eclipse. 1. Start Eclipse, select Help> Software Updates .... 2. In the resulting dialog, click the tab Available Software. 3. Click Add Site ... 4. Enter the following address: https: / / dl-ssl.google.com/android/eclipse / Click OK. 5. Back to the view available software, you will see the plug-in. Select next to the Developer Tools and click on Install ... 6. In the next installation window, select the "Android Developer Tools" and "Android Editors". Android editor feature is optional, but we recommend to install it, if you choose to install, requires the previously mentioned WST plug-in. Click Finish. 7. Restart Eclipse. After restart, update your Eclipse preferences to point SDK folder: 1. Select Window> Preferences ... to open the Properties panel. (Mac OS X: Eclipse> Preferences) 2. From the left panel select the Android. 3. In the main interface, click on Browse ... to locate SDK SDK and then locate the folder. 4. Click Apply, then click OK. ADT Installation Troubleshooting I follow the above steps if you download the ADT plugin in doubt, here are some suggestions: In the fourth step, try changing the URL address of a remote update to http, not https. If you are under the protection of the firewall (Enterprise Firewall) Please make sure your Eclipse proxy settings right. In Eclipse 3.3/3.4, you can configure from the main Eclipse menu: Window (in the Mac, Eclipse)> Preferences> General> Network Connections If you can not download the ADT plug-in installed to Eclipse, according to the following steps to download from your computer and install the plug-in: 1. Download ADT compressed files (not extract). 2. In accordance with the default installation of the first and second step (above). 3. In Eclipse 3.3, click New Archive Site .... In Eclipse 3.4, click Add Site ..., then click the Archive ... 4. Browse and select the downloaded zip file. 5. From the beginning the fifth step above the rest of the process to complete. Update your plug-ins, you must follow these steps to replace the default line description more. Update ADT plug-in some cases, your machine may SDK and ADT plugin is compatible, you can use the following steps to update the ADT plug-in from Eclipse. Eclipse 3.3 (Europa) Eclipse 3.4 (Ganymede) 1. Select Help> Software Updates> Find and Install .... 2. Select Search for updates of the currently installed features and click Finish. 3. If ADT can update, select and install the update. Or: 1. Select Help> Software Updates> Manage Configuration. 2. Expand the navigation tree and select Android Development Tools <version> 3.Available Tasks, select Scan for Updates. 1. Select Help> Software Updates ... 2. Select the tab Installed Software. 3. Click the Update ... 4. If the ADT allows update, select it and click Finish. Installation Notes Ubuntu Linux Note If you need help to install and configure java on your ubuntu machine, the following resources may help you: https: / / help.ubuntu.com / community / Java https: / / help.ubuntu.com / community / JavaInstallation Here are java and Eclipsed the installation steps to install the Android SDK and ADT plugin. 1. If you use your development machine 64-bit version, you need to use apt-get install ia32-libs package apt-get install ia32-libs 2. Next, install Java: apt-get install sun-java6-bin 3.Ubuntu Package Manager Eclipse 3.3 version is not available to download, so we recommend you from eclipse.org ( downloads /) to download. Recommend the use of Java or RCP versions of Eclipse. 4. In accordance with the preceding section provides steps to install the SDK and the ADT plug-ins. Note other versions of Linux if you install the ADT plug-in Eclipse encounter this error: An error occurred during provisioning. Cannot connect to keystore. JKS Your lack of suitable development environment virtual machine, install the Sun Java 6 can solve this problem, then you re-install the ADT plug-in. If JDK is already installed on your development computer, make sure the version on this page are listed in the top of the list has some Linux contains jdk1.4 or the gnu java compiler, Android does not support either of the above. Updated SDK This guide will help you upgrade your development environment and application to the SDK, the latest version of Xi if you have applied the previous version of the Android SDK, also need to use this guide. To ensure that your application is compatible with android1.0 system, you need to install the new SDK and API with new transplant existing android application, the following sections guide you through the process. Install a new SDK Download the SDK and extract to a safe location. After extracting the new SDK, you should complete the following operation. Erase data from your simulator SDK version as the new release, some of the data format has changed. Therefore, any data previously saved simulator must be removed. Open a console / terminal and the operation of SDK in the / to ols directory. Start simulator gall wipe-data option Windows: emulator-wipe-data Mac / Linux:. / Emulator-wipe-data Update your PATH variable (Mac / Linux; optional) If you have set the PATH variable to point to the SDK tools directory, then you must update to point to the new SDK's. Eg,. Bashrc or. Bash_profile file: export PATH = $ PATH: <your_new_sdk_dir> / tools Update ADT Eclipse Eclipse plug-If you use the ADT plug-in development, follow these steps to install the new plug-in match the new SDK. Eclipse 3.3 (Europa) Eclipse 3.4 (Ganymede) 1. Select Help> Software Updates> Find and Install .... 2. Select Search for updates of the currently installed features and click Finish. 3. If any ADT effective, select and install 4. Restart Eclipse. 1. Select Help> Software Updates ... 2. Select the Installed Software tab. 3. Click the Update ... 4. If any ADT effective, select and click Finish 5. Restart Eclipse. Restart, update your Eclipse SDK directory set point. 1. Select Window> Preferences ... to open the Preferences panel. (Mac OSX: Eclipse> Preferences) 2. Select Android from the left panel. 3. For the SDK in the main panel location, click Browse ... and locate the SDK directory. 4. Click Apply, then OK. Signed to establish the application to install all applications must be signed before them. ADT plug-and ant-based development tools support this requirement, they are through with a debugger KEY gall apk file to the issue of compilation. To do this, compile the tools included in the JDK's Keytool to create a keystore and with a known alias and password of a key with a known alias and password. For more information, please refer to sign your application. In order to support signed signature, you should first make sure Keytool for SDK build tools to be effective. In most cases, you can tell the SDK build tools to find Keytool, J AVA_HOME by setting your environment variable settings, and an appropriate JDK. Alternatively, you can add the JDK keytool version to your PATH variable if you are developing a version of Linux that was originally using GNU's JAVA compiler sound of many people eating, make sure the system is using the Keytool the JDK version, rather than gcj, if keyt ool already in your path, it may point to a symbolic link is / usr / bin / keytool. In this case, check the symbolic link target to ensure that it points to the correct Keytool. If you are using ant compile your. Apk file ض instead of ADT, you must re-create your build.xml file. To do this, follow these steps: 1. Android application in your project directory, locate and delete the current build.xml file 2.2. Run activitycreator, direct output to your application project that contains the folder 3 .- exec activitycreator - Out your.activity.YourActivity ض activityCreator run this way will not work either, or create a new Java file (or manifest file ض , for those already existing activity and the package. Is important, package and the activity is real. The tool creates a new build. xml file, and a new directory called libs ", this directory will be placed on third-party jar file, which is you can use ant script automatically. Transplantation updated your application after your SDK, you may experience broken code, because the framework and API changes. You need to update your code to match the changing Andriod the API. One way is to use Eclipse to open your project and view your application ADT tag error. From here, you can find the corresponding changes in potential changes in the report preview and API changes. Update your code if you have other problems, please visit android group discussion to seek help or turn to other android developers. If you have modified a ApiDemos application, and want to migrate to the new SDK, please note that you will need to uninstall pre-installed ApiDemos version of the simulator. For more information, or (run or install A piDemos) encountered a re-installation "error, see Troubleshooting on Zi because the wrong signature, I can not install on my IDE ApiDemos application to get information to solve this problem. Development and debugging This section describes the android on the development and debugging applications. It will teach us how to create, compile, run and debug android code. Or, you can also Hello Android tutorial. Start Main content 1. The eclipse on the development of android applications 2. Use other IDE and tool development android application 3. To sign the application 4.ApiDemo sample application usage 5. Debug 6. Device debug and test set 7. Top debugging skills 8. Compile the application to install a android 9. Remove android procedures 10.Eclipse skills developed in eclipse Android application development in the android with eclipse IDE application before you first create an Android project and create a launch configuration, after which you can start writing, running, and debugging your application. The following section assumes you have installed in the eclipse environment ADT plug-in, if you do not, please use the following instructions after installation. Reference to install the eclipse plugin (ADT) Create an android project ADT offers a new project wizard, you can quickly create a new project or to create works in the existing code. Create the project as follows: Select File> New> Project 1. Select Android> Android Project, and then press Next 2. Select the Project Content: Select Create new project in workspace, the code to create a new project. Enter project name (project name), based on the package name (the base package name), and the Activity class name. To create a stub. Java file name and other documents and procedures. Select Create project from existing source, create a project for the existing code. If you want to compile and run the SDK sample programs provided, you can use this option. SDK sample programs stored in the samples / directory. Browse the directory that contains existing code, click ok, if the directory containing the available android manifest file, ADT will you fill out the appropriate package, activity, and application names. 3. Click Finish. ADT plug-in based on your project type to create the appropriate files and folders, as follows: src / include stub. java Activity file folder. res / resources folder. AndroidManifest.xml project list. Create a startup item to run in eclipse to debug the application before, you must create a boot entry for it. Startup Items specify which projects will be started, which activity to work, and the use of which simulator options. Follow these steps for the Eclipse version of the application to create a suitable startup items: 1. Open the Start key management tool. In Eclipse 3.3 (Europa) version, as appropriate, select Run> Open Run Dialog ... or Run> Open Debug Dialog .... In Eclipse 3.4 (Ganymede) version, as appropriate, select Run> Run Configurations ... or Run> Debug Configurations .... 2. In the left list select the Android Application project type selection, double-click (or right click select new), create a new startup entry. 3. Enter the name of startup items. 4. In Android tab, browse to the beginning of the project and Activity. 5. In the Target tab, set the desired display screen and network properties, and any other emulator startup options. 6. You can set the Common tab for more options. 7. Click Apply save the startup configuration, or press Run or Debug (). Run and debug the application once you start setting up projects and project configuration, you can follow the instructions to run and debug application. Main menu from the eclipse, according to choose Run> Run or Run> Debug, launch start running or debugging activity items. Note that activity started running configuration management item is the most recently selected one. It is not necessarily in the Eclipse Navigation panel, select the program (if any) Activities start to set and modify items, you can use the start key management tool. How to get startup item management tools can refer to create a startup item to run or debug your application will trigger the following actions: Start the emulator, if he has not yet begun to run. Compilation works, if in the last compiled on the basis of the modified code will be recompiled. Install the application in the simulator. Run option, and start running the program. Debug in "Wait for debugger" mode, start the program and then open the Debug window and Eclipse Java debugger, and associated procedures. Using other IDEs and tools for developing Android applications are commonly used to install the ADT plug-ins eclipse Eclipse with the ADT plugin. To develop Android program, the plugin will edit, build and debug features into the IDE. However, if you want the IDE to develop in other procedures, such as IntelliJ, or use without ADT plugin eclipse can be. SDK provides the installation, compilation, debugging tools required for application. Create an android project Android SDK contains a activityCreator program, it will produce multiple stub files for the project and a build file. You can use this program to create a new Android project or in the existing code to create projects such as the SDK contains examples. For Linux and Mac systems, SDK provides activityCreator.py, a Python script, Windows on a batch script is activityCreator.bat. No matter what kind of platform, use the same. Follow these steps to run activityCreator create Android works: 1. In the command line, switch to the SDK under the tools / directory for your project file to create a new directory. If you create a project in the existing code, switch to the program's root directory. 2. Run activityCreator. In the command line, you must specify the fully qualified class name as a parameter. If you are creating a new project, the class represented by the same name with its stub class and script file. If created in the existing code works, you must specify the package name of one of the Activity class. The script command options include: - Out <folder> set the output directory. By default the output directory is current directory. If you want to file for the project to create a new directory, you can use this option to point to it. - Ide intellij, a new project in IntelliJ IDEA project file to generate. Here is an example: ~ / Android_linux_sdk / tools $. / ActivityCreator.py - out myproject your.package.name.ActivityName package: your.package.name out_dir: myproject activity_name: ActivityName ~ / Android_linux_sdk / tools $ activityCreator script generates the following files and directories (but not rewrite the existing file): AndroidManifest.xml program list file, while for the project specified Activity class. an Ant build.xml file to compile / package the application. src / your / package / name / ActivityName.java you to specify input Activity class. your_activity.iml, your_activity.ipr, your_activity.iws [only with the-ide intelliJ flag] intelliJ project file res / resources directory. src / source code directory. bin / build script output directory. Now you can move the folder will be developed anywhere, but remember, you must use the tool / folder, the adb program under send files to the simulator. So you need in your work environment and tools / folders between the activities. Of course, you need to avoid moving SDK directory, because it will interrupt the build script. (Re-build before the need to manually update the SDK to map the path) Compile android application uses activityCreator generated Ant file build.xml to compile the program 1. If you do not, you can be Ant Apache Ant home page file. Install it, and make sure it's executable file in your path. 2. Call Ant before, you need to declare JAVA_HOME environment variable and set it to JDK installation path. Note: The windows on, JDK default installation path "Program Files", this path will lead to Ant failed because the path to the middle of a space. Solve this problem, you can specify the environment variables like JAVA_HOME: JAVA_HOME = c: \ Prora ~ 1 \ Java \ However, the simplest solution is to install the JDK directory without spaces. For example: c: \ java \ jdk1.6.0_02. 3. If you have not so ready, in accordance with the above project to create a new description of a project. 4. Now you can run your project Ant build file, just the same folder in the build.xml can import ant. Each modification of the original documents or resources, we need to re-run ant, it will be the latest version of the application package to deploy. Run Android running a compiled program, you need to use adb tool. Apk file loaded into the simulator / data / app / directory, use as described below. 1. Start the emulator (run the command line sdk directory / tools / emulator). 2. Emulator to switch to the main screen (best not to run when the installation program to the simulator, you can press home key to exit application). 3. Run adb, install myproject / bin. / <appname>. Apk file. For example, the installation of Lunar Lander example, the command line, switch to the SDK directory / sample / LunarLander subdirectory, type .. / .. / tools / adb install bin / LunarLander.apk 4. In the simulator, open the executable list, scroll the screen, select and start your application. Note: When you first install an Activity, you may need to start before the item display, or other program calls it before the re-start the emulator. Because the package management tools usually only start in the simulator to complete the review of manifests. Attach the debugger to programs in this section we introduce how to display debug information on the screen (such as CPU utilization), and how to run the IDE and simulator program associate. Using the eclipse plugin can automatically generate debugger. But you can also configure the debug port by IDES to monitor debug information. 1. Start Dalvik Debug Monitor Server (DDMS) tool, it is played between the IDE and simulator port translation service role. ? 2. Set simulator debugging configuration options. For example, debugging information is loaded until after the start the application. Note that a lot of debugging options without DDMS can also use, for example, the simulator shows the efficient use of CPU, or the screen refresh rate. 3. Configuring IDE, IDE makes debugging associated with the 8700 port. How to set up Eclipse to debug your project. Contains the following information. Additional debug port configuration IDE DDMS for each virtual machine is assigned a special debug port, the port can be found in the simulator. You have your IDE with this port (virtual machine information on these ports is listed in column) associated with the default port 8700 or. This keeps the IDE to connect to the emulator program in the list of either program. IDE need to associate your running programs on the simulator, showing its threads, and allows you to hang it, check its status, set a breakpoint. If you set the panel options in the development of a "wait debugging", the application will wait until after the run Eclipse connection, so you need to set a breakpoint before the connection. Changes are debugging the program, or select the program is running in the current "wait for the debug" will cause the system to kill the application. If your program is in a bad state, you can use the method to kill it, very simple, just set and the hook off the check box. Application Signature Android system requires all of the procedures to install digitally signed, if the digital signature is not available, the system will not allow installation to run this program. Either simulator or real equipment, as long as android system, which is applicable to all. For this reason, the device or emulator before running the debugger, you must set your application digital signature. Understand the procedures for signature of the important points android:: All procedures must be signed, the procedure has not been signed, the system can not be installed. You can use self-signed certificate to sign your application must be no certificate authority is. System only when the test will be to install signed certificate is valid, if an application's signature is not due until after installation, then an application can still be activated properly. You can use standard tools-Keytool and Jarsigner-generated key to sign the application. Apk file. Android SDK tools can help you debug the application when to sign. ADT plug-ins and Ant build tool are available two signature model-debug mode and release mode debug mode, compile using the JDK tools in the general program Keytool and password created by the known methods of secret lock and key. Each compile time, tools, key signatures using the debug application. Apk file. Because the password is known, tools do not need to compile every time when prompt you to enter the password lock and key. When your application has been prepared to release, you can compile in release mode. release mode, the tool does not compile time. apk file signature. You need to generate key and secret Keytool lock, then the Jarsigner JDK tools to. Apk file signature. In order to support the basic set signature generated under lock and key, you must first determine Keytool in the SDK compile tools to be effective. In many cases, you can set the JAVA_HOME environment variable to tell SDK how to find Keytool, or you can add in the PATH variable Keytool the JDK version. If you are a linux version in development, was originally from Java Gnu compiler, make sure that systems are Keytool version of the JDK, rather than the gcj version. If Keytool have PATH, it will point to symbolic link / usr / bin / keytool. This case, the goal is to verify the symbolic link points to JDK under the Keytool Eclipse / ADT sign in if you are under the Eclipse development, and has been described above in accordance with the installation of the Keytool, by default, can be signed in debug mode. When you run the debugger when the ADK will. Apk file signature, and install the simulator. This part does not require special action, ADT has entered Keytool Compiler in release mode, press the Package project right panel, select Android Tools> Export Application Package. Or you can click on the Manifest Editor, overview page "Exporting the unsigned. Apk" connection, export unsigned apk file. Save. Apk file, with Jarsigner and your own key to the apk file signature, if not the key, you can create a key and secret Keystore lock. If you already have a key, and as public key, you can give. Apk files signed. If you compile with Ant Ant signature. Apk file, assuming you use the latest version of the SDK contains activitycreator tool to generate build.xml file, by default, you can use the debug signature scheme. When you run Ant on the build.xml compiler, build scripts to generate secret lock and key and signature. Apk file. This part does not need to do other special moves. release mode compiler, you need to do is specify the build command in the Ant target "release". For example, if the directory in bulid.xml run ant, enter the following command: ant release build script to compile a program and not signed. Compilation finished. Apk file, you need Jarsigner and your own key to. Apk file signature. If there is no key, you can create a key and secret Keystore lock. If you already have a key, and if the public key, you can give. Apk files signed. Commissioning period of self-signed certificate for the certificate program in debug mode (default is Eclipse / ADT and Ant builds), since its creation one year from the time period. When the certificate expires, there will be a compilation error. And the error shown below: debug: [Echo] Packaging bin / samples-debug.apk, and signing it with a debug key ... [Exec] Debug Certificate expired on 8/4/08 3:43 PM In Eclipse / ADT, you can see a similar error. A simple way to solve this problem is to remove debug.keystore file. Linux / Mac OSX save this file under ~ /. Android under, windows XP, the file is saved in C: \ Documents and Settings \ <user> \ Local Settings \ Application Data \ Android. windows Vista the file saved in the C: \ Users \ <user> \ AppData \ Local \ Android. Next compilation, the compiler tool will generate a new secret lock and key. Note: If your development device using a non-Gregorian locale, often the wrong compiler tools to generate a debug expired certificate, so you will get compile time error. For solution, see the Troubleshooting topic I can't compile my app because the build tools generated an expired debug certificate. Sample application using ApiDemo Android SDK contains a set of sample programs, they verify a number of functions and API usage. ApiDemos package is installed in the simulator in advance, so you can start the emulator, an application in the main screen to open it in a drawer. You can also <SDK> / samples / ApiDemos find the source, can see it, the realization method of learning Demo. If you prefer, you can also ApiDemo sample program as a project loaded in, modify and run the simulator. However, before that you first uninstall before installing the ApiDemos. If you do not remove the previously installed version of the development environment directly in run or modify ApiDemos, will be installed incorrectly. On how to uninstall and reinstall ApiDemo, can refer to the I can't install ApiDemos apps in my IDE because of a signing error. So you can in your development environment to work. Debugging Android has a wide set of tools to help you debug your application: DDMS - A lively program that supports port translation (so you can IDE code you under in the endpoint), support the crawling simulator screen, thread and stack information, and many other features. You also can run logcat regain Log information. Click this link for more information. logcat-dump system information, such information includes, emulator throws an error when the stack is running and log message. Run logcat, click the link. ....android.home.AllApps) ... Android Log - output log file information simulator Log class. DDMS If you run a logcat, you can read these real-time information. Add your code logging method call. Using the log class, you can get the information you want the important level of call Log.v (verbose), Log.d () (debug), Log.i () (information), Log.w () (warning) or Log.e (error). to distribute log messages Log.i ("MyActivity", "MyClass.getView () - Requesting item number" + position) You can use logcat read this information. Traceview - Android can call the function as well as call time saved to a log file, you can use graphics reader Traceview view details. For more information see this link under the subject Eclipse plugin-Eclipse plug-in integration of a considerable number of tools (ADB, DDMS, logcat output, and other functions), click on this link for more information. Debug and Test Device Settings-Android reveals a number of useful settings, such as CPU usage and frame rate, see the following Debug and Test Settings on the Emulator Also, see the Troubleshooting section of the doc to figure out why your application isn't appearing on the emulator, or why it's not starting. In addition, see the Troubleshooting section of this document to find out why did not your application appear in the simulator, or why not start. Device debug and test set Android allows you to set multiple settings so you can test and debug procedures. Development for simulator set, you can choose Dev Tools> Development Settings. Development in accordance with the following options will open the Settings page (or one of them): Debug app selection process to be debugged, you do not set this to associated debugger, but this variable has two effects: Android breakpoints in debugging to prevent the Commissioner of time to throw error to stay. Wait for Debugger allows you to select the option to suspend the proceedings until the debugger to be associated with the (as introduced) Wait for debugger to load until the associated block on the debugger. So you can onCreate () to set the endpoint, which start the process of debugging when the Activity is important. When you change this option, any currently running instance will be killed. To check this box, you must, as described above to select a debugger. This is the code to add waitForDebugger () is the same. Immediately destroy activities tell the system as long as the activity stopped on the destruction of it. (Like Android have recovered memory). The test onSaveInstanceState (Bundle) / onCreate (android.os.Bundle) code path is useful when, otherwise, would be difficult to effect. Selecting this option may bring a lot of problems because they do not save the program state. Show screen updates when this option is selected, the screen redraw any rectangular area will flash pink. This was found unnecessary screen drawing useful. Show CPU usage at the top of the screen shows the progress of a CPU, display CPU usage. Above the red bar shows the total CPU usage, below the green bar shows the current CPU usage time frame. Note: Once the open time function can not be turned off, unless you start the emulator. ? ? ? Show background screen displayed when no background activity panel, this usually only occurs when debugging. Simulator after restart still remember these settings. Top of the stack dump debugging skills quickly get heap dump from the emulator, you can log adb shell, use the "ps" command to find the process you want, then use "kill-3", the stack using the track will appear in the log file in. Displayed on the screen in the simulator device can display some useful information useful information, such as CPU utilization, as well as highlight the redraw area. Can set the window in the development of open and close these features. Setting debug and test configurations on the emulator. In detail. You can Dalvik Debug Monitor Service tool to get the dump state information. Please refer to adb described dumpsys and dumpstate Get the emulator application state information (dumpsys) You can Dalvik Debug Monitor Service tools were dumpsys information. Reference adb described dumpsys and dumpstate. Access to the wireless connection information you can Dalvik Debug Monitor Service tool to get the wireless connection information. In the Device menu, select "Dump radio state" You can record tracking data activity by calling android.os.Debug.startMethodTracing () to record the function calls and other tracking data. Detailed reference Running the Traceview Debugging Program. Wireless data recording By default, the system does not record wireless data (data are many). However, you can use the following command record wireless data: adb shell logcat-b radio Run adb Android have adb tool, he provides many functions, including mobile and synchronize files to the simulator, change the port the emulator to run UNIX shell. See Using adb. Screenshots for simulator Dalvik Debug Monitor Server (DDMS) can crawl simulator screenshots. Help using the debug class Android to offer easy to use debugging helper class, such as util.Log and Debug Compile application installation Anroid Android build tools specifically required to correctly compile the resource file and other parts of the application, so you must build your application a specific build environment. Android compiler specific steps, including, XML and other resources to compile the file and create the appropriate output format. Compiled Android application is a. Apk compressed file, it contains. Dex files, resource files, the original data files, and other documents. You can scratch, or construct a suitable source Android works. Android currently does not support development in the local code on third-party applications. Comparison of recommended Andriod application development is to use Eclipse with the Android plugin, it supports compile, run, debug Android applications. If you have any other IDE, Android provides tools for other IDEs can compile and run Android applications, but they are not complete. Out of an Android application out of an installed application in the emulator, you need to perform adbrun adb deleted. Apk file. . Apk file is installed on when to send to a simulator. Adb shell into the device using the shell, switch to the data / app directory, delete the apk file with the rm command: rm your_app.apk. Usage is described in the connection. Eclipse Eclipse skills in the execution of arbitrary java code in Eclipse, when the program stopped at the breakpoint when you can execute arbitrary code. For example, in one with "zip" function of the parameter string, you get package information, call the class method. You can also execute arbitrary static methods: such as, input android.os.Debug.startMethodTracing (), start dmTrace. Open source implementation of the window, the main menu, select Window> Show View> Display, open display window, a simple text editor. Enter your code, highlight the text, click the 'J' icon (or CTRL + SHIFT + D) to run the code. Code in the context of the thread selected to run, and this thread must be stopped at the breakpoint or single-step stopping point. (If you manually link to the thread, you must single step. Thread stopped in Object.wait () is of no use). If you are currently stopped at a breakpoint, you can simply press the (CTRL + SHIFT + D) highlight and implement a code. You can highlight text in one selected area, by pressing ALT + SHIFT + up / down arrows to change the size of selected area Here are some examples of input and response messages eclipse display window. Input Response zip (Java.lang.String) / work/device/out/linux-x86-debug/android/app/android_sdk.zip zip.endsWith (". zip") (Boolean) true zip.endsWith (". jar") (Boolean) false You can also use the clipboard to insert the code without debugging. Find the document in the eclipse "scrapbook" related. Manually run DDMS Although recommended for ADT plug-in debugger, but you can also manually run the DDMS, configure Eclipse to the debugger on port 8700 (Note: Make sure you start the DDMS). Increase the JUnit test class in Eclipse / ADT, you can add a JUnit test class program, however, the normal test run before you need to set specific JUnit configuration JUnit configuration on how to set up more details, see, see the Troubleshooting topic I can't run a Junit test class in Eclipse. Hello, Android! As a developer, your first feeling is that you get this development framework to write "Hello, World!" Program level of difficulty you left. Of course, Android, the this very easy, I'll give you the following presentation: Create a project to create UI Run the code: Hello, Android The following sections describe in detail UI using XML Construction Debugging works do not use Eclipse to create a project we started to create works to create a project as simple as possible, Eclipse Android plug-ins can make the development easier. You need a computer with Eclipse IDE (reference system and software requirements), you also need to install the Android Eclipse Plugin (ADT). If you are ready to continue to see here. First, you need to create a "Hello, World!" Have a rough idea: 1. In the menu File> New> Project to create a new Android project. 2. Android project dialog to create complete project details. 3. Edit templates automatically generate code to display some of the output. That's it, the next step, we will explain in detail each step. 1. Create a new Android project to open Eclipse, select File> New> Project, if the Eclipse Android plug-ins installed correctly, the pop-up dialog will have an "Android", this one has a unique sub-item " Android Project ". Select the "Android Project", click Next. 2. Fill in the detailed information you need to complete the project next more information, here is an example: A specific meaning of each: Project name you want to save your work machine which directory package name > Package name space (java programming language to follow the naming rules), all your code will be in this namespace. This will generate package names to events automatically. You use the name of this package must be installed on your machine other package names do not conflict, so using a standard rule of the package name is very important. As patients, we used the package name as "com.android", but you need to use a different type. "Activities" Name This is the plug-in for you automatically generate class names. It also is the Android activity class of a subclass. An activity is just a function and can contain the implementation of the class. If it is selected, you can create user interfaces, but it is not necessary. Program name is the name of the last generation applications. Optional box "Use default location" allows you to select a directory to save the other files generated by the project. 3. Editor plugin automatically generates code to run, it will automatically generate a class "HelloAndroid" (available in the program package HelloAndroid> src> com.android.hello found.) Like this: public class HelloAndroid extends Activity ( / ** Activity is first created after the call. ** / @ Override public void onCreate (Bundle savedInstanceState) ( super.onCreate (savedInstanceState); setContentView (R.layout.main); ) ) Now, you can execute a program. But we can also further studies, so that we can better understand the procedures were. So, the next step we can build UI to change some code We see the following revised code, you can file your HelloAndroid.java do the same changes, we come to line by line analysis: package com.android.hello; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity ( / ** Event is created after the first call * / @ Override public void onCreate (Bundle savedInstanceState) ( super.onCreate (savedInstanceState); TextView tv = new TextView (this); tv.setText ("Hello, Android"); setContentView (tv); ) ) Tip: If you forget to introduce TextView the packet, you can try Ctrl-Shift-O (If the Mac system Cmd-Shift-O). This is a shortcut to Eclipse management applications - it will show not find the package and then automatically as you add. In Android, the user interface, called the view by a number of different levels of classes. A view is a simple object. Such as radio button, animation controls, a text box (our example), we said the deal with a child views the text called TextView. Here to teach you how to create a TextView. Here to teach you how to create a TextView: TextView tv = new TextView (this); Android TextView constructor is an instance of the context, this context is just a handle pointing to the system, which provides resources to deal with the class as the service. Contains a number into the database and the parameters of the entrance. The event is also inherited context. HelloAndroid class is a subclass of activities, it is also a context, we operate through this TextView. Create TextView, add to display the content: tv.setText ("Hello, Android"); Here is normal. We create a TextView, and then tell it to display the content. The final step is to make TextView displayed on the screen, like this: setContentView (tv); Activities in setContentView () method that view which needs to be operated on the current UI. If an activity can not call this method, then there is no current interface system appears as a blank screen. We just want to display some text, so we will just create the TextView connection Android platform, which is in the "Hello, World", of course, we can see next operation. Implementation of the code: Hello, Android Eclipse plug-ins makes it easy to run your program. Select Run> -> Open Run Dialog menu. (Eclipse3.4 version, the menu for the Run-> Run Configurations) can see that the dialog box Next, select "Android Application", click in the upper left corner (the button like a piece of paper with a "+" sign) or double-click the "Android Application". Have a new option "New_configuration". Changed its name to the image of a little more like "Hello, Android", and then press the Browse button to select your items, (if you have multiple Android projects in Eclipse need to open, sure to select the right) plug-in will automatically scan your items where activities of sub-class, and then in the "activity" drop down menu loaded. If your "Hello, Android" is only one project, it will be set as the default item, then you can continue. Click "Apply" button, here is an example: This can, and click the "Run" button, Android emulator starts. One to start your program will appear, when all OK, you can see: This is the Android's "Hello, World", is not very simple? The next section we will provide more detailed information. When you reach more of the Android, you will find it very valuable. Use XML UI construction You just completed the "Hello, World" example of using what we call a "programmable" in the UI layer, meaning that by writing code to set up your UI layer. When you develop enough of the UI program, you will find some very bad things: some small changes you have to do a lot of code changes. You often forget the View link, which will result in some errors, waste a lot of time to debug your code. That is why the Android change the UI to provide a development module: XML-based documents. The simplest interpretation of this concept is the demonstration example. Here is a XML file, it can achieve, and you have just finished the code the same effect: <? Xml version = "1. 0" encoding = "utf-8"?> <TextView xmlns: android = "" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: Android is usually in XML file structure is very simple. Just a collection of some of the tree tag, each tag is a view class. In this case, it is a simple De TextView element of the tree, you can use the XML file's name extension classes Any as your marker, this Yebao Kuo you in your own Daima in the definition of the name. This structure allows you to use a simple structure and syntax of rapid formation of UI, this model as the site development model, you can separate the UI and program logic, to obtain or fill data alone. In this example, there are four XML attributes, the following are attributes of the general meaning: Property Description xmlns: android This is an XML namespace, told the Android development tools are you going to use Android in some of the common namespace attribute. Android XML design files in all the most outer tag must use the tree. android: layout_width This attribute defines the width of the view need to occupy the screen. In this example, we can take only one view of the entire screen, that is, "fill_parent" means. android: layout_height This and "layout_width" is similar to that occupied by the screen height. android: text This set the text display, in this example, we use "Hello, Android". This is the XML layout, you need to put this file located? On your project / res / layout can be under. "Res" is a "resource" for short, this catalog contains all the application needs of the non-code section. Such images, strings, XML documents. Eclipse plug-ins for you to create these XML files in a. In our example above, we do not used it. In the package manager, the start directory / res / layout, editing main.xml file, replace the above text and then save the changes. Code directory from Open R.java file, you can see them like this:; ); ); R.java is the document defining the value of the index of all the resources defined. You use this class in the code, as in your project using a simple method that your resources. In the Eclipse IDE tools such as where, in this way for the code completion feature is very effective because it lets you quickly have to locate what you're looking for. One important point to note is that there is an internal class "main", a "layout" of the members of the class. Eclipse plug-in to remind you add a new XML file, then generate R.java file, when you add other resources to your project, you can see R.java change in sync. The last to do is use the latest version of XML you modify your code to replace the previous HelloAndroid coding. This has re-written example of the class of models, you can see, the code becomes very simple: package com.android.hello; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity ( / ** Called when the activity is first created * / @ Override public void onCreate (Bundle savedInstanceState) ( super.onCreate (savedInstanceState); setContentView (R.layout.main); ) ) When you make these changes, you only need to copy, copy. R in the class that you can use the code in the AutoComplete feature, you'll find that really helpful. Now you have completed these changes, continue your program - you need to do is press the green "Run" button, or select Run-> Run History-> Hello, Android. You can see ... wow, and as seen before! This shows that the construction of two different ways to achieve the same result. There are many ways to create the XML file, you want to do before. Read more information available to achieve the user interface. Commissioning works Android plug-ins on the Eclipse development and debugging tools for Eclipse integrates very well. In order to show you, we have added a code bug. You can modify the same code like the following to your code: package com.android.hello; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity ( / ** Event is created after the first call * / @ Override public void onCreate (Bundle savedInstanceState) ( super.onCreate (savedInstanceState); Object o = null; o.toString (); setContentView (R.layout.main); ) ) This change just introduced a NullPointerException to your code. If you run the program again, and finally you will see: According to "Force Quit" to terminate program and turn off the simulator windows. To search for the wrong reasons, set a breakpoint in the Object o = null; (in the bar code tag next to double-click); and then from the menu select Run-> Debug History-> Hello, Android to enter debug mode. Your application will restart in the simulator, but this will stop you set the breakpoint. You could Eclipse's Debug Perspective in single-step code, the same as you debug other programs. Do not use Eclipse to create works if you do not use Eclipse (for example, you like other IDE tools, or just use a text editor or command line tool), then the Eclipse plugin does not work for you. Do not worry - it will not because you do not use Eclipse to use to lose any functionality. Android Eclipse plug-ins on the Android SDK is only a tool outside. (These tools such as: simulator, aapt, adb, ddms in other documents, etc.) Therefore, these tools and other tools such as "ant" build file combination is possible. Android SDK contains a Python script in "activitycreator.py", it can create for your project all the code and the directory. Like the ant in the "build.xml" file. This allows you to use the command line to compile your project or use your own IDE tool integration. For example, as we have just created HelloAndroid project using Eclipse, you use the command: activitycreator.py - out HelloAndroid com.android.hello.HelloAndroid Compile the project, you run the "ant" command, when the command successfully executed, will be "bin" directory create a "HelloAndroid.apk" file, "apk" file is a package Android, you can use "adb "tool to install or execute. If you would like more information, please read the website provided for him the document. Android Applications Android application form is generally of four components by the following structure made of: Activities of radio receiver services provider to note that not every Andorid applications must reconstruct the four components, some may be caused by a combination of these components. Once you have determined your application components required, then you should be listed in AndroidManifest.xml them. This is an XML configuration file, which is used to define the components required in the application, components, functions and necessary conditions. This file is necessary. For details, see Android manifest file documentation The four components as follows: Activities Activities are the most basic Andorid application components, application program, an activity usually is a single screen. Each activity is implemented as a separate class, and from the activities inherited base class, activity class will be displayed by the view of the composition of user interface controls, and respond to events. Most of the application is composed by the multi-screen display. For example, a text messaging application may have a display screen, the contact list to send a message, the second screen is used to write text messages and select recipients, again a screen view message history or information set manipulation. Each screen here is an activity that is very easy to implement from one screen to a new screen and complete the new activities. In some cases, the current screen may need to move up a screen to provide the return value - for example, allow users to select a photo from the phone address book as a telephone dial back to those picture. When you open a new screen, a screen will be set prior to suspension of state and pressure into the history stack. Users can rewind back to before the parade opened the screen. We can not selectively remove the need to retain some of the screen, because Android will open the program from the desktop of each remain in the stack. Intent and Intent Filters Android proprietary class of Intent calls for agencies to switch between screens. Intent is to describe the application you want to do. Intent data structure is the most important part of the two movements and actions correspond to the data. The typical action types: MAIN (event gateway), VIEW, PICK, EDIT, etc.. The action corresponding to the URI of the form data Zeyi said. For example: To view an individual contact, you need to create an action type VIEW of intent, and one that the person's URI. Has a relationship with a class called IntentFilter. When the intent to do something when asked, intent filter used to describe an activity (or BroadcastReceiver, see below) to operate what intent. An activity if you want to display a contact person, you need to declare a IntentFilter, this IntentFilter to know how to deal VIEW action and that a person's URI. IntentFilter need AndroidManifest.xml defined. By analyzing a variety of intent, to switch from one screen to another screen is very simple. When the forward navigation, the event will be called startActivity (myIntent) method. Then, the system will be installed in all applications defined IntentFilter find, find the best match myIntent of Intent corresponding activities. New activities received myIntent the notice, began to run. When the start method is called activity analysis myIntent will trigger the action, this mechanism provides two key benefits: Activities can re-use from other components in the form of Intent activities can produce of a request at any time by a same IntentFilter new activities to replace radio receiver you can use BroadcastReceiver to make your application on an external event to do the response. For example: When the incoming call, the data network is available, or at night time. BroadcastReceivers not show UI, it is only through NotificationManager to notify the user of these interesting things happened. BroadcastReceivers both registered in AndroidManifest.xml can also be used in the code Context.registerReceiver () to register. But these interesting things happen, your applications do not need to request call BroadcastReceivers, the system will need time to start your application, and where necessary, trigger BroadcastReceivers. Applications also can be used Context.sendBroadcast () will broadcast their own intent broadcasts to other applications. Services with a service is not for a longer life cycle and user interface procedures. An example is a good play list are songs from media player. In a media player application, should have more activities, so that users can select songs and play songs. However, the music playback function does not correspond to this activity, because users will of course think that the navigation screen to the other music should still play. In this example, the media player of this activity will use Context.startService () to start a service, so you can keep the music in the background. Meanwhile, the system will maintain this service has been implemented to run until the end of this service. (You can read the Life Cycle of an Android Application for more information on services, introduction). In addition, we can also use the Context.bindService () method to connect to a service (if this service has not run to start it) . When connected to a service, we can also provide the interface through the service to communicate with it. Take this example of media players, we also can pause, replay and other operations. Content Provider Applications to save their data to a file, SQLite database, or even any valid device. When you want your application to share data with other applications, the content of their would be useful. A content provider class implements a standard set of methods that will allow other applications to save or read the content provider handling the various data types. More detailed information on the content provider, can refer to the attached document Accessing Content Providers. Tutorial: a notepad application examples of this tutorial taught you the way through, explain how to use the Android framework and various tools to build their own mobile applications. A pre-configured from the start the project file, the tutorial with a simple notepad application complete development process, supported by detailed examples that runs through the guide you how to set up projects, organizations, application logic and UI, and even then the compiler and run the executable procedures. The tutorial will be the Notepad application development process as a set of exercises (see below), each composed of a number of steps by the exercise. You can closely followed the steps to complete each exercise, gradually establish and improve their own applications. These exercises provided in this application you need to achieve - down to each step - the specific example of the code. When you complete this tutorial, a practical function of Android applications born from your hands and your Android application development in some of the most important concepts will have a more profound understanding. If you want to you this simple Notepad application to add more complex functionality, you can use Notepad another way to achieve your exercise program cf code specific documents can be found in Sample Code section. Target audience of this tutorial This tutorial is mainly for a certain experience, especially those with some knowledge of Java programming language developers. If you had never written a Java application, then you can still use this tutorial, but pace slightly slower opinion only. This tutorial assumes you are familiar with the Android application of some basic concepts and terminology. If you are familiar with these words is not enough, you have to Overview of an Android Application carefully ponder about, to continue following the study. It is necessary to note, the tutorial Android integrated development environment is a pre-installed plug-in Eclipse. If you do not have Eclipse, can still do these exercises and the establishment of the following applications, but you will be forced to face some of the steps involved in Eclipse Eclipse IDE, how to achieve non-issue. Practice before the preparation of this tutorial build Android applications involved in the project-related information in Installing the SDK and Hello Android to do the two documents in detail. These two documents explain in detail to establish Android applications, build their own development environment necessary for knowledge. Before you start the tutorial before the two documents, SDK installed and set up the development environment you have to have everything ready to ensure that only wind up. Training required for this section of the preparatory work: project exercises archive (. Zip) 2. Unzip to a directory on your local 3. Open the folder NotepadCodeLab 1. Download project exercises archive (. Zip) 2. Unzip to a directory on your local 3. Open the folder NotepadCodeLab NotepadCodeLab this folder are six project files, the specific are: Notepadv1, Notepadv2, Notepadv3, Notepadv1Solution, Notepadv2Solution and Notepadv3Solution. One such Notepadv # project directory is the starting point of each exercise, and Notepadv # Solution is a corresponding answer. If you encounter problems in a practice, you can code your local project compare with the corresponding answers from my answer. Exercises The following table lists some of the tutorial exercises, and describes the development of each exercise covered in the training content. Each practice is based on before you have completed the premise that any exercise to commence. Exercise 1 A simple notepad application development process starting this. You can add notes to build a new, simple notes but not edit the list. Demonstrate the basic aspects of ListActivity and how to create and control a menu item, and how to use a SQLite database to store the contents note. Exercise 2 Notepad application to add a second Activity. Demonstrates how to construct a new Activity to the Android operating system to transfer data between different Activity, using the more advanced screen layout, and demonstrates how to call startActivityForResult () the API to activate another window and returns a result. Exercise 3 Add to the Event for the application life cycle control, in order to get the application throughout the life cycle state. Additional study demonstrates how to use the Eclipse debugger and view the Event generated by the debugger after the entire life cycle. This section of non-required reading, but still highly recommended reading. Other resources and extension of learning not covered in this tutorial, some minor, but more extensive concept, please refer to the Common An Related Posts of Documents on the Chinese android. J2EEer Learn Ruby Ruby has long heard of the development of efficient and accurate is to use Ruby on Rails to develop WEB applications very convenient. While J2EE has a lot of very good Opensource framework, automatic code generation tools, can greatly enhance the developm The real design and coding Software development process at the design and coding, both organizations (as well as other details of the project controllability requirements) engineering method is XP ah, UPS ah what the design phase is to cover the entire software development pro ... Software Performance 1.1 Software Performance In general, the performance is an indicator that the software system or component to its timeliness requirements in line with the level; followed by software performance, are an indicator can be used to measure time. Performa ... ...
http://www.codeweblog.com/documents-on-the-chinese-android/
CC-MAIN-2014-42
refinedweb
11,503
55.34
Okay, let’s sit down to create a new game. Step 1. Open text editor. Done. This is easy. Hmm … Geez, maybe I should break out of my shell and try something new. I have developed MANY applications of all sorts of shapes and sizes using the Django Framework. I am a huge supporter of it from the early days, and strongly believe it still has a long future. But, what about all these new things out there? Sure, I can jam stuff into Django, or even replace the ORM with something else. I even had started working on a package to bring Elasticsearch into the Django model manager. This time, I want something different. Let’s start by adding GraphQL to the stack. My Stack ======== [X] GraphQL How am I going to interface with the specification inside Python? Ahh, Graphene. What an amazing package! Basically, you create a schema that looks very much like any ORM: a series of classes with fields that map to attributes. This raises a problem though. You see, when developing my elasticmanager package, I initially grabbed the existing Django ORM models and looped over them to generate a schema that fit inside elasticsearch_dsl. The problem was that this did not give me enough flexibility. So, I took that out and created two sets of schemas: Django models, and elasticsearch datatypes. Once I added Django REST Framework into the mix, I now had a third schema! I want to avoid this problem on this project. So, I need to be able to have one defined schema, and that will be graphene. My Stack ======== [X] GraphQL [X] Graphene Well, what about database you say? I thought about Postgres (my typical go to). Seeing how this is a side project and I am already taking on new technologies, maybe I should see what else is out there that I don’t know. Neo4j is a relational graph database that comes with its own query language called cypher. Probably a topic for another post. Suffice it to say that cypher is both extremely comfortable and natural to write, and hugely powerful. Back to my stack. How am I going to interact with Neo4j? There is a really neat package that looks EXACTLY like Django ORM: neomodel. That certainly would be an easy transition; I can already tell how I would interact with it. It looks like the code I have been writing for a long time. It does, however, seem like a little bit of a cop out though since it generates all the cypher queries for you. Do I abstract that away with neomodel? Or, take it head on and learn it. Again, this is a side project, what do you think the answer is? My Stack ======== [X] GraphQL [X] Graphene [X] Neo4j, without an ORM layer Now my backend is starting to shape up. I am still missing, however, the key component to bind it altogether. I already decided to NOT build with Django. I suppose Flask, Bottle, or Pyramid. Hmm … thinking about the frontend though, I REALLY want to have a tightly coupled chat application and live streaming data. It really seems like something meant for WebSockets. Since Django is out, that means the awesome Django Channels (my typical WebSockets interface) is out. What next? Tom Christie of DRF fame has been working on a new API project called apistar. It does not currently handle the sort of connections I am looking for, but he also worked on a project called uvicorn. That looks promising. Ooo, someone made a connection for Sanic with GraphQL. With one line of code I can hook up GraphQL and Grapehne. app.add_route(GraphQLView.as_view(schema=Schema, graphiql=True), '/graphql') And it handles both HTTP and WebSockets. I’m sold. My Stack ======== [X] GraphQL [X] Graphene [X] Neo4j, without an ORM layer [X] Sanic - HTTP - WebSocket Now … I just need to hook this all up. That was surprisingly easy. Here is how I did it. from sanic import Sanic from sanic.response import text from graphene import ObjectType, List, Schema, String, Field, AbstractType from sanic_graphql import GraphQLView from neo4j.v1 import GraphDatabase import copy uri = "bolt://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "<PASSWORD>")) def query(cypher, **kwargs): with driver.session() as session: with session.begin_transaction() as tx: return tx.run(cypher, **kwargs) league_attributes = { 'abbreviation': String(), 'name': String(), } class LeagueAbstract(AbstractType): def resolve_name(self, args, context, info): return self['l'].get('name') def resolve_abbreviation(self, args, context, info): return self['l'].get('abbreviation') League = type('League', (LeagueAbstract, ObjectType), copy.deepcopy(league_attributes)) class Query(ObjectType): leagues = List(League, copy.deepcopy(league_attributes)) league = Field(League, copy.deepcopy(league_attributes)) def resolve_leagues(self, args, context, info): abbreviation = args.get('abbreviation', None) abbr = 'WHERE l.abbreviation={abbreviation}' if abbreviation is not None else '' cypher = f'MATCH (l:League) {abbr} RETURN l;' records = query(cypher, abbreviation=abbreviation) return records def resolve_league(self, args, context, info): abbreviation = args.get('abbreviation') cypher = 'MATCH (l:League) WHERE l.abbreviation={abbreviation} RETURN l;' records = query(cypher, abbreviation=abbreviation) return records.single() schema = Schema(query=Query) app = Sanic(__name__) app.add_route(GraphQLView.as_view(schema=schema, graphiql=True), '/') app.run(host="127.0.0.1", port=8000, debug=True) This is my proof of concept. Clearly this script needs to be cleaned up and abstracted away into modules. But, the point of the matter is that when taking on a side project. Step out of the comfort zone and grab a whole bunch of new tools. Because, in doing so, I have been inspired to to build several new tools. All three of those mini side projects have been fun. And I would have built none of them if I had stayed inside the lines. Go ahead. Build something new. ▄▄▄▄▄ ▀▀▀██████▄▄▄ _______________ ▄▄▄▄▄ █████████▄ / \ ▀▀▀▀█████▌ ▀▐▄ ▀▐█ | Gotta go fast! | ▀▀█████▄▄ ▀██████▄██ | _________________/ ▀▄▄▄▄▄ ▀▀█▄▀█════█▀ |/ ▀▀▀▄ ▀▀███ ▀ ▄▄ ▄███▀▀██▄████████▄ ▄▀▀▀▀▀▀█▌ ██▀▄▄▄██▀▄███▀ ▀▀████ ▄██ ▄▀▀▀▄██▄▀▀▌████▒▒▒▒▒▒███ ▌▄▄▀ ▌ ▐▀████▐███▒▒▒▒▒▐██▌ ▀▄▄▄▄▀ ▀▀████▒▒▒▒▄██▀ ▀▀█████████▀ ▄▄██▀██████▀█ ▄██▀ ▀▀▀ █ ▄█ ▐▌ ▄▄▄▄█▌ ▀█▄▄▄▄▀▀▄ ▌ ▐ ▀▀▄▄▄▀ ▀▀▄▄▀ photo credit: wizzer2801 Classic IBM PC Full via photopin license
https://brewmaster.tech/2017/09/28/my-new-development-stack-using-python-graphql-and-neo4j
CC-MAIN-2019-13
refinedweb
974
68.57
How to Deploy Your Secure Vue.js App to AWS 'vue' import Router from 'vue-router' import Home from '@/components/home' import Secure from '@/components/secure' Vue.use(Router) let router = new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/secure', name: 'Secure',: 'history', })for: - Windows: - Mac/linux run pip install awscli After you’ve installed aws-cli, you will need to generate keys within AWS so you can perform actions via the CLI. - Choose your account name in the navigation bar, and then choose My Security Credentials. (If you see a warning about accessing the security credentials for your AWS account, choose Continue to Security Credentials.) - Expand the Access keys (access key ID and secret access key) section. - Choose Create New Access Key. A warning explains that you have only this one opportunity to view or download the secret access key. It cannot be retrieved later. - If you choose Show Access Key, you can copy the access key ID and secret key from your browser window and paste it somewhere else. - If you choose Download Key File, you receive a file named rootkey.csvthat contains the access key ID and the secret key. Save the file somewhere safe. Note: If you had an existing AWS account or are not using root credentials. You can view and generate your keys in IAM. Now that you have your Access Key and Secret Access Key, you need to configure the cli. In your console run aws configure and paste in your keys. $ aws configure AWS Access Key ID [None]: YOUR KEY AWS Secret Access Key [None]: YOUR SECRET Default region name [None]: us-east-1 Default output format [None]: ENTER Now, you can use the aws-cli to sync your ./dist folder to your new bucket. Syncing will diff what’s in your ./dist folder with what’s in the bucket and only upload the required changes. aws s3 sync ./dist s3://your-bucket-name Tab back to your S3 bucket endpoint, and you should see your site hosted on S3! For convenience, add the following script entry to package.json so you can run npm run deploy when you want to sync your files. "scripts": { "deploy": "aws s3 sync ./dist s3://your-bucket-name" } Distribute your App with Amazon CloudFront CDN Amazon S3 static web hosting has ultra-low latency if you are geographically near the region your bucket is hosted in. But, you want to make sure all users can access your site quickly regardless of where they are located. To speed up delivery of your site, you can AWS CloudFront CDN. CloudFront is a global content delivery network (CDN) that securely delivers content (websites, files, videos, etc) to users around the globe. At the time of writing this article, CloudFront supports over 50 edge locations: Setting up a CloudFront Distribution takes just a few minutes now that your files are stored in S3. - Go to CloudFront Home - Click Create Distribution, and select Get Started under Web settings - In the “Origin Domain Name” you should see your bucket name in the drop-down. Select that bucket and make the following changes: - Viewer Protocol Policy: “Redirect HTTP to HTTPS”. (This is a secure app, right!?) - Object Caching: “Customize”. And set Minimum TTL and Default TTL both to “0”. You can adjust this later to maximize caching. But, having it at “0” allows us to deploy changes and quickly see them. - Default Root Object: “index.html” - Click Create Distribution The process can take anywhere from 5-15 minutes to fully provision your distribution. While you wait, you need to configure your distribution to handle vue-router’s history mode. Click on the ID of your new distribution and click the “Error Page” tab. Add the following error pages. These error page configurations will instruct CloudFront to respond to any 404/403 with ./index.html. Voila! Click on the “General” tab, and you should see an entry for “Domain Name”. The Domain Name is the publicly accessible URL for your distribution. After the status of your new distribution is Deployed, paste the URL into your browser. Test to make sure the history mode works by navigating to the secure page and refreshing your browser. Add Authentication with Okta To use Okta, you must first have an Okta developer account. If you don’t have one you can create a free account. After you are logged in, click “Applications” in the navbar and then “Add Application” button. Make sure to select “Single-Page App” as the platform and click Next. You will need to add your CloudFront URL to both Base URIs and also as a Login redirect URIs, otherwise Okta will not allow you to authenticate. Your application settings should look similar to this (except for your CloudFront URL). Note: Make sure to use HTTPS when entering your CloudFront URL. Take note of your “Client ID” at the bottom of the “General” tab as you will need it to configure your app. Add Secure Authentication to Your App Okta has a handy Vue component to handle all the heavy lifting of integrating with their services. To install the Okta Vue SDK, run the following command: npm i @okta/okta-vue@1.0.1 Open src/router/index.js and modify it to look like the following code. Also, make sure to change {clientId} and {yourOktaDomain} to yours! import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/home' import Secure from '@/components/secure' import Auth from '@okta/okta-vue' Vue.use(Auth, { issuer: 'https://{yourOktaDomain}/oauth2/default', client_id: '{clientId}', redirect_uri: window.location.origin + '/implicit/callback', scope: 'openid profile email' }) Vue.use(Router) let router = new Router({ mode: 'history', routes: [ { path: '/', name: 'Home', component: Home }, { path: '/implicit/callback', component: Auth.handleCallback() }, { path: '/secure', name: 'Secure', component: Secure, meta: { requiresAuth: true } } ] }) router.beforeEach(Vue.prototype.$auth.authRedirectGuard()) export default router Next is to lock down the /secure route to only authenticated users. Okta’s Vue SDK comes with the method auth.authRedirectGuard() that inspects your routes metadata for the key requiresAuth and redirects unauthenticated users to Okta’s authentication flow. Finally, make some style changes to App.vue <template> <div id="app"> <div> <a href="#" v-Login</a> <div v-else> Welcome {{ activeUser.email }} - <a href="#" @click.Logout</a> </div> </div> > <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style> In your terminal, restart the dev server via npm run dev. Tab to your browser and open. If you click “Login” or “Go to secure page” (the protected /secure route), you should get Okta’s authentication flow. Clicking either of these should show you as logged in and you should be able to access the Secure Page. Build a Secure Express REST Server Finally, we are going to build an Express server to respond to /hello and /secure-data requests. The /secure-data will be protected and require an authentication token from the frontend. This token is available via $auth.getUser() thanks to Okta’s Vue SDK. To get started, create a new directory for your server. mkdir secure-app-server cd secure-app-server npm init -y Then install the required dependencies. npm install -s express cors body-parser @okta/jwt-verifier aws-serverless-express Next is to create a file that will define the application. Copy the following code into app.js and change {clientId} and {yourOktaDomain} to yours. const express = require('express') const cors = require('cors') const bodyParser = require('body-parser') const authRequired = () => { return (req, res, next) => { // require! } } // public route that anyone can access app.get('/hello', (req, res) => { return res.json({ message: 'Hello world!' }) }) // route uses authRequired middleware to secure it app.get('/secure-data', authRequired(), (req, res) => { return res.json({ secret: 'The answer is always "A"!' }) }) module.exports = app Create one last file that loads up the app and listens on port 8081. Create ./index.js and copy the following code. const app = require('./app') app.listen(8081, () => { console.log('listening on 8081') }) Start the server by running node ./ in your console. Tab to your browser and open. You should see our JSON payload. But, loading should result in an error. Call the Secure API Endpoint from Your Vue.js Frontend With your secure Express REST server still running, navigate back to your client and install axios so you can call the /secure-data endpoint. npm i axios Modify ./src/components/secure.vue so that it will get the access token from the Okta Vue SDK and send the request to the API. <template> <div> <h1>Secure Page</h1> <h5>Data from GET /secure-data:</h5> <div class="results"> <pre>{{ data }}</pre> </div> <div> <router-linkGo back</router-link> </div> </div> </template> <script> import axios from 'axios' export default { data () { return { data: null } }, async mounted () { let accessToken = await this.$auth.getAccessToken() const client = axios.create({ baseURL: '', headers: { Authorization: `Bearer ${accessToken}` } }) let { data } = await client.get('/secure-data') this.data = data } } </script> <style> .results { width: 300px; margin: 0 auto; text-align: left; background: #eee; padding: 10px; } </style> Tab back to your browser and reload your web app. Navigate to the, and you should see the results from the API call. Configure Serverless and Deploy the Express API Serverless is an open-source AWS Lambda and API Gateway automation framework that allows you to deploy your app into a serverless infrastructure on AWS. The term “serverless” (not to be confused with the software Serverless) is used to describe an app running in the cloud that doesn’t require the developer to provision dedicated servers to run the code. Serverless uses AWS Lambda and AWS API Gateway to run your express API 100% in the cloud using only managed services. AWS Lambda is a service that lets you run code in the cloud without provisioning or managing servers. And, AWS API Gateway is a service that makes it easy for developers to create, publish, update, monitor, and secure API’s at scale. Combining both of these services give you a robust platform to host a secure API. To get started with Serverless, install it globally. npm install -g serverless Next, you need to create a Serverless configuration in your server app. Use the following command from within your ./secure-app-server project. serverless create --template aws-nodejs --name secure-app-server Open up serverless.yml and modify it to look like the file below. When you create a Serverless configuration, it contains a lot of boilerplate code and comments. The following structure is all you need to get the app deployed. service: secure-app-server provider: name: aws runtime: nodejs8.10 stage: dev functions: api: handler: handler.handler events: - http: path: "{proxy+}" method: ANY cors: true The provider spec informs Serverless that your app runs NodeJS and targets deployment on AWS. The functions outlines a single handler that should handle ANY HTTP requests and forward them your app. To finish up Serverless configuration, modify handler.js to the following code. It uses aws-serverless-express which is a neat little package that proxies ALL API requests to a local express app. 'use strict'; const awsServerlessExpress = require('aws-serverless-express') const app = require('./app') const server = awsServerlessExpress.createServer(app) exports.handler = (event, context) => { awsServerlessExpress.proxy(server, event, context) } Finally, you should be ready to deploy your app via Serverless. Run the following command. serverless deploy This process will take a few minutes to provision the stack initially., Once completed, you should see an endpoints entry under “Service Information” (your URL will be slightly different than mine). endpoints: ANY -{proxy+} To test it out, navigate to and you should see our hello world message. Attempting to go to should result in an error. Change Frontend Vue to Use Production API Up until this point, your frontend app has been configured to call the API hosted locally on. For production, you need this to be your Serverless Endpoint. Open ./src/components/secure.vue and replace baseURL with your endpoint within mounted(). baseURL: '', Finally, build your app and deploy it to CloudFront. npm run build npm run deploy Navigate to your CloudFront URL, and you should have a working app! Congratulations on a job well done! If your CloudFront URL failed to pull the latest version of your web app, you might need to invalidate the CDN cache. Go to your distribution, click on the Invalidations tab. Click Create Invalidation and invalidate paths “/*”. It will take a few minutes, but once it’s complete, you should be able to pull in the latest version. Final Thoughts Amazon Web Services is a robust platform that can pretty much do anything. But, it has a relatively steep learning curve and might not be right for all cloud beginners. Nonetheless, I encourage you to dig more into what AWS provides and find the right balance for your development needs. You can find the full source code for this tutorial at: and. Here are a few other articles I’d recommend to learn more about user authentication with common SPA frameworks. - Build a Basic CRUD App with Vue.js and Node - Add Authentication to Your Vanilla JavaScript App in 20 Minutes - Build a React Application with User Authentication in 15 Minutes - Build an Angular App with Okta’s Sign-in Widget in 15 Minutes Please be sure to follow @oktadev on Twitter to get notified when more articles like this are published.
https://www.sitepoint.com/deploy-your-secure-vue-js-app-to-aws/
CC-MAIN-2020-10
refinedweb
2,242
66.44
I have the sneaking suspicion that I ought to punt and try to implement EEE Cooks in Sinatra + CouchDB, but I really would like to give Rails3 a least a cursory go. The chain is not about getting it done, but doing something, so... Some Git Yak Shavin I again start the night with rm -rf *(to get rid of rails edge) in my main application code directory. I then git checkout .to get to my clean repository, but a quick git statusreveals: cstrom@jaynestown:~/repos/eee-code$ git statusDang it. My submodule checkout of rails edge is still hanging about. Since the lightweight revert did not work, may the higher powered # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # new file: .gitmodules # new file: vendor/rails # git resetmight? cstrom@jaynestown:~/repos/eee-code$ git reset --soft HEAD^Aw crap. Now git thinks that my browse_meal feature definition is a new file. I am beyond my depth with git, so time for brute force: cstrom@jaynestown:~/repos/eee-code$ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # new file: .gitmodules # new file: features/browse_meals.feature # new file: vendor/rails # cstrom@jaynestown:~/repos/eee-code$ cd ..Hopefully, I can figure out how to really do this before I need to delete the Rails3 spike. cstrom@jaynestown:~/repos$ rm -rf eee-code/ cstrom@jaynestown:~/repos$ git clone git://github.com/eee-c/eee-code.git Initialized empty Git repository in /home/cstrom/repos/eee-code/.git/ remote: Counting objects: 7, done. remote: Compressing objects: 100% (5/5), done. remote: Total 7 (delta 0), reused 0 (delta 0) Receiving objects: 100% (7/7), 1.06 KiB, done. cstrom@jaynestown:~/repos$ cd eee-code/ cstrom@jaynestown:~/repos/eee-code$ ls features README.rdoc cstrom@jaynestown:~/repos/eee-code$ git status # On branch master nothing to commit (working directory clean) On To Rails 3?At least I would like to move on to Rails 3, but how to get it? There is no clone URL for Rails 3 on github—the URL is the same as the master (yes, I really am pretty much a git newb). The answer is to clone the repository URL, but to specify the desired branch: cstrom@jaynestown:~/repos/eee-code$ git submodule add -b 3-0-unstable git://github.com/rails/rails.git vendor/railsAfter that, I ran into problems with Rails (they call it unstable for a reason). Specifically, I kept getting errors along the lines of Initialized empty Git repository in /home/cstrom/repos/eee-code/vendor/rails/.git/ remote: Counting objects: 95428, done. remote: Compressing objects: 100% (21582/21582), done. remote: Total 95428 (delta 73746), reused 94376 (delta 72754) Receiving objects: 100% (95428/95428), 17.18 MiB | 128 KiB/s, done. Resolving deltas: 100% (73746/73746), done. Branch 3-0-unstable set up to track remote branch refs/remotes/origin/3-0-unstable. NameError: uninitialized constant ActionController::RewindableInput, which I ultimately resolved with this patch: cstrom@jaynestown:~/repos/eee-code/vendor/rails$ git diff railties/lib/initializer.rbUnfortunately, I have to call it a night at this point. Hopefully I can make a bit more progress on Rails3 tomorrow. If not, I may have to abandon this trail... diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index da064c8..26b90f0 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -545,7 +545,7 @@ Run `rake gems:install` to install the missing gems. def initialize_metal configuration.middleware.insert_before( - :"ActionController::RewindableInput", + :"ActionDispatch::RewindableInput", Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?) end
https://japhr.blogspot.com/2009/03/bleeding-edge-rails.html
CC-MAIN-2018-05
refinedweb
604
52.26
Introduction: Bike Wheel WS2811 LED Effects With Arduino [TODO: insert a neat video or pictures from actual riding] [Note the Arduino sketch works but is work in progress, see last step for link] Persistence of Vision (POV) effects let you display arbitrary images with just a few controllable pixels on a fast moving object by changing the pixels' colours fast enough. There's plenty of existing POV projects using a LED strip on a spinning object, like a bike wheel or a spinning CD. This is yet another implementation of POV on a bike wheel. Adafruit has a similar project, they sell the kits and have it well documented, there's probably a few more implementations. All the ones I've seen used custom LED controller circuits though. This instructable uses just the most obvious, off-the-shelf elements and requires some basic soldering and a lot of zip-ties. It also allows you to switch the LED effect programmes without getting off your bike, by using short sequences of braking ("gestures") which are detected by the same sensors we use for keeping track of the wheel position. Wifi, bluetooth, etc. control would also be easy but I've not done that. Here are the materials I used, but you may have similar components at home that are likely compatible and will work just as well. - 1.5m of the well-known WS2811 / WS2812B / compatible LED strip. I got a 5m reel of the "waterproof" variant at aliexpress.com for about $50 (here's one seller). You may not need 1.5m. I have the LEDs in 25cm 15-LED strips mounted on 6 spokes on a standard 28" wheel. If your wheels are 26" you might want 14 LEDs for example and you can start with just one spoke. - A small Arduino-compatible board. I used the popular cheap $2.12 Pro Mini clones from aliexpress.com (10 MOQ - here's the seller). My firmware code should work with any Atmega328-based board. - A 6+ DoF sensor board like the popular $10, 10DoF Acc+Gyro+Mag+Baro IMUs from e-bay. My code is only tested with the Invensense MPU6050 sensor chip (here's my seller - but you can grab a similar board with the BMP085 instead of the higher-precision MS5611 baro and it'll be below $10 - we won't use the barometer here anyway) - A lithium-polymer RC battery with enough capacity for your rides, the amount these LEDs consume depends a lot on how they're used, but they're quite power-hungry. I'm using a variety of batteries, for example this 3S1P 3700mAh one from HobbyKing, which should last for a good few hours in any configuration. You don't need that high a C rate, even 5C would do. Any voltage between 7V and 30V will do so a 2S or higher LiPo. Note the battery width matters because it needs to fit between the spokes of your wheel somewhere close to the hub end. - A 5V step-down regulator, optimally a switching one. In RC airplane hobbies those are called BECs. I use a 25W one similar to this. You may not need all 25W if using fewer LED strips than 6 but it's safe to get a bigger one, and my 25W BEC already gets hot. - Some 4-wire cable, male & female pin headers for the plugs and the sockets, thin zip-ties, optimally some hot-glue. Soldering stuff. Perhaps some more mounting and water-proofing material if you can make use of it. My setup isn't water-proof and my mounting doesn't look very pretty. This should come out at about $100 in total or less than $50 per wheel. You also need a LiPo charger if you don't have one. You'll also need a bike (or at least the wheel). If you're new to Arduino, you should know that you'll probably need a USB-to-Serial adapter to program the board, unless the Arduino has a USB port already or unless you have a real serial port & cable in your computer. If you don't code, you probably want to reproduce my setup exactly. If you're not new to Arduino, my code currently has just some basic LED programs, you'll probably want to modify/add your own. The code achieves about 400-700 Frames Per Second, so at, say, 20km/h, you'll have only about 200 virtual pixels per LED along the perimeter depending on the wheel diameter and how intensive the effect's code is on the Arduino. I'm not storing bitmaps on the Arduino, each effect (programme) is a function that calculates what the current colour of each LED needs to be. More info on the firmware in the final step of this instructable where we program the Arduino. Let's connect the pieces together. Step 1: The Wiring General View Here's the diagram of my wiring. There's no individual electrical components, just the battery, LEDs, voltage regulator, the Arduino and cables. One thing that I'd have added in retrospect is a connection between BAT+ and one of the Arduino analog inputs, e.g. A3 (PC3) through voltage divider resistors so the Arduino can measure the battery voltage. Discharging a LiPo cell below 3V destroys that cell. [Note: I'm not sure what those exact LEDs are called, possibly WS2812B. In the diagram I used WS2811 as the name of the family of WS281x chips and their clones] Step 2: Arduino Power and Serial Pins To power the Arduino, we'll connect it to the voltage regulator through its VCC and GND pins. The regulator comes with a "servo connector" which looks like 3-pin standard female pin-header. So we just need some male pin-headers on the Arduino. On the Pro Mini the through holes for the power pins are on the opposite side from the reset button, together with three serial port pins: Tx, Rx and DTR. We'll also be using the three serial port pins for programming, so just solder a 5-pin male header row in the holes labelled: GND, VCC, RXT, TXD, DTR (the DTR label is on the bottom of the PCB) The power connector is ready. When you connect the regulator's servo lead just make sure the black or brown wire connects to GND, red to VCC and the third pin, which will connect to RXT, may be unpopulated on the servo connector or it may have a dummy white or yellow wire. Step 3: Connectors for the LED Strips I started with one strip of LEDs for testing but made connectors for 6 of them for expansion and later ended up using six. Each "connector" is a 4-wire female pin-header sliced off from a 40-pin row. I mounted the headers perpendicularly to the side of the Arduino board with some distance between each header so that the male connectors can be slightly thicker than a pin header, as in the photo. The connector has the following lines starting from the side closer to the Arduino: GND, 5V, DOUT & DIN. I was too lazy to make a proper PCB to solder the headers in, so I sort of made an ugly ladder of wires initially held in the air by a third hand. The GND lines of all 6 headers are connected together by a piece of rigid wire like those of a through-hole resistor, same for the 5V lines of the connectors. If the pictures and the diagram from step 1 are enough for you to follow then you don't need to read all the details below. Sorry I don't have a picture from before the whole shebang was covered in hot glue, you can also see I had a few redesigns there... the thing holds together Ok though, I made a few hundred kilometres with it. I'm not that great at soldering so this is what I did: - cut off 6 pieces of 4-pin female headers. - grab each one in turn in a third hand, tin all 4 pins so they're easier to solder things to. Whenever soldering connectors of any kind it's good practice to have them plugged into the opposite side of the connector (plug or socket) to increase heat capacity and make it difficult for you to accidentally melt the plastic. So put some male headers in the female connectors when soldering. - grab a small through-hole resistor in the third hand, so that it has two pieces of straight wire sticking out on both sides. - slide hot soldering iron along the wire feeding it a little tin so as to cover both wires in tin. - starting from one end grab a female header with pliers, touch one of its pins to the resistor wire, heat for a moment for the pin to stick to the wire with the tin already present. - once all 6 pieces of female headers are holding to the resistor wire, cut off that side of wire from the resistor. - now hold this structure with pliers again, and with the resistor still held by the third hand touch the second pin of all the header rows to the resistor wire and solder the second pin of each row. - cut the wire on the second side of the resistor, store the resistor for future projects. - you can add blobs of tin here and there to improve the connections. Now we'll need to connect these headers to the corresponding Arduino pins and also make some connections for the LED signal between pairs of headers. Use another piece of wire to connect the ground line under the headers to the GND pin on the long side of the Arduino PCB, same for the 5V (VCC) line. Perhaps use a cable with plastic jacket to avoid shorting the wires where they cross. To connect the signal lines you need to establish some numbering for the header connectors, it doesn't really matter what it is but we need to call them something. Use another piece of wire to connect pin 3 of connector one to pin 4 (the one furthest from the Arduino) of connector two. Same for pin 3 of connector 3 & pin 4 of connector 4. Same for pin 3 of connector 5 & pin 4 of connector 6. Then connect the pin 4 (the one furthest from the Arduino) of connector 1 to Arduino A2 hole, pin 4 of connector 3 to Arduino A1 hole, pin 4 of connector 5 to Arduino A0 hole. In summary, these are all the connections needed: - between Arduino GND and pin 1 of all 6 connectors, - between Arduino VCC and pin 2 of all 6 connectors, - between Arduino A2 and pin 4 of connector 1, - between Arduino A1 and pin 4 of connector 3, - between Arduino A0 and pin 4 of connector 5, - between pin 3 of connector 1 and pin 4 of connector 2, - between pin 3 of connector 3 and pin 4 of connector 4, - between pin 3 of connector 5 and pin 4 of connector 6, You'll notice pins 3 of connectors 2, 4 and 6 are left unconnected. Sorry for the pictures above, you can't see any of that there. There's one more thing that I'd recommend doing: to avoid all of the current needed by the LEDs from passing through the very thing GND and VCC lines on the Arduino PCB, solder a piece of wire between the power connector's GND (the male headers we added in the previous step) to the GND wire under the 6 LED connectors, same for the VCC lines. You can solder these to the bottom end of the male headers that come out under the Arduino. Step 4: Connect the IMU to the Arduino Most of the $10 IMUs (sensor boards) from E-bay / aliexpress / etc. have an onboard 3.3V regulator so you can connect a 5V source directly. You only need to connect four lines between the Arduino and the sensor board, and that accounts both for powering the board and for two-way communication. The pin names on the sensor board will be normally: GND, VCC_IN, SDA and SCL, the other pins can be left unconnected. I connected my GND and VCC lines to the GND and VCC lines under my LED strip connectors. The SDA line connects to the Arduino's SDA line which is labelled A4, and the SCL is labelled A5. On the popular, cheap Pro Mini clones, the holes for those pins are located on the same side of the board as the reset button, together with A7 & A8. I believe on the original Arduino Pro Mini the A4 & A5 pins are set apart on the longer side of the PCB close to A2 & A3. I used a flexible 5cm 4-wire cable for the connection so that I can orient the sensor board independently from the Arduino if needed, since the sensor board is going to sense the wheel's orientation. I used no pin headers because I don't plan to disconnect the sensor board. Step 5: Power the Regulator Unless your regulator has an input connector compatible with the discharge connector of the battery (T-dean, XT60, etc.) it's probably easier to cut off whatever input connector it has and use male pin-headers to plug into the battery's charger jack. For a 2-cell LiPo the charger connector will have 3 wires, for a 3-cell there will be 4 wires, etc. We want to connect the regulator's red wire to the charger connector's red and the regulator's black to black. In other words we only need the first and the last wire from that connector and ignore those in the middle. But we'll use a pin row with all 4 pins (or as many as the charger connector has) to make a firmer grip between the "plug" and the "socket". So just solder the regulator's two input wires to the two pins at the ends of the row. Since the headers doesn't have anything to prevent you from plugging them in reverse, be very careful to connect the red wire side to the battery's red wire. In my case I actually have both a 3-pin and a 4-pin male header strip so that I can use either a 2S or a 3S battery. Again sorry for not having a good pic. Step 6: Mount the Battery and Controller in the Wheel You might want to mount the whole thing now or later after testing that it works with the LED strips that we'll prepare next. The mounting is all up to you, myself I just used a lot of zip-ties and pieces of 3-mm plywood to hold it all together. The sensor board should be mounted roughly perpendicular to the wheel axis or within the wheel "disc" plane, but doesn't need to align exactly -- the software can account for some misalignment. Here are some additional notes on what to avoid: - Avoid squeezing the LiPo battery too hard with the zip ties and make sure the centrifugal force won't squeeze or pinch it against something once you're riding the bike and the wheel is spinning. These batteries are fragile and can be explosive or catch fire when damaged. The centrifugal force obviously acts in the direction away from the wheel hub and is smallest close to the centre. So mount it close to the centre and perhaps use a piece of something flat between the battery and the zip ties to maximise the surface on which the force is applied. - Avoid putting the sensor board too far away from the wheel hub too because the code needs to use the accelerometer readings for gyro drift compensation. My sensor board is about 6cm from the wheel centre. Too far away and, at higher speeds, the centrifugal force will saturate the accelerometer's range and the program won't be able to make any sense from the data. Step 7: Prepare LED Strips I use 6 strips of LEDs on 6 spokes, you may want to use fewer for a start. This is how to prepare one strip. Cut a pieces of tape 15-LEDs long, cut it off at the white dashed lines marked on the tape between the chips. You can use scissors. If the tape is protected by a silicon rectangular tube like mine just cute the tubing too. If the tape comes with some wires pre-soldered at the end, desolder them. For now slide the tape out of the silicon jacket. Prepare a piece of 4 wire cable long enough to connect the LED strip to the sockets we added to the Arduino board. For the strips to be mounted on the same side of the wheel as the controller board, you can use a shorter cable, for the ones on the opposite side of the hub they need to be longer. Obviously an excess cable is less of a problem than a short cable. You also need a single wire of about the same length as the LED strip to connect the output (DO pin) from the last WS2811 chip. Solder one end of the long wire to the DO pin. Them the four-wire cable's wires need to be connected in the following order: - GND pin on the input end (the first LED) of the strip, - 5V pin on the input end, - DO pin from the opposite end through the single wire we just added, - DI pin on the input end. Solder a 4-pin male header on the other end of the cable. Also slide the jacket back on. Step 8: Mount the LEDs, Add Hot Glue Before mounting the LEDs you may want to secure the ends of the silicon tube around the LED strip with some hot glue, try to inject some of it into the tube. This will at least prevent humidity from staying inside the LED strip, so you don't have to take them all off the wheel when there's a chance of rain. You'd probably still want to leave the other electronics at home though, and you definitely want to take out the battery. If you know of a good way to waterproof the whole setup, please comment. I hear that WD-40 is great at protecting SMD electronics from water, just spray some of it over all the PCBs. Note however that you shouldn't spray anything into the barometer chip aperture on the sensor board or cover it with hot-glue unless you don't plan on ever using it. I like to secure all the hand soldered elements like the male and female headers, with hot-glue to also add some structural support for the connectors and make them easier to grab with fingers or pliers without risk of breaking the solder joints. With the hot-glue gun the blobs always come out quite ugly but you can later use a hot-air gun with a wide nozzle to melt the glue, force it into holes or even spread it over the whole Arduino PCB. Finally the LED strips are just zip-tied to the spokes, make sure they don't slide along the spoke. In my case I mounted the 6 strips on pairs of adjacent spokes on three opposite sides of the wheel due to the symmetry present in the spoke pattern. I suppose this spoke pattern is quite standard. Having strips close together helps make POV text readable at a low speed. Step 9: Flash a Program on the Arduino Check out my firmware code from, not everything works yet -- check the github page for current status. The sketch depends on the following Arduino libraries: I2Cdev, MPU60X0 (both ship with the FreeIMU library), and WS2811. The WS2811 library needs to be the one from because that version supports significantly faster updating of the LED's colours. Once the libraries are installed, just load wheel.ino into the Arduino IDE and upload it to the Pro Mini board. If your laptop doesn't have USB overcurrent protection, make sure the electronics are powered from the LiPo battery during flashing, or disconnect the LEDs. For development I used a long cable that connects the Arduino's GND, TXD, RXD and DTS lines to the USB-to-Serial adapter, but the VCC (and GND) to the voltage regulator & battery. The cable is about 70cm allowing the wheel to make a few turns without disconnecting from PC. Be the First to Share Recommendations 26 Comments 3 years ago i can't find the lib #include "./Timers.h" please help post its link 4 years ago hello!please Hape me! blinkenbike-master\blinkenbike-master\wheel\wheel.ino: In function 'void setup()': wheel:234: error: 'acc_update' was not declared in this scope exit status 1 'acc_update' was not declared in this scope Reply 4 years ago Hi, not sure why you're getting this but try moving the acc_update declaration from line 637 somewhere near the top of the file, e.g. L22. But it sounds like you're either compiling outside of the Arduino IDE, or this is not the first error. Please report the top error that is printed because in programming one error will often trigger an avalanche of other, mostly unhelpful messages. Make sure you have the MPU60X0 library installed correctly. Reply 4 years ago Hello; I am getting the same error after fixing the avalanche of errors. Now MP60X0 Libraries gives tons of errors. Do you have any idea why could that happen? Reply 4 years ago Sorry I don't... but if you use the same version of Arduino that I was using, which must have been either 1.0.1 or 1.5.4, it should really build with not errors. Please check with a 1.5.x Arduino version and if it still fails... then we'll look at whether any of the libraries has changed maybe. Reply 4 years ago Hello again. I have tried everything but it doesnt work still. İs there any chance that libraries changed since you first wrote this code? Me and my 3 other friends tried but still the same error and after that avalance of errors. Reply 4 years ago So I tried building with Arduino 1.8.2 and got the same error about acc_update(). I added a forward declaration just before setup() and it compiles fine, give it a try. I uploaded this change to github so if you checked the code out with git, just run "git pull", if you downloaded the .zip, just re-download it. Arduino 1.8 must have changed how they generate the internal forward declarations. Reply 4 years ago Thank you Reply 4 years ago yes the problem solved. Thank you for your concern. You are very kind for helping us thanks again. Reply 4 years ago The libraries gives the errors. İs there any chance that changing the codes acording to the new versions. We really want to make this project :) thanks for your concern. Reply 4 years ago Which one specifically? Try the original FreeIMU from Fabio Varesano, it hasn't changed:... In any case I've uploaded a .zip containing FreeIMU, the WS80211 library and a .hex file I just build with Arduino 1.8.2 for anyone that needs those, unfortunately I have no way to test the .hex file until next month: 5 years ago I am curious, why did you do this with 6 strips? why not just one? what are the advantages (dis-advantages?) In my mind and in the other kits, is makes sense that you only seed one strip on one radius (and peddle very fast.) Reply 5 years ago So that you don't have to go impossibly fast. In my experience a single spoke is not enough to get POV effect other than for tiny repeating images, two spokes might be ok depending on velocity and also on the timing precision of the board, and the LED density. The 16MHz arduino I used is rather slowish for this task. The commerical kits I've recently seen use two spokes, but have more LEDs/cm and probably a faster controller (today I'd just get one of these from aliexpress, they're cheap, waterproof and probably work) Reply 5 years ago thanks! 5 years ago coool! 6 years ago on Introduction Hello. Code hex. ??? thanks 6 years ago on Introduction You mentioned using a voltage divider to monitor battery voltage with the arduino. Do you have any recommendations for resistor values? Thanks for the project! 6 years ago on Introduction You were asking about waterproofing circuit boards... I am an EE and have done this before at home... All you need to do is use a clear acrylic spray paint and just paint your boards... This will effectively conformal coat your boards and make them waterproof. 7 years ago on Introduction Awesome project. Check this one out on LED's 7 years ago on Introduction awesome instructable!! thanks for sharing!! I think the proyects queue has change!!
https://www.instructables.com/Bike-wheel-WS2811-LED-effects-with-Arduino/
CC-MAIN-2021-43
refinedweb
4,241
77.47
I have a template: var colDateTemplate = { editable: true, width: 200, align: "center", sortable: true, sorttype: "date", editrules: { date: true }, editoptions: { size: 20, maxlengh: 10, dataInit: function(element) { $(element).datepicker({ showOn: 'both', dateFormat: 'dd/mm/yy', buttonImage: '/images/calendar-icon.png', buttonImageOnly: true }); } }, searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn'], dataInit: function(element) { $(element).datepicker({ showOn: 'both', dateFormat: 'dd/mm/yy', buttonImage: '/images/calendar-icon.png', buttonImageOnly: true }); } } } And when I'm searching and select th Is that a Custom Control? If so, you need to add a public property in it's code behind that will get or set the readonly property of the textbox of your calendar. public bool ReadOnly { get { return WatermarkExtender1.ReadOnly; } set { WatermarkExtender1.ReadOnly = value; } } Then you can set it like dtSupBookedFromDate.ReadOnly = true; You should make your Custom Control like this... <UserControl x:Class="WpfApplication2.ucCalender" xmlns="" xmlns:x="" xmlns:mc="" xmlns:d="" mc:Ignorable="d" d: <Grid Height="48" Width="303"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100*" /> <ColumnDefinition Width="100*" /> <ColumnDefinition Width="100*" /> </Grid.ColumnDefinitions> <ComboBox Height="30" HorizontalAlignment="Left" Margin="2,2,2,2" You have to unbind/bind your datepicker to your TextBox every time the page (re-)loads. I don't know how your timepicker works, but with jQueryUI's you can use something like that (js): function pageLoad() { $("#myTextBox").unbind(); $("#myTextBox").datepicker(); } Your textbox should use ClientIDMode="Static" for that. can you please check this link where you can popup datepicker with textbox id I think that the reason of the problem which you described is wrong parameters of jQuery UI Datepicker which you use. You use formatter and formatoptions parameters of datepicker which not exists. Instead of that you should use dateFormat option which format described here. UPDATED: The main reason of the problem which you describe is wrong date format which you use. It's important to understand that srcformat and newformat of formatoptions should have PHP date format, but jQuery UI Datepicker supports another format which described here for example. The input data 11/1/2013 12:00:00 AM contains both date and time. On the other side jQuery UI Datepicker support date only. Because you use newformat: 'yy-M-d' then I suppose that you want just ignore the time part of the date. In the case I I think the problem is, that the DatePicker isn't a single Widget but a bunch of them. And according to the documentation they are always used within Dialogs, e.g. DatePickerDialog. So I suggest you create a button dynamically and add an on-click callback that opens a DatePickerDialog. The best idea is to consider using a custom binding like the one in this answer: knockoutjs databind with jquery-ui datepicker or this answer: Knockout with Jquery UI datepicker. If you don't need the two-way data-binding, then a minimal custom binding would be simply: ko.bindingHandlers.datepicker = { init: function(element) { $(element).datepicker(); //handle disposal (if KO removes by the template binding) ko.utils.domNodeDisposal.addDisposeCallback(element, function () { $(element).datepicker("destroy"); }); } }; Note: This answer isn't complete. However, as it's too large for a comment and probably helpful (towards a solution) anyhow I've taken the liberty and posted it as an answer. Anyone that can complete this answer is invited to do so through an edit or by spinning off into another better answer. The thing that seems to be spoiling the party (taken from the documentation, emphasis mine): This will be called once when the binding is first applied to an element, and again whenever the associated observable changes value. If I hackisly prevent the update from doing its datepicker calls in the first update the datepicker won't break anymore (other issues do arise though). For the init I've added this line at the end: element.isFirstRun = true; Then the update method will do the follow Bootstrap datapicker plugin just support left orientation. You can check the original code here. However, it has some smartness to keep it in view. All you can use is: $("#dp3").datepicker({ orientation: 'left' }); orientation as right, top are not supported. I thought a little bit and I think what I would do is not possible... How could the datpicker calculate the days of the month if the year is not specified? So, Have you got any suggestions to force my users to change the year default value ? Please try the below: <script type = "text/javascript"> $(function () { $("#from").datepicker({ onSelect: function (date) { $("#to").datepicker("option","minDate", date); $("#to").datepicker("option","maxDate", new Date()); }, maxDate: 0 }); }); </script> red one, It would be helpful to share a jsFiddle of your code. At least let us know what scripts you are loading and styles you are loading and in which order. Since the datepicker is dependent on jQuery you need to make sure that jQuery is loading before your .js files. You asked about the bootstrap-responsive and bootstrap files. As long as you are linking to the correct one it should work. Hopefully that gives you a little direction. Will update when you share more information. Based on your comment above, I would guess your code is not executing because you have not included jquery.timePicker.js in your code. Download the file and include it like this: <script src="path/to/your/js/file/jquery.timePicker.js"></script> You don't need to include datePicker.js because datepicker is a plugin included with the jquery-ui library. (So really you do have datepicker included!) Also, looking at your comment, you do not need to have a ; after declaring a <script> tag Like this: <script></script> Not like this: <script></script>; EDIT I found the issue, it appears the jquery.timepicker.js library is quite old (2009). It was developed with a much older jquery version. When I run jquery.timepicker.js with a newer version of Did you google around? There are lot of links that can help you Instead of using date type inputs, just use text inputs. Since you don't care about date input support, you no longer need the Modernizr test. You may need to give them all the same class so that you can select them to initialize the date picker widget: HTML <input type="text" class="date"/> jQuery $('input.date').datepicker(); Working Demo take a look at the following demo: There is button which says "Set Min Date". so this will set Min date of another date picker. Basically the controls have a rich client side API. so you need to use the right methods to work with the controls from client side. So here is the JavaScript code to set Min Date on a date picker control: function getDatePicker() { var datePicker = $('#DatePicker').data("tDatePicker"); return datePicker; } function minDatePicker() { var value = $('#DatePickerMinOrMax').data("tDatePicker").value(); getDatePicker().min(value); } In the above code - DatePicker is the main control on which I want to set a min date. DatePickerMinorMax Below is the snippet for above requirement...... <head> <title>Testing</title> <link href="css/jquery-ui-start-custom-1.10.3.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .ui-datepicker-next, .ui-datepicker-prev { display: none; } </style> <script src="scripts/jquery-1.10.1.min.js" type="text/javascript"></script> <script src="scripts/jquery-ui-custom-1.10.3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('.ui-datepicker-prev ui-corner-all').hide(); $("#datepicker").datepicker({ changeMonth: true, changeYear: true, yearRange: "-0:c); That version of DatePicker uses hided inputs. So what you see is not what your input has as value, it has a unix datestamp. If you noticed the Date.parse($('arrival_date').value); was in the 70's, that's because javascript uses miliseconds and unix time is in seconds. To get the "real" day from the $('arrival_date').value you need to multiply by 1000. But you actually dont need that. To make the second DatePicker get the day from the first you can use this: onSelect: function (){ var depDate = $('departure_date'); if (depDate.value == ""){ depDate.value = $('arrival_date').value + 86400; } } This will add one day to the first datepicker date if the second is empty. The thing is that you will not see the change until the you open the datepicker, so if you change th You can get the options of the existing datepicker using this: var options = jquery('#datepicker').datepicker('option', 'all'); to get one specific option, for example the numberOfMonths: var numberOfMonths = jquery('#datepicker').datepicker('option', 'numberOfMonths'); I used this code snippet in a project once. Hope it helps: $(function() { calendar(); }); function calendar(){ //omitted datepicker init $(".calendar").datepicker("option", $.datepicker.regional["<%=locale%>"]); } All date field's css attributes are specified as calender and locale is retrieve in java code. I'm not familiar with CookieLocaleResolver, I used SessionLocalResolver but there should be equivalent way to get the Locale. public static Locale getLocaleFrom(HttpSession session) { return (Locale) session .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME); } And I remember we modified the datepicker for different locale values between Java and datepicker. You could use a mapping mechanism as an alternative solution.. Try binding SelectedItem property to ControlTemplate <ScrollViewer x:Name="PART_ContentHost" Content={TemplateBinding SelectedItem} can declare the DataContext property of the <TextBlockControl /> as the Text property of the "editor" <TextBox />: <wpfSandbox:TextBlockControl DataContext="{Binding Text, ElementName=editor}" /> and inside your control: <Grid> <TextBlock Text="{Binding}" /> </Grid>?
http://www.w3hello.com/questions/-DatePicker-control-in-Asp-net-
CC-MAIN-2018-17
refinedweb
1,562
57.77
java.lang.Object org.jboss.cache.search.Transformerorg.jboss.cache.search.Transformer public class Transformer This class is one that does all the 'conversion' work between JBossCache and Hibernate Search. This is where users can switch from Fqn and key to a documentId and vice versa. If the Fqn is in the form /a/b/c and the key - which has to be a String - is keystring; the documentId - which is also a String - will be "Fqn=[/a/b/c]Key=[keystring]" public Transformer() public static String getKey(String docId) docId- - for the keystring to be obtained public static org.jboss.cache.Fqn getFqn(String docId) docId- - for the Fqn to be obtained public static String generateId(org.jboss.cache.Fqn fqn, String key) throws InvalidFqnException, InvalidKeyException fqn- - standard call Fqn.fromString() key- - cannot be an object. InvalidFqnException InvalidKeyException
http://docs.jboss.org/jbosscache/searchable/1.0.0.GA/apidocs/org/jboss/cache/search/Transformer.html
CC-MAIN-2015-32
refinedweb
139
52.49
README React Natve Advanced StylesheetReact Natve Advanced Stylesheet Yes, it's another library that does very common thing, but it created because of lack of solutions with required functional to live "happy" live as react-native developer. RNAS provides functionality for theming your app with dynamically provided ( via react context, NOT with GLOBAL instance of something ) theme defenition, also it provides generation of styles depending on additionally passed values ( just call it props ). WARNING: Library recently created, and it's can change in near future, so think twice before using it right now ( or stick to specific version of npm package you want ). So, to get started we need to do few simple steps.So, to get started we need to do few simple steps. 1. Setup provider at top level of your app1. Setup provider at top level of your app import { Provider } from 'react-native-advanced-stylesheet'; // somewhere in your component // IMPORTANT: you need to pass new theme instance because under the hood it compared by ref equality, so be carefull and not mutate your theme while waiting to something will happen, and also be sure to provide same instance if theme not changing at the moment to avoid of recalculating of ALL currently exsisting styles <Provider theme={theme}>{/* Your components tree here */}</Provider>; 2. Somwhere in your code define stylesheet.2. Somwhere in your code define stylesheet. // define stylesheet // define has 2 overloads: // define(() => ({}), { }) // 1 - Dynamic styles 2 - Static styles which will be merged together but will not be recalculated // define({ }) - 1. Static styles. Just to keep consistant approach in project, probably will be better to use define instead of StyleSheet.create everywhere. const styleSheet = define((theme, { background }) => ({ root: { backgroundColor: background }, caption: { color: 'red' } })); // NOTE: here we have object { dynamic, staticStyles } which is format required for useStyles hook, so if you want to test your styles creator, just use .dynamic() and pass theme, props arguments to call it. Actually define is required for TS typization, because currently i didn't find other way to provide types for strongly type check and get resulting type matching requirements. // in your component file const YourComponent: React.FC = ({ background = 'tomato' }) => { // styles will be recalculated when theme in provided changed ( new instance passed ), or if second argument ( props ) will fail shallow compare check agains previous render value const styles = useStyles(styleSheet, { background }); return ( <View style={styles.root}> <Text style={styles.caption}>Caption</Text> </View> ); }; And we are done with setup! Styles recalculationStyles recalculation There are cases when we will need to recalculate styles and rerender components depending on some external conditions or events. For that reason you may use StyleContext and just hook { recalculate, theme } in your components by yourself. When calling recalculate it will trigger all mounted styles to recalc and rerender component. Also there is pre made component for defining subscriptions. You can use <RecalculateSubscription /> to do that. return ( <View> {/* Place it somewhere in your components, but probably on the top level */} <RecalculateSubscription // called on didmount on={recalculate => Dimensions.addEventListener('change', recalculate)} // called on willunmount off={recalculate => Dimensions.removeEventListener('change', recalculate)} /> </View> ); Example allows to subscribe on Dimensions change and rerender styled components. For Dimensions tracking already create <DimensionsSubscribtion /> component so you can import it and just place where it needed. PlansPlans - Add nested styles to allow structuring styles like: { input: { color: '#000', borderWidth: 1, focused: { borderColor: 'green' } } } - Add some built-in helper functionality like mixins. - Improve TS type support, currently there are few problems needed to be fixed ( for example when you define styles using "define" when first property added, next properties in style object will not be checked by TS to match exsisting in RN style properties ) - withStyles decorator ( for those who don't want to use it as hook ) - Write more tests. ( partially tested right now ). FeaturesFeatures If you want to offer some feature, feel free to write issue with request and it can be implemented later.
https://www.skypack.dev/view/react-native-advanced-stylesheet
CC-MAIN-2021-43
refinedweb
650
51.07
In article <mt1yscm7yu.fsf at astron.berkeley.edu>, Johann Hibschman <johann at physics.berkeley.edu> writes: > Joshua Marshall writes: > >>> This is infinitely more sane than: > >>> % perl -e 'print 500 + "cool"' >>> 500 > >> Comparing Python to Perl here doesn't seem very fair. They're very >> different languages. In general, I'm surprised by the urgency with >> which people often jump to compare them. > > Well, Perl's the only language that I know of that lets you add 500 to > "cool" without an error. Well, I suppose tcl might. But it's still a > fairly safe inference that the original poster was coming from Perl. > Well, my first guess was Java. public class Test { public static void main(String[] args) { int variableOne = 500; String myVariable = variableOne + "cool"; System.out.println(myVariable); } } gere(1)> javac Test.java gere(2)> java Test 500cool Since I havn't found a % operator or a printf function, I like it. /Fredrik (Well, I have gotten to like Haskell a lot more after learning Java, wrote a complete parser+typechecker for a little language, 211 lines in Haskell ~2400 lines in Java (and I'm not counting the generated code.))
https://mail.python.org/pipermail/python-list/2001-March/100327.html
CC-MAIN-2014-10
refinedweb
192
67.45
Minimize the Sum of Minimum and Second Minimum Elements from All Possible Triplets Introduction Greedy problems are often difficult to solve as they don’t have any predefined method of solving, and every new problem is a problem in itself. Thus only practice can help you to master it. But don’t you dare to worry, your best friend Ninjas is here to help you, and today we will one such frequently asked question, i.e., minimize the sum of minimum and second minimum elements from all possible triplets, which will help you to get a better grasp of the greedy algorithm. Problem Statement We have been given an array ‘ARR’. Our task is to minimize the sum of minimum and second minimum elements from all possible triplets in the array, with the constraint that a single element can be part of only one triplet. Let’s understand this by the following example. ‘ARR’ = [9, 1, 3, 4, 5, 2] Now we can form two triplets (i.e., number of elements (6) / 3 = 2). We can form a large number of triplets, but the ones that will give us the best answer are (1, 2, 9) and (3, 4, 5). Thus our answer would be 10. Intuition As we have to choose minimum elements, we will first sort the array in ascending order. Then we will traverse the array and form triplets by choosing two elements from the left side and one from the right side. This is done because we need to separate the maximum elements from each other. Thus, each maximum (starting from the rightmost) element is distributed among possible triplets. We will maintain a ‘FIN_ANS’ variable which will store the final answer. Now let’s look at the code. Code #include <iostream> #include <vector> #include <algorithm> using namespace std; // Function to minimize the sum of two minimum elements of every triplet. int TwoMinTriplets(vector<int> &arr) { // To store the final minimized sum. int finAns = 0; // Sorting the array. sort(arr.begin(), arr.end()); int i = 0; int j = arr.size() - 1; // Traverse the array. while (i + 1 < j) { // Now, as only minimum and second minimum elements need to be added, they will be added to 'FIN_ANS'. finAns += arr[i]; finAns += arr[i + 1]; i = i + 2; j = j - 1; } // Return the ans as the result. return finAns; } int main() { int n; cin >> n; vector<int> arr(n, 0); // Taking input. for (int i = 0; i < n; i++) { int element; cin >> element; arr[i] = element; } // Calling the function 'twoMinTriplets()'. cout << TwoMinTriplets(arr); } Input 6 1 9 2 4 5 3 Output 10 Time Complexity O(N * log N), where ‘N’ is the length of the array. As we are sorting the array it will take O(N * log N) time. And also we are looping the array, which will take O(N) time. Thus overall time complexity will be O(N * log N) + O(N) ~ O(N * log N). Space Complexity O(1). As we are not using any extra space. Key Takeaways We saw how we solved the problem minimize the sum of minimum and second minimum elements from all possible triplets using the greedy method, i.e., by first sorting it and then picking only the required elements from the array for our final answer. Now greedy problems require a lot of practice only after one can truly master them. So what are you waiting for? Move over to our industry-leading practice platform CodeStudio to practice top problems and many more. Till then, Happy Coding!
https://www.codingninjas.com/codestudio/library/minimize-the-sum-of-minimum-and-second-minimum-elements-from-all-possible-triplets-2432
CC-MAIN-2022-27
refinedweb
590
73.37
Amazon is world's largest online retailer and cloud computing services, provider. Read Best interview questions and answers on Amazon. Following are the list of some Amazon's frequently asked questions for candidates who were preparing for amazon job interview. Amazon Interview Questions - 1) Write a program to reverse a string without using Library Function? - 2) Program to find all permutation of a string in C Language? - 3) Program to find Longest substring in C - 4) Explain Priority queues.How do you implement it. - 5) Write a program reverse a singly linked list? - 6) Given an array of unique integers, return a pair of integers that sum up to a target sum. - 7) C program to find all anagrams in a string? - 8) Write breadth-first search in a matrix - 9) Program to implement a Tree Iterate over BST - 10) What is memoization ? Write program to implement memoize. Download Amazon Interview Questions PDF Below are the list of Best Amazon Interview Questions and Answers Different ways to reverse a string Longest substring in C Priority Queues Basic method to find a pair whose sum matches with given sum: C program: #include <iostream> #include <algorithm> // Function to find a pair using Sorting in an array with given sum void findPair(int arr[], int n, int sum){ std::sort(arr, arr + n); // sort the array in ascending order int i = 0; int j = n - 1; while (i < j) { // loop till i is less than j if (arr[i] + arr[j] == sum){ // sum found std::cout << "Pair found"<<”\n”<< arr[i]<<arr[j]; return;} // decrement j if total is more than the sum // increment i if total is less than the sum (arr[i] + arr[j] < sum)? i++: j--;} // No pair exists in an array with the desired sum std::cout << "Pair not found";} // Main function from which find pair function is called int main() { int arr[] = { 8, 7, 2, 5, 3, 1}; int sum = 10; int n = sizeof(arr)/sizeof(arr[0]); findPair(arr, n, sum); return 0;} Anagram strings are those strings which have same letters but in different orders. Method to check: First, sort the strings and then compare the sorted strings. If strings are equal then they are anagram strings otherwise not. Program: #include <stdio.h> #include <string.h> int main () { char str1[] = "listen"; char str2[] = "silent"; char temp; int i, j; int n1 = strlen(str1); int n2 = strlen(str2); //strings are not anagrams if they are of different length if( n1 != n2) { printf("%s and %s are not anagrams! \n", str1, str2); return 0; } for(i=0; i<n1-1; i++) { // first sort both strings for (j = i+1; j < n1; j++) { if (str1[i] > str1[j]) { temp= str1[i]; str1[i] = str1[j]; str1[j] = temp; } if (str2[i] > str2[j]) { temp = str2[i]; str2[i] = str2[j]; str2[j] = temp; } } } for(i = 0; i<n1; i++) { // Compare character by character both strings if(str1[i] != str2[i]) { printf("Strings are not anagrams \n", str1, str2); return 0; }} printf("Strings are anagrams! \n"); return 0;} Related Interview Questions - Aws interview questions - Amazon Interview Questions - Amazon Support Engineer Interview Questions - Amazon Cloud Engineer interview questions - AWS Lambda Interview Questions - Amazon DevOps Engineer Interview Questions - Dynamodb Interview Questions - AWS VPC Interview Questions - AWS S3 interview questions - Amazon Redshift Interview Questions - AWS Ec2 interview questions - AWS ELB
https://www.onlineinterviewquestions.com/amazon-interview-questions/
CC-MAIN-2020-10
refinedweb
557
57.61
Linux Software › Search › description file Tag «description file»: downloads Search results for «description file»:… NDS KFile plugin 0.1 by Thomas Kockerbauer NDS KFile Plugin allows to display meta data of Nintendo DS ROM files in the file tool tips and properties dialogs of the K Desktop Environment. It displays following data: Title Description Maker code Size Game code Description Loader type The package also includes a thumbnail… Riley 0.5 by Reid Fleming Riley is a file integrity checker written in Perl,somewhat similar to Tripwire. Running 'riley -initialize' puts a file called '.riley' in each directory specified in the configuration file. Each '.riley' file contains N one-line descriptions, one description per file. Each description contains… MP3::Splitter 0.03 by Ilya Zakharevich MP3::Splitter is a Perl extension for splitting MP3 files. SYNOPSIS r… a2ping.pl 2.77p by pts a2ping.pl is a small tool written in Perl, used to convert between PS, EPS, and PDF and other page description formats. a2ping is a Unix command line utility that converts many raster image and vector graphics formats to EPS or PDF and other page description formats. Accepted input file forma… Geometry Description Markup Language 2.7.0 by Witold Pokorski and Radovan Chytracek for… MP3::ID3Lib 0.12 by Leon Brocard; JSyntaxColor 1.2.9 by Alexandre Brillant JSyntaxColor is a library for coloring in real time user text input. JSyntaxColor is a shareware, it is free to try for 30 days, else you must register for a low price the full version at : registring you have a royalty free license and you can include JSyntaxColo… Basilisk Live CD 1.40 by Linux4all This is a fedora core 3 based Livecd with KDE 3.3.1, Gnome 2.8, OpenOffice, Fire- and Thunderbird and a lot of other tools. Limitations: It will not work from a scsi - cdrom device. Requirements: minimal - 866 Mhz Intel Pentium,Amd XP or similar X86 PC with at least 128Mb Ram - 36x-5…… y2l 1.1.1.1 by Kris Van Hees sub…… BuildProcess 0.4 by Jean-Baptiste Onofre Build tool… pydelicious 0.3.0 by regenkinder pydelicious library allows you to access the web service of del.icio.us via it's API through python. def getrss(tag = "", popular = 0, url = '', user = ""): get posts from del.icio.us via parsing Rss tag (opt) sort by tag popular (opt) look for the popular stuff user (op… Vatata 1.50 by Vatata Vatata system is an end-to-end and large-scale solution for publishing , delivery and reception of streaming contents. Vatata is an open system completely based on internet. Its grid technology guarantees the low-cost and clear delivery of content to millions of internet users. Users can easily bui… octavia 0.25 by Sreekant Kodela octavia is a compiler for a music description language that compiles to MIDI data. octavia music source files can also use Python code to perform generic programming tasks that a composer might wish to accomplish. What's New in This Release: This release deals correctly with accented notes in
http://nixbit.com/search/description-file/
CC-MAIN-2015-14
refinedweb
515
58.18
Called when the mouse enters the GUIElement or Collider. The corresponding OnMouseOver function is called while the mouse stays over the object and OnMouseExit is called when it moves away. // Change the mesh color in response to mouse actions. using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public Renderer rend; void Start() { rend = GetComponent<Renderer>(); } // The mesh goes red when the mouse is over it... void OnMouseEnter() { rend.material.color = Color.red; } // ...the red fades out to cyan as the mouse is held over... void OnMouseOver() { rend.material.color -= new Color(0.1F, 0, 0) * Time.deltaTime; } // ...and the mesh finally turns white when the mouse moves away..
https://docs.unity3d.com/kr/2017.4/ScriptReference/MonoBehaviour.OnMouseEnter.html
CC-MAIN-2021-25
refinedweb
109
62.34
One of the reasons why I write these articles is to fortify the knowledge of new concept I recently learned, while trying to apply that knowledge to everyday tasks I have to do as a developer. And one of the most common things you do as a developer is fetching some data from an API and present it on a client. And I already wrote about that in the past, with "Fetching data with React hooks and Axios" and just the other day I published "A practical example of Suspense in React 18" on the same topic. But the latter article was using a very manual approach, where you write your wrapper around the fetching library to use the new Suspense component in React 18, but it's not the only way, and there's a new tool in the block that can make that same job way more simple and easy to use: SWR. But what is SWR? In the project own words: The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data. It's not a data fetching library for sure, it does the same job as the wrappers I talked this previous article, and it let you use a simple hook to simplify the fetching process and how to handled it in a react functional component. But on top of that it also cache it, so if you are requesting the same endpoint multiple times, it checks if the internal cache already the data you need (and if it's still valid), improving the overall performances of your application. Let's refactor our code Install the package As usual, first thing to do is to install it, so: npm install swr --save The starting point So previously we had the following components and libraries: - A wrapper for our fetching library that was throwing exception when the fetching promise was not resolved, so it was in a pendingstate, or it was rejected. Example here. - A wrapped fetching logic, where we used axiosto call an API to get our data, and it was wrapped by the function above. Example here - A child component that is calling the function to fetch the data and it renders the code with it. - A parent component that uses Suspense with a fallback component, which it will be shown until the fetching promise is resolved, once that done, the child component will be rendered instead. Example here. What we need to change? So, the wrapper and wrapped function can go, we don't need that anymore. The parent component will be unchanged, as everything will happen in the child component. Our actual job will be to just refactor the child component, and the current code will look like this: import React from 'react'; import fetchData from '../../api/fetchData.js'; const resource = fetchData('/sample.json'); const Names = () => { const namesList = resource.read(); return ( <div> <h2>List of names</h2> <p>This component will use a custom handler for fetching data.</p> <ul> {namesList.map(item => ( <li key={item.id}> {item.name} </li>))} </ul> </div> ); }; export default Names; As we said, we can get rid of the old fetching logic, so this import line can be replaced with swr and axios import: // from this import fetchData from '../../api/fetchData.js'; // to this import useSWR from 'swr'; import axios from 'axios'; Now we still need to use axios to fetch our data, and this will replace our resource object we had before: // from this const resource = fetchData('/sample.json'); // to this const fetcher = url => axios.get(url).then(({data}) => data); Here I'm using axios, but what library to use is up to you, you can use any fetching library you want as long it does return a promise with the data we want to read. So far all of this is happening outside the component code, and while with the old logic we used to call a read() method from our resource object, like this: const Names = () => { const namesList = resource.read(); Now we need to use the useSWR hook instead, but there's a catch: in order to use the suspense component, you need to pass a parameter to tell SWR to support that: const Names = () => { const { data: namesList } = useSWR( '/sample.json', fetcher, { suspense: true} ); Some of you might wonder "Why I can just pass the url directly to the fetcher callback function?". The reason is because SWR will use that key as a cache key, so next time you will call that same endpoint, it will return the cached value. And that's it! The rest of the code will be identical! So the final children component code will look like this: import React from 'react'; import useSWR from 'swr'; import axios from 'axios'; const fetcher = url => axios.get(url).then(({data}) => data); const Names = () => { const { data: namesList } = useSWR('/sample.json', fetcher, { suspense: true}); return ( <div> <h2>List of names with SWR</h2> <p>This component will use the SWR hook for fetching data.</p> <ul> {namesList.map(item => ( <li key={item.id}> {item.name} </li>))} </ul> </div> ); }; export default Names; The parent component will still be unchanged, as everything is happening in the children component, but in case you want to see how everything is wrapped with Suspense, here the code: import React, { Suspense } from 'react'; import Names from './Names'; import Loading from '../Loading'; const Home = () => ( <div> <h1>Best devs:</h1> <Suspense fallback={<Loading />}> <Names /> </Suspense> </div> ); export default Home; I hope this article helped you to understand how to use SWR with the new Suspense component in React 18 ;-) Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/darkmavis1980/using-swr-hook-with-suspense-in-react-18-1clk
CC-MAIN-2022-33
refinedweb
963
65.35
JS Party – Episode #58 Real JavaScript, not too much, stage three and above JavaScript standards, the boundaries of the spec, and ASTs with Jory Burson and Amal Hussein. Standards & Opening the Black Box - TC39 on GitHub - Myles Borins - Daniel Ehrenberg - Maggie Pint - TC39 proposals - The TC39 Process - How to join ECMA - Jory’s talk on Standardizing JavaScript On the distribution of stakeholders On testing the JavaScript spec with JavaScript On the Boundaries of the Spec ASTs - Amal’s talk on ASTs for Refactoring - Esprima - Babel parser - Acorn - Dojo upgrade tool (using ASTs) - Awesome AST Other Transcript Click here to listen along while you enjoy the transcript. 🎧 Alright, Kball here. I’m here at Node+JS Interactive with my buddy Nick Nisi… We are here with Jory Burson, the standards liaison at Bocoup, and Amal Hussein, the open platform– Senior open web engineer. Senior open web engineer, as well as a veteran podcaster herself… Welcome! Hi, thanks for having us. Thank you, hello. We’re excited to talk. We wanted to start a little bit exploring standards, because I think standards in JavaScript is something that used to be a dirty word, and it’s something that we’ve gotten worlds better about over the last 4-5 years. Can you give us the insider’s view on what do standards even look like for us now? Yeah, that’s a great point, and a point I hope to make in my talk tomorrow morning. We’ve kind of used the word web standards a bit as like a dirty word, in a way… There’s a lot of history behind it, it’s not exactly positive; you know, you kind of conjure up some bad vibes… But it’s really changed quite a bit, and I have to give a lot of credit to some folks on TC39 specifically, like Myles Borins, Daniel Ehrenberg, Maggie Pint… Folks who’ve done a lot of outreach and bringing people into the fold, opening up that sort of black box for how decisions get made, how people can participate, that kind of things. I think the tides are turning a little bit, maybe perception is changing - at least we hope, because it’s actually quite a bit of fun, and we’d love to get more people involved… That’s a big theme for the TC39 folks at this conference. Yeah. So do you wanna open that black box a little bit for our listeners? Sure, yeah. So what can I share…? Some things that people might know - we meet about six times a year (TC39 does), but a lot of the work happens in the open on GitHub. You can go to our GitHub pages and track the proposals, track the conversation, see what people – or bring your own proposal to the table, that’s another possibility. All of that is pretty openly documented, and that’s something that we really wanna emphasize. At the meetings themselves a lot of debate happens, a lot of discussion, presentations about different kinds of proposals, and just sort of analyzing where might there be problems, where do implementers think that there are gonna be issues, and then providing the feedback. [04:06] It’s a process that takes a long time, and that’s something that I think can’t be overstated. A lot of folks get these ideas, they get very passionate about it and they wanna see it happen now, but we can’t work at that pace when we’re talking about changing the web. The web is a long-term platform, so we have to think about change management for it in a very thoughtful, pragmatic way. The process does involve a lot of conversation, and getting a lot of people to think about it, debate, provide use cases, write tests… So that we know that the decisions that are being made are the right ones. There’s a proposal process that your listeners might be familiar with, where we have different stages. There are four stages; we start down at the very bottom with “Hey, this is an idea. Wouldn’t it be cool if…?” and it can take a while to go from that stage to the final stage, stage four, which is everybody agrees that it’s the thing to do. We have multiple examples of use cases, we’ve shown that it’s not or maybe it might introduce a regression, there’s tests for it, but once it gets to that stage, it’s going to be in the next edition of the language, which is now produced on a yearly basis. So that can take a long time, and there’s a lot of stuff that happens in-between, but it’s very important. You mentioned the GitHub, tc39/proposals. It’s something that I have bookmarked and look at very regularly. I don’t know the details of how things move, and that’s one thing I was gonna ask… You said that you meet six times a year. Do proposals move between stages only at those times, during those meetings, or…? Yes, absolutely. They do a lot of discussion and work and championing and thinking and that kind of thing on the issues between, but it doesn’t advance until the committee meets in person, looks each other in the eyes and says “Do we all agree that this is ready for the next stage?” That’s really important, and I know that we wanna work in an asynchronous fashion and everything, but sometimes what it takes is everybody getting in the same room and saying “Yes, we’re really on the same page about this.” “Yes, we can.” “Yes, we can.” [laughs] That’s right. Yes. Currently, Ecma International is the standards body that produces the specification, and members of Ecma companies can come and participate in the TCs. I do wanna make a pitch that Ecma membership is actually really affordable, and it’s a pretty easy-peasy process to join… So if participating in standards work in a formal capacity is something that you’re interested in, I’m @jorydotcom on Twitter, let me know; I’d be very happy to help you with your application, or whatever. Easy stuff. And that’s what it takes to be there? Because we were talking about there’s all this in the open, but what Nick is saying - all the decisions are happening in this room with everyone. What does it take to be in the room where it happens? Two things. One is that you join the member organization Ecma, and the other is that you can be an invited expert, and we’re actually really open to that as well. So especially if you’re thinking about joining, let us know, because we would be happy to invite you to come see what it looks like in person. [07:58] I think it’s worth noting that it’s a three-day event; the meeting has grown from maybe ten people – it used to be less than ten people working on the standard, and now I think the last meeting we had like 60 people. We’ve gotta know who’s coming, basically… It could grow to the size of a small conference if we weren’t careful, but we do want to invite folks who are interested in participating to come do that as an invited guest, especially if you’re thinking about joining… Or if there’s an area that you would like to present to the committee about, we’d like to hear from you. Yeah, I’d love to chime in here… The TC39 are kind of put on this pedestal, and to some degree rightfully so, because it’s really hard work, but it’s also really a self-selecting group of people. It’s really tedious work, and the output is lovely. We have wonderful features like async/await that are implemented in all browsers, that work… But it takes a lot to get there, and I think one of the things that really makes the TC’s decisions very cumbersome sometimes is that there’s multiple stakeholders, the first stakeholder (and the most important one) being the users of the web; the users of the web platform are very important, and we cannot break this for them… So backwards compatibility is important, making sure that implementations of new features don’t break the web, any significant portion of it anyway. So that’s one stakeholder. Another stakeholder is developers - people that are writing and using these APIs, these primitives. So does this make sense, is this intuitive, does this fit in with the overall language design? Another very tough stakeholder is implementers. Can V8 implement this in a way that isn’t gonna be a huge performance burden? And what does it mean if all the implementers were on board except for one? So there’s multiple stakeholders that really drive home a really hard bargain, which is why you might see a bunch of things in proposal stages, but the reality is things that actually make it into the spec for real and make it across the finish line - it’s a very small percentage of that… And rightfully so. It’s really important to think about what we put into the platform, because once it’s there, we can’t undo it. A good example of that is even just like symbols that we choose; there’s literally just a limited number of keys on a keyboard, and when we’re looking for new symbols, we have to be really careful about picking that symbol, because once we pick it, it’s gone, it’s forever taken. So there’s a lot of really hard decisions, and it’s really humbling work. Being at Bocoup and being exposed to standards a bit more closely now, as somebody who was kind of just, you know, a standard web developer, and who’s now kind of working on the platform more closely, it’s really humbling and it’s very insightful. Amal makes a great point - sometimes what we have to say no to is more important than what we say yes to… And the nature of it is that we’ll maybe get a dozen or more proposals for something, and maybe just one thing is ultimately what makes it through, because you can’t say yes to everything; that’s tough, and that may be part of where the negative press comes from… But it’s important. TC-thirty-nay… [laughter] Yaaaay! And I’m okay with that personally, because the web is a public utility, it’s something that’s for everyone; it’s how people pay their bills, it’s how people communicate, it’s people’s only communication medium sometimes, if they’re unable to communicate physically otherwise… So we can’t break it, and we have to be careful with it. I’d be interested to hear a little bit – Amal, you mentioned there are these different stakeholders, and there was some recent interesting discussion in the CSS world about the distribution of stakeholders and how it tends to be biased towards implementers… Is the same thing true in TC39? What is the balance of representation across different stakeholders? That’s a great question. The nature of it is we could come up with a dozen different specifications, but none of it matters unless it gets implemented. So the power is really in the hands of the implementers. But we have quite a few folks from companies you would be surprised to hear - Airbnb, PayPal… There are a couple smaller companies like Bocoup, Tilde, for example… So I would say that [unintelligible 00:13:15.06] is another one. If I were to give it a percentage, I might say it’s 50/50. I feel like it’s 50/50. But the latter voices are still the implementers, because ultimately if they don’t put it in, it doesn’t matter… So let’s go back a little bit and talk about the staging of things. I think there was some interesting stuff we were talking about maybe covering, in terms of when do you jump in on something, what do the different stages mean, and what happens if you start using something before it’s fully solidified? …that sort of area. So what are those stages and what do they imply for developers? Yes. I’m a conservative person, I’m fairly risk-averse, so my advice to people is don’t implement it until it’s actually published… But generally, if somebody wants to implement something in stage four, that’s okay, that’s a safe bet. Usually, if it’s stage four, it’s not coming out; it’s going to be adopted in the final draft of the spec. It’s when you start looking at things that are younger than that, less mature ideas, that you get into the super-danger zone… Again, the first stage being “This is an idea. You might want to implement it just as a test case, a proof of concept.” By stage three we expect there to be tests, and some really solid use cases… And stage four - that’s when you’re in the safer zone. What happens is somebody will author a proposal, and they will bring it to the meeting; a champion brings it to the meeting and just presents. There is discussion, and at the end of that discussion the champion might ask “What do you guys think? Do you think it’s time? Can we move it to the next stage?” And the committee will say yes, or “No, we want to see more XYZ…” Then the champion will take that feedback, or they’ll get their green light to move it to the next stage, and then they have more work to do. That all happens on the champion’s timeline, or whoever has authored the proposal; they move at the pace that they can move, that the group of people who feel like this is important can move. So it’s not a timeline-driven sort of thing; it’s about effort. And I guess it’s time-intensive in like how much time does it take to get people to the table, to get the idea seasoned, if you will. And to get that green light, is that a majority vote? Is that a unanimous consensus? What does that look like? We’re consensus-seeking, so a lot of the times the question is “Does anybody oppose moving this to the next stage?” and a lot of times the answer is yes. Yeah. Everybody comes to the table as peers, so anybody could say “I’m not comfortable with that”, and that’s just an opportunity to discuss the issue more acutely. The debate is very valuable, and people saying “Hm…” is not a bad thing. It’s very healthy. You mentioned tests are part of that, and I think Amal you’re a big part of that… Can you describe what that is, what the process is around tests and how that affects a proposal of moving through the standards process? Yeah, sure. TC39 maintains the official conformance suite for testing JavaScript… Which means it’s tests written in JavaScript, that test JavaScript. And I say that because these tests are run in different JavaScript engine runtime contexts, so it tests how V8 for example, or JavaScriptCore, which is the WebKit runtime - how does it implement this feature? So we write tests which basically follow the specification, and we try to break things; they’re tests that have invalid inputs etc. So we test the expected and we test the unexpected. Those tests are then used by implementers. They basically import that project, run it in their own CI process, and it helps implementers when they’re adding features to test their code. So it’s this wonderful validation, and it’s something that really drives interoperability; it’s really important for making sure that JavaScriptCore’s implementation of generators is the same as Chrome’s, and it’s not gonna cause weird bugs, and everybody wins. So it’s to push web interoperability, but it also heavily speeds up the development process for implementers… Because if they have tests and they’re not having to think about it or write their own, it really helps aid the process tremendously. [20:10] I’m really proud to say that my teammates, Rick Waldron… Rick is technically my boss; he’s my boss. My boss, Rick Waldron, my teammate Leo Balter, are maintainers for the project. It’s a small body of maintainers… And I’ve contributed to that project as well. It is not Jest, but it is Jest-like, in the sense that it’s a light, very thin test harness that’s used for the development purposes, but every implementation has their own runner and harness and all of that. And for us it’s very minimal and it’s very unlike writing tests for like a web application, where you’re trying to be dry, and reuse things, and you have a set of helpers… You’re writing tests for the spec, which means that you don’t have to ever really edit this test again. And every test has to be atomic, so literally one specification will introduce hundreds and hundreds and hundreds of tests, because every test file tests one line in the spec, and there might be multiple test files for one line even… So it’s very atomic, very different. There’s no concept of adding spy’s or mocks… It’s as minimal as possible. And even when you’re testing features in ES6, let’s say we’re writing a test for async/await - we’re not really gonna be using arrow functions or whatever… We’re not gonna be using other ES6 features; we have to minimalize the usage of JavaScript features in the specification year that we’re testing for. It’s a very different type of project, and I think we’re gonna be writing a bit more about that on Bocoup’s blog, what it’s like to contribute to this. I think contributing is a great way to get familiar with the spec. If you really love tests – Amal loves tests, I love tests… If you really love tests, it’s a great way to learn the specification as well. That’s really cool. I honestly did not know that there is something out there that I can contribute to. You can contribute, and you’ll learn a lot for it… And it’s a really wonderful gift that will outlive you and all of us, because the web is here to stay, hopefully… It also sounds like it’s a pretty low barrier way to get involved, because these things are so tiny and atomic that if you only have a little bit of time and you wanna learn about a little bit of the spec, you go, you write 3-4 tests, and you’re in the door. You’ve started onboarding and you’ve started contributing back to not just open source, but to the entire platform of the web. Yeah. I actually wanna make a comment about other ways to get involved, beyond joining and going to these meetings, which are laborious… The test are a great way; contributing use cases, trying out some of the implementations in your own projects and providing feedback on that are all really effective data points. There’s a couple of different efforts to improve documentation, and to get more feedback from different groups like educators, for example, like “What can we be doing to make the language more accessible to newcomers?” Those are all really important things to be talking about, beyond “What new crap can we put in this thing next year?” [laughs] Which is fine, but also we have a lot of crap, so… [laughs] That’s really good. I didn’t consider getting those perspectives. That’s a really good thing, to hear that that’s happening… More than just getting features and syntactic sugar, and making my life easier, but actually “Does it actually provide benefit beyond that?” Yeah. [24:02] I’d be curious to hear a little bit about what are the boundaries of what is and is not specified? One thing that came up in a recent JS Party that we were talking about was error messages, and the fact that the same error can have different error messages across every different browser. Where are the lines that are left up to the discretion of the implementer? That is a great question. Yeah, I have so many thoughts on this… Okay, go for it. So I wrote a bunch of tests for Atomics, which is this awesome new feature, it’s a new built-in that’s coming into the language, that basically brings threading to JavaScript. It’s sick, it’s so amazing. Anyway, this was my first big stab at contributing tests [unintelligible 00:24:46.03] and one of my annoyances were like “Why are the messages not standardized?” and I kept harping on this; like, “This doesn’t make any sense at all.” My web developer brain – I’m thinking adding logging, and messaging, it’s all about having your namespaces, and making sure that you can trace things down to where they came from, and “How are you supposed to know the difference between the same error that’s happening in Safari versus Edge?” Apparently, it’s really difficult to standardize that… So reading through the specification you’ll see that there’s a bunch of things that have double square bracket, and those are kind of like internal implementation details. How they’re implemented isn’t specified, but how they behave is. So it’s like behavior versus implementation. There’s some things that are left up to the implementers because they’re writing the code, and that part is unreachable by JavaScript. So the parts that we can observe are the parts that we test, which is that an error is being thrown; but the contents of that error are not really – it’s not really where the value is. It’s just that when this thing happens, an error should be thrown; when this thing happens, we can assume XYZ conditions… So there’s assumptions, and then there’s like internal implementations, and then there’s what’s actually observable. It’s multi-layered… It deserves its own discussion, and I think with implementers, because I think it’s a fascinating topic. If you’re listening to this and you’re an implementer, we wanna talk to you. [laughter] Yeah… I don’t know, Jory - is there anything else that you wanted to add to that? No. I mean, I think you nailed it. It’s one of those things where for a lot of people on the committee there’s a desire to specify further, and then there’s a lot of pushback the other way, and in the standards process itself it’s all about that push-pull between like “Web developers want X, and implementers need to focus on Y, so what’s the harmonious balance we can reach in between?” That’s why it takes so long sometimes. Yeah, it can take multiple committee meetings for one little thing to advance just partially, let alone – because everybody comes back with… You know, lots of really smart people breaking down a problem and finding the holes. Yes. The most glorious bikeshed you’ve ever witnessed. [laughter] I wanna make a community service announcement, actually, since we’re talking about standards… This is something that I know Jory is extremely passionate about as well, but please, please, please stop using proposals in production… Yes… [laughs] And it’s a good segue into my – You know, proposals are proposals, and they will change; they’re almost guaranteed to change. Decorators is a prime example of that. Babel makes it really easy for us to use these stage zero, stage one presets, but now since they’ve added messages and warnings saying “FYI, this is going to change. This is not real JavaScript yet.” [28:13] So just understand that it’s a major maintenance burden for you and your teams moving forward. Like, yeah, somebody might write some automated way to refactor it, but it’s still something that you have to do, and it’s still decisions that need to be made by product teams and QA teams, and… You know, it’s just not worth it. Be responsible and only use real JavaScript. [laughter] We should make like a “Real JavaScript” sticker. “Keep calm and use real JavaScript.” “Real JavaScript. REAL JavaScript.” What if you can make Michael Pollan reference, where you do the three things, like “Use JavaScript, not too much, mostly real. Proposal stage three or above.” Yes! Only shop at whole foods JavaScript. [laughter] Use real JavaScript, not too much… I primarily write TypeScript, so I kind of go by that as the – the new features, when they get added to that language, then I can start using them. Segueing into your talk a little bit - tell us a little bit about what you’re gonna be talking about at the conference. Yeah, sure. My talk is on machine-powered refactoring, so leveraging ASTs (Abstract Syntax Trees) to basically push your legacy code and the web forward… Your legacy code, and consequently the web forward. The idea is that the web is an evolving, moving target, and we have - as Jory so eloquently pointed out - new specifications that are being added to the language… So the language itself is shifting, the web APIs are shifting, and new things are getting added; dependencies are getting changed, versions are deprecated, and you have code that you also want to deprecate. So we have all these changes that we need to make, and we need to really get comfortable with automating that process, and doing it in a safe way, and using tools that are better than RegEx, or simple Find and Replace. Yeah, RegEx… If you say it three times, my brain will explode, so please, careful on the number of… RegEx, RegEx, RegEx…! Halloween! Maybe a Beetlejuice will show up. [laughter] Well, isn’t there a statement about that…? Like, any problem, you’re gonna eventually reduce it to doing RegEx? Anything dealing with text… Yeah, yeah. I mean, they’re so powerful up to a point, and then you can get yourself in so much worlds of pain… Basically, ASTs are this powerful thing that helps – so when your code is basically processed by a language parser, it first gets broken down into a tree, and that tree is this predictable data structure, that then you can use to safely make changes to your code, and do an in-place regeneration… So those are the things that I’ll be exploring tomorrow. There’s a lot of tools around that, and there’s even lots of ASTs… Do they all have similar data structures that they eventually get converted into, or do they all have their own subtle intricacies between them? That’s a great question. There is an effort to standardize ASTs and tokens in general, but currently there’s a few different competing versions. Depending on what parser you’re using - Esprima, Babel, Acorn etc. - they’re all a little different, but as long as you’re using the same one to make your changes continuously throughout your process, you shouldn’t have any issues. It’s when you’re mixing things that you kind of get into trouble. But that’s a great question. What are the problem domains in which someone should look at doing that, and where does the line come where you say “Okay, this is not actually easy to do from a machine. We need to get a person involved”? Yeah, that’s a great question. If you have a change that is (I would say) queriable, and that’s a finite and scoped problem… For example, we change the API of this class, which is now used all over our codebase, to take an extra parameter; so now I wanna refactor across the codebase safely - how would I do that? That’s a good use case for an AST. You can also leverage - in AST-based transformation - error handling, or adding in a code snippet or something like a marker for something that you wanna maybe do manually. If it’s a 90% match for your use case, but you’re like “Oh, I found something that’s funny”, that’s something that you can also do. It’s a little trick, but you can do that. Yeah. I have a little bit of experience with this; I work on the Dojo project, and we have a CLI tool and a bunch of plugins for that… And of them is an upgrade tool. We’ve been making some drastic changes as we go, and we consolidated eight packages into one package, between versions. So one really easy transform was “Go look at all the imports, and if they match where this import was, change it to this.” That’s a really easy, finite one. As we get more and more complex, another example is something where we have a component that still exists, but instead of it being a higher-order function that you would call, that returns a component, you just use it as a component. So I can go through and query the data AST, find out if it’s being imported, what its name is, find that token in there and then see if it’s actually being called or if it’s just being passed as an argument. From there, I can’t really refactor that, but I can output logging and say “Hey, you’re using this here. It’s changed. You should go in and fix that.” Yeah, and that’s something that I get into, too. It’s an ability for you to query your codebase, and understand “Where does the complexity lie? Where do I have seven function calls that are being made from one function? Where do I have 17 variables being defined?” It’s a way for you to understand what are the patterns of your codebase, and then also take the opportunity to improve your custom linting rules as well. [36:06] If you make a transform, or if you’ve deprecated some API or whatever, you can also use ASTs to extend out your linter to be a bit more custom to your team’s conventions. Or you can use it to reinforce this bug from never happening. So if you ever fix a bug, you should ask yourself, “Hey, is there a linting rule, or is there something that I can do to automate this, so that nobody else has to ever fix this bug again? If the answer is yes, then go do that.” Then the next question should be “If the answer is no, then can I write a unit test, so that our build will–” and then if the answer is “No, I can’t write a unit test”, “Okay, then can I write an integration test?” and the answer will definitely be yes. So there’s multiple layers for stopping regressions from happening, and I’m trying to automate that and make that as binary as possible. It just takes the human emotion and human time out of it, which is really valuable. Does that make sense to you all? Yeah, definitely. That’s not something that I had really considered. Either I haven’t written custom linting rules, but… Super-easy, come to my talk tomorrow. You’ll learn how. [laughs] Absolutely. I imagine these talks are gonna be published online at some point… I was just wondering that myself, and I feel like I should know that, but I don’t know that. There are cameras in the back of the room, so… Yeah, I think they’re all getting recorded… So if you’re listening to this, check and see if Amal’s talk is up yet. Yeah, hopefully… And they usually get them up really quick after the event. Oh, that’s nice. Are there any tools or references or places to start for someone who is interesting in learning more about ASTs, that you’d recommend? My talk on YouTube… [laughter] And my link to my slides, which maybe we can include in the show notes, or something… For sure, yeah. Send them over. But there’s also an awesome AST, which is kind of sparse, but I have a bunch of resources that I’ve put together when I was researching my talk, so I hope to add to that list. If you all have time, I’d love to poke at one other subject… Bocoup is an open source consultancy, which is a model that certainly fascinates me, but I think it’s probably something a lot of our audience may be interested in as well… Can you describe what does that even mean? Open source consultancy, as compared to just an agency, or something else… That’s a great question. Yes, we’re a professional services firm, so there’s a lot of different types of these kinds of companies, and different industries, and we serve the open source/open web tech industry. What that meant in 2009 when the company was first formed and what it means now is different, because everything changes, and you kind of have to stay with the changes. In 2009 it meant convincing people that JavaScript was a language worth learning and using in enterprise; it meant teaching people a lot about new tools, like jQuery, that they could use to better work with the DOM, and that kind of thing… And it’s evolved over time to include a lot of work on tools, and things that make life better for developers. Whatever happens with technology in the future, I think what Bocoup will be doing is whatever needs to be done in order to help advocate and improve the lives of developers - and users that they support, right? Because that’s the other constituency that we care a lot about. In practice today that means we’re working a lot on infrastructure tools, and primarily the test suites, but also Amal’s team… If you wanna plug Gaia really quick… [40:13] Oh, yeah. At Bocoup, our model is we have engineers that work on our reliability standards and testing projects with our browser vendors. Then some of us also still kind of do what Bocoup was really famous for, which is we make amazing web apps; but we’ve really evolved from making amazing web apps, which we feel like the community is really there, but we’re pushing the boundaries now with computer vision and augmented reality, games interactive media… So web applications that have all of those components, that are a little bit more niche. We’re not really working on standard React Redux apps, we’re working on really complex things that really leverage the web platform APIs heavily. Our expertise on these APIs really helps us help our customers, push the boundaries forward with what they can do with their web applications. To your point about what’s really the difference between that kind of service versus an agency, where we try and serve is in that sort of longer-term relationship and commitment, not just to the product, but also to the technology, and helping companies understand what the lifecycle of that technology is, how to work with it in a healthy, sustainable, maintainable kind of way, versus “We need an application for our car rental company”, which has more of like a marketing and advertisement focus to it. We’re really there for the tools and the teams behind the tools. Yeah, exactly. “Here’s how to think about where your company is, and its transition to maybe becoming more of a tech company.” That’s the thing that’s of concern right now for a lot of companies - “How do we go about our digital transformation (that buzzword), and how do we do it in a responsible way? Because we can’t just go chasing the next best framework, or whatever… That’s not really gonna get it done. How do we need to organize, how do we need to think? What are some of the things we need to learn, some of the things we need to let go of?” That kind of thing. Last point on this, engineers at Bocoup are very unique, in that we have a strong web developer background, but we’re also really involved with the web platform… And those two worlds - it’s funny, they’re operating on the same thing; web developers make things for the web, platform engineers make the web… Right? [laughs] But they’re two different worlds, and the Venn diagram between those two is small, and Bocoup kind of interestingly fits in both of those worlds. Yeah, we definitely have tried to do that. Neat. Anything else you all wanna talk about? Just how much fun I had getting to meet you two, and… Yeah, this has been great, and I feel like I’ve learned a lot about standards, and a little bit about ASTs, and now I’m really excited; I hope I can make your talk tomorrow… Hopefully. If not, I’m gonna watch that recording. Yeah, on YouTube. Hopefully we can include it in the show notes. And thank you very much for inviting us. It’s been an absolute pleasure. Yeah, definitely. Awesome. Thank you. Our transcripts are open source on GitHub. Improvements are welcome. 💚
https://changelog.com/jsparty/58
CC-MAIN-2022-40
refinedweb
6,391
64.44
/*- * [] = "@(#)fwrite.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/stdio/fwrite.c,v 1.11 2002/10/12 16:13:41 mike Exp $"); #include "namespace.h" #include <stdio.h> #include "un-namespace.h" #include "local.h" #include "fvwrite.h" #include "libc_private.h" /* * Write `count' objects (each size `size') from memory to the given file. * Return the number of whole objects written. */ size_t fwrite(buf, size, count, fp) const void * __restrict buf; size_t size, count; FILE * __restrict fp; { size_t n; struct __suio uio; struct __siov iov; iov.iov_base = (void *)buf; uio.uio_resid = iov.iov_len = n = count * size; #if __DARWIN_UNIX03 if (n == 0) /* POSIX */ return 0; #endif /* __DARWIN_UNIX03 */ uio.uio_iov = &iov; uio.uio_iovcnt = 1; FLOCKFILE(fp); ORIENT(fp, -1); /* * The usual case is success (__sfvwrite returns 0); * skip the divide if this happens, since divides are * generally slow and since this occurs whenever size==0. */ if (__sfvwrite(fp, &uio) != 0) count = (n - uio.uio_resid) / size; FUNLOCKFILE(fp); return (count); }
http://opensource.apple.com//source/Libc/Libc-594.9.1/stdio/fwrite-fbsd.c
CC-MAIN-2016-40
refinedweb
170
72.42
At 22:54 +0800 on 30 Jun (1341096874), Zhou Jacky wrote: > I re-post this from Xen-User maillist. > > I found that xen PV linux performance is very poor comparing with native > linux or HVMPV linux in some case such as system call (which will cause > context switch). > Here is a very simple sample: > > double geTime() { > struct timeval t; > gettimeofday(&t, 0); > return (double) t.tv_sec + (double) t.tv_usec / 1000000.0; > } > > int geInc(int sum) { > return sum+1; > } > > int main() { > for (i=0; i<; i++) { > geTime(); > } > > In PV linux guest, It will be 10 times slower than PVHVM linux guest. > While call getInc() 10000000 times, PV guest is a little faster then > HVMPV. gettimeofday() is often a vsyscall on native/HVM linux (i.e. it doesn't actually make a system call), and I'm not sure that's the case on PV. You could try coding up an actual system call (in assembly), or using a libc wrapper that always makes a system call (I think getppid() is a good choice but you should use strace to confirm it's making system calls). > So it seems that PV linux guest has poor performance in context switch case. By context switch people usually mean changing from one process to another, which is not what's happening here. > How can I tune this or if there's any plan fixing this issue? That depends -- what's your actual goal? Do you actually care about gettimeofday() performance or is there some other workload that's running slowly for.
https://old-list-archives.xen.org/archives/html/xen-devel/2012-07/msg00005.html
CC-MAIN-2021-49
refinedweb
256
71.24
Opened 9 years ago Closed 9 years ago #7229 closed (duplicate) newforms-admin does not display validation errors that aren't associated with a particular field Description If you attempt to add custom validation to a newforms-admin model adding/editing page that runs against more than one field (and hence should be in the form's "clean" method, rather than a clean method associated with a particular field) you run in to problems. Here's the example code: def custom_clean(self): image_url = self.cleaned_data.get('image_url', None) image = self.cleaned_data.get('image', None) if not image and not image_url: raise forms.ValidationError("You must upload OR enter an image") return self.cleaned_data class EntryOptions(admin.ModelAdmin): def get_form(self, request, obj=None): form = super(EntryOptions, self).get_form(request, obj) form.clean = custom_clean return form This works in as much as you get a message about there being errors on the page, but the actual errors are not displayed anywhere. They should be displayed in a list at the top of the page. Forms have a non_field_errors() method that can be used for this purpose. Looks like #6809 reports the same problem.
https://code.djangoproject.com/ticket/7229
CC-MAIN-2017-43
refinedweb
192
57.27
Difference between revisions of "Modeling PMC Meeting, 2006-06-20" Latest revision as of 14:51, 21 April 2007 Agenda If you've got any specific items to add to the list of topics for tomorrow, please reply. I have (again) tried coming up with a structure for the Modeling project, and propose this be our primary topic for tomorrow. We'll need to resolve this soon in order to move forward with provisioning, etc. I've attached a slide (with notes) that Ed and I feel is a good starting point for the discussion, so please review at your convenience. Notes Attendees: - Richard Gronback - Ed Merks - Kenn Hussey - Fred Plante - Sebastien Demathieu Absent: - Jean Bezivin The primary discussion point of the call was regarding project structure within Modeling. A number of suggestions were made in reference to the initial proposal, sent earlier (see below). An updated slide with the changes discussed on today's call is attached. It is planned to have this issue resolved no later than our next PMC call (July 18th) so that provisioning can commence ASAP. - Net4j/Teneo components for EMF are to remain within EMF, although not indicated in slide (fixed). - The Eclipse Modeling Tools (EMT) project proposed to house modeling tools was generally accepted, while Kenn thought Model[ing?] Development Tools (MDT) was a more appropriate name (most agree, it seems as it fits nicely with JDT/CDT). Fred expressed some concern with including 'Tools' in the name. It was suggested that Kenn would take leadership of such a project, as it would initially contain UML2 and related tooling. The inclusion of "industry standard" in the name was proposed, and seems fine except for the case in the where a modeling 'tool' in the future might be added but not follow an industry standard. - Kenn also pointed out that MDT (or whatever) should be the home for the OCL project, as it is a spec found within UML2 according to the OMG's organization. A discussion of the project's namespace followed, as it's currently org.eclipse.emf.ocl, while it would be more appropriately found in org.eclipse.ocl (according to convention). Unfortunately, we've just agreed in the Release Review that OCL was to exit incubation in its current state, which leaves the next major release version as the time to make such a refactoring. - The MXF (Model Transformation Frameworks) project was thought better split in two by Fred. This was generally accepted and the project names are proposed to be M2M (Model to Model) and M2T (Model to Text). (I guess MXM and MXT could be alternatives that save the 'X' ;-) - Fred proposed, as was suggested in the slide, that the GMF and TMF projects be combined into one (MXF represents an analogous combination) with "notation" in the name. It was agreed to keep them separate, which is in keeping with the proposed separation of MXF into M2M and M2T. - As JET seems to have the most progress toward the formation of a standalone project for M2T, it is believed it would form the initial M2T component, perhaps with Paul Elder as lead. There is also the proposed MOF2Text project (still not public) and the xPand component within GMT to consider. - We need to get feedback from Jean regarding potential rename of GMT to indicate it's nature as both technology incubator and research project. Currently, it's Generative Modeling Tools and one suggestion is Generative Modeling Technologies. This seems to imply it is only for "generative" tooling, however. It will be left to Jean to discuss impact of this or alternative namings, as well as feedback regarding the whole nature of this change (additive) as he is the project lead. - A final note is in reference to switching to Subversion as the repository provider for Modeling. It was agreed that it is best to wait for resolution on a proposed new build facility for Eclipse, as there will be a necessary integration required. Also, the existing scripting used and hopefully to be leveraged throughout Modeling works with the existing infrastructure.
http://wiki.eclipse.org/index.php?title=Modeling_PMC_Meeting%2C_2006-06-20&diff=34404&oldid=18046
CC-MAIN-2014-42
refinedweb
682
58.92
Adding Validation Note, a page-based programming model that makes building web UI easier and more productive. We recommend you try the Razor Pages tutorial before the MVC version. The Razor Pages tutorial: - Is easier to follow. - Covers more features. - Is the preferred approach for new app development.. Notice the System.ComponentModel.DataAnnotations namespace does not contain System.Web. DataAnnotations provides a built-in set of validation attributes that you can apply declaratively to any class or property. (It also contains formatting attributes like DataType that help with formatting and don't provide any validation.) Now update the Movie class to take advantage of the built-in Required, StringLength, RegularExpression, and Range validation attributes. Replace the Movie class with the following:; } } The StringLength attribute sets the maximum length of the string, and it sets this limitation on the database, therefore the database schema will change. Right click on the Movies table in Server explorer and click Open Table Definition: In the image above, you can see all the string fields are set to NVARCHAR (MAX). We will use migrations to update the schema. Build the solution, and then open the Package Manager Console window and enter the following commands: add-migration DataAnnotations update-database When this command finishes, Visual Studio opens the class file that defines the new DbMigration derived class with the name specified ( DataAnnotations), and in the Up method you can see the code that updates the schema constraints: public override void Up() { AlterColumn("dbo.Movies", "Title", c => c.String(maxLength: 60)); AlterColumn("dbo.Movies", "Genre", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.Movies", "Rating", c => c.String(maxLength: 5)); } The Genre field is no longer nullable (that is, you must enter a value). The Rating field has a maximum length of 5 and Title has a maximum length of 60. The minimum length of 3 on Title and the range on Price did not create schema changes. Examine the Movie schema: The string fields show the new length limits and Genre is no longer checked as nullable.. In the code above, Genre and Rating must use only letters (white space, numbers and special characters are not allowed). The Range attribute constrains a value to within a specified range. The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length. Value types (such as decimal, int, float, DateTime) are inherently required and don't need the Required attribute. Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database. For example, the code below will throw a DbEntityValidationException exception when the SaveChanges method is called, because several required Movie property values are missing: MovieDBContext db = new MovieDBContext(); Movie movie = new Movie(); movie.Title = "Gone with the Wind"; db.Movies.Add(movie); db.SaveChanges(); // <= Will throw server side validation exception The code above throws the following exception: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. Having validation rules automatically enforced by the .NET Framework helps make your application more robust. It also ensures that you can't forget to validate something and inadvertently let bad data into the database. Validation Error UI in ASP.NET MVC Run the application and navigate to the /Movies URL. Click the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client side validation detects the error, it displays an error message. Note to support jQuery validation for non-English locales that use a comma (",") for a decimal point, you must include the NuGet globalize as described previously in this tutorial.. Test validation using the Edit action method, and the same validation is applied. The form data is not sent to the server until there are no client side validation errors. You can verify this by putting a break point in the HTTP Post method, by using the fiddler tool, or the IE F12 developer tools.. public ActionResult Create() { return View(); } // POST: /Movies/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")]) checks ModelState.IsValid to see whether the movie has any validation errors. Getting this property evaluates any validation attributes that have been applied to the object. If the object has validation errors, the Create method redisplays the form. If there are no errors, the method saves the new movie in the database. In our movie example, the form isn't posted to the server when there are validation errors detected on the client side; the second Create method is never called. If you disable JavaScript in your browser, client validation is disabled, and the HTTP POST Create method gets_3<< The following image shows how to disable JavaScript in the FireFox browser. The following image shows how to disable JavaScript in the Chrome browser. >>IMAGE> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Movie</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.Title, new { @ @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> </div> @*Fields removed for brevity.*@ <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }. Using DataType Attributes DataType attribute. [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } [DataType(DataType.Currency)] public decimal Price { get; set; } The DataType attributes only provide hints for the view engine to format the data (and supply attributes such as <a> for URL's and <a href="mailto:EmailAddress.com"> for email. You can use the RegularExpression attribute to validate the format of the data. The DataType attribute is used to specify a data type that is more specific than the database intrinsic type, they are not validation attributes. In this case we only want to keep track of the date, not the date emits HTML 5 data- (pronounced data dash) attributes that HTML 5 browsers can understand. The DataType attributes do not provide any validation. DataType.Date does not specify the format of the date that EnrollmentDate { get; set; } The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.) You can use the DisplayFormat attribute by itself, but it's generally a good idea to use the DataType attribute also. attribute can enable MVC to choose the right field template to render the data (the DisplayFormat if used by itself uses the string template). For more information, see Brad Wilson's ASP.NET MVC 2 Templates. (Though written for MVC 2, this article still applies to the current version of ASP.NET MVC.) If you use the DataType attribute with a date field, you have to specify the DisplayFormat attribute also in order to ensure that the field renders correctly in Chrome browsers. For more information, see this StackOverflow thread. Note jQuery validation does; } [Required,StringLength(60, MinimumLength = 3)] public string Title { get; set; } [Display(Name = "Release Date"),DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } [Required] public string Genre { get; set; } [Range(1, 100),DataType(DataType.Currency)] public decimal Price { get; set; } [Required,StringLength(5)] public string Rating { get; set; } } In the next part of the series, we'll review the application and make some improvements to the automatically generated Details and Delete methods.
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/adding-validation
CC-MAIN-2022-40
refinedweb
1,289
56.45
React global state by Context API I had been trying to find a way to use React without using class. Redux is one solution to achieve this. Although I love the idea of writing everthing in pure functions, Redux is sometimes not suitable for small apps. React v16.3 introduced new Context API officially. Since then, several ideas were proposed to use it for managing global state. So far, I wasn’t able to find something I really liked, hence I made a new one. The following code is a working example. Hope it shows the idea well. import React from 'react'; import ReactDOM from 'react-dom'; import { createGlobalState } from 'react-context-global-state'; const initialState = { counter1: 0, }; const { StateProvider, StateConsumer } = createGlobalState(initialState); const Counter = () => ( <StateConsumer name="counter1"> {(value, update) => ( <div> <span>Count: {value}</span> <button onClick={() => update(v => v + 1)}>+1</button> </div> )} </StateConsumer> ); const App = () => ( <StateProvider> <h1>Counter</h1> <Counter /> <Counter /> </StateProvider> ); ReactDOM.render(<App />, document.getElementById('app')); The initialState is an object. For each properties of the object, a context is created. StateProvider wraps all the context providers and StateConsumer requires a name prop to specify which context consumer to use. There is a package to support the above example. You can install it: npm install react-context-global-state You can also check out the source code: In this short post, I introduced a way to use global state with React Context API. A library package is developed and example code works with it. Hope anyone interested would try it out, and drop me a note. Thanks.
http://brianyang.com/react-global-state-by-context-api/
CC-MAIN-2019-04
refinedweb
261
56.35
Read Image¶ Reads image into numpy ndarray and splits the path and image filename. This is a wrapper for the OpenCV function imread. plantcv.readimage(filename, mode = "native") returns img, path, image filename Parameters: - filename - image file to be read (possibly including a path) - mode - return mode of image ("native," "rgb,", "rgba", or "gray"), defaults to "native" Context: - Reads in file to be processed - Note: - In most cases, the alpha channel in RGBA image data is unused (and causes issue when used as RGB image data), so unless specificed as mode='rgba'the pcv.readimage()function will read RGBA data in as an RGB image under default settings ( mode='native'). However, if the alpha channel is needed users can specify mode='rgba'. - Example use: from plantcv import plantcv as pcv # Set global debug behavior to None (default), "print" (to file), or "plot" (Jupyter Notebooks or X11) pcv.params.debug = "print" #read in image img, path, img_filename = pcv.readimage("home/user/images/test-image.png", "native")
https://plantcv.readthedocs.io/en/latest/read_image/
CC-MAIN-2019-18
refinedweb
165
50.06
cabs, cabsf, cabsl − absolute value of a complex number #include <complex.h> double cabs(double complex z); float cabsf(float complex z); long double cabsl(long double complex z); Link with −lm. The cabs() function returns the absolute value of the complex number z. The result is a real number. These functions first appeared in glibc in version 2.1. For an explanation of the terms used in this section, see attributes(7). C99. The function is actually an alias for hypot(a, b) (or, equivalently, sqrt(a*a + b*b)). abs(3), cimag(3), hypot(3), complex(7) This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at−pages/.
http://man.linuxtool.net/centos7/u3/man/3_cabsl.html
CC-MAIN-2019-35
refinedweb
128
60.21
I have a project with contracts (project A) that generates a library and another one (project B) that implements an interface from that library. I've tried copying the contract files from project A to project B and the contracts fire at runtime without problems. But when I'm trying to reference project A from project B. The static analyzer is still working, but the runtime checks no longer work. Am I doing something wrong? Is there something I do not understand about how code contracts work? Important: this was discussed here - CodeContracts issue Replicated a similar project structure in a new solution. Everything worked without any problems. I still could not find what is the matter with the production solution. Out of despair I created a new CompanyName.ContractsDebug library. Some test contract implementations fired the runtime checks when using that library. Then I tried going for the stupid fix, I refactored the namespace of the old contracts project ( CompanyName.Contracts) to a new name ( CompanyName.Shared.Contracts). And that somehow fixed everything. Very weird bug. Update I was hasty to say that moving it to Shared.Contracts worked. Moving it to Shared.IContracts did. I don't know what is the deal with the Contracts keyword.
https://codedump.io/share/kRd9CP1d3QDe/1/code-contracts-on-different-projects
CC-MAIN-2017-09
refinedweb
208
68.67
This alternative migration steps provides a means of migrating an old ITM version to a new version. At the same time gives an opportunity to review and correct errors in the following. Situations definition and property Navigators and views Workspaces Policies Users access and group. Background: A customer who is running ITM 6.2.3 decided he want to upgrade to ITM 6.3.0 FP2 but do not want to do a straight upgrade as he dose not want any interruption to his existing environment and also correct any errors and update situations What the wanted is to be able to migrate the following into the new system in stages. After spending some time with the customer thinking of how to do this migration I came up with the following procedures to get this work done. Process and Step: Here are the options that you have 1. What you can do is not to use the Bulk export or import of those situation but use the Viewsit to export and Createsit to import those situations with long name. 2. The other error suggest that the list did not contained the situation that you are trying to export or import. 3. The only other alternative is to do an upgrade from your current version of ITM to ITM 6.3.0 FP2. There is a BASE ITM 6.3.0 FP2 that you can upgrade to. Here are what you do need to do before you start. a) Run the following tacmd command to list all the components that you need to migrate. You will need to get the output of each of these command so that you know the extent of what you need to import into the new installation. Unfortunately, where you have a big installation you will need to use the bulk export and bulk import but there are few bulk export and import that you can do. Here is the list. Also you will need these other commands Then use the equivalent imports to import the results from the above to you new system. It is a good idea to have the managed systems list in place before you start importing the situations, Navigators etc. What you can do is use the output of the listSystems command and the editsystemlist to add the managed systems. Please be aware of the syntax for the managed system as the name should not be longer than 32 characters and no underscore. Now regarding the exporting and importing of users and user groups, you will need to backup the TEPS database from the old system first. Then you will have to import the TEPS database backup from the old system onto the new system. Once this is finished with no error then you run the Presentation.bat to finalize the process. Launch the demo
https://www.ibm.com/developerworks/community/blogs/0587adbc-8477-431f-8c68-9226adea11ed/entry/alternate_migration_of_itm_from_an_old_version_of_itm_to_a_new_version?lang=en
CC-MAIN-2019-43
refinedweb
474
70.94
So far, we have been running scripts in an IIFE, which works fine for those that need to run every time we invoke it. But for the last part, we need a route to which a webhook can post data. We need these webhooks to support the Sendy callback on subscribe and unsubscribe. We will create a route for those callbacks that will do the same action for the user on Revue. If you want to follow along with the project, start from this GitHub branch. Adding routes to our project To make things easier for myself, I will use Fastify to handle my routes. Fastify is a great project which doesn't take a lot of configuration, so we can focus on writing the actual content of the routes. First, let's install the dependency. npm install fastify Once installed, open up the index file and import the module. import Fastify from 'fastify'; const fastify = Fastify({ logger: true, }); The next step is to add our first route. Let's already call it subscribe. fastify.get('/subscribe', function (request, reply) { reply.send({ hello: 'world' }); }); Then we need to spool up the Fastify server. fastify.listen({ port: 3000 }, function (err, address) { if (err) { fastify.log.error(err); process.exit(1); } }); When you now run your server ( node index.js), we should be able to visit. However, this now supports GET requests only, and our webhook performs a POST request. These are easy changes as we can change the method on the Fastify route. In the previous tests with the web hook request bin, we also learned the webhook returns which action is triggered, so we can rename our route to be one uniform route. fastify.post('/sendy-webhook', function (request, reply) { reply.send({ hello: 'world' }); }); Now we should be able to post to this webhook route. Since we used our request bin in our initial testing, we know what the data object looks like. { "trigger": "unsubscribe", "name": "", "email": "info@daily-dev-tips.com", "list_id": "xxx", "list_name": "DDT Subscribers", "list_url": "xxx", "gravatar": "xxx" } Handling the webhook data Let's modify our route to handle valid triggers. fastify.post('/sendy-webhook', function (request, reply) { const data = request.body; if (!data.trigger) { throw new Error('Invalid data'); } const { trigger, email } = data; if (['subscribe', 'unsubscribe'].includes(trigger)) { reply.send({ [trigger]: data.email }); } throw new Error('Trigger not found'); }); Let's restart our server and try the endpoint in our API platform. That seems to work perfectly. When we created our Revue routes, we only supported the GET routes, but we need to post data for this one. Let's modify our callRevueAPI to handle this. const callRevueAPI = async (endpoint, method = 'GET', body) => { const response = await fetch(`{endpoint}`, { headers: { Authorization: `Token ${process.env.REVUE_API_TOKEN}`, 'Content-Type': body ? 'application/x-www-form-urlencoded' : 'application/json', }, method, body, }).then((res) => res.json()); return response; }; This call defines which content type to set and passes the optional body. Now we can modify our webhook to call this function like this. if (['subscribe', 'unsubscribe'].includes(trigger)) { const url = `subscribers${trigger === 'unsubscribe' && '/unsubscribe'}`; const status = await callRevueAPI(url, 'POST', convertToFormData({ email })); return reply.send(status); } We can use the same convertToFormData function we created before and simply post to the correct URL. On execution, we return whatever Revue API returns to us. I get the following response when trying this out in our API platform. Excellent, we can see we get the correct response from Revue, and if we now check their system, we should see that the person is unsubscribed. Let's also try and see what happens on subscribe. And yes, the subscription also works as intended. Conclusion We set up a dynamic route by using Fastify. This handles a POST request that can hold a uniform subscribe and unsubscribe callback. We only have to host these scripts, and we should be ready to perform end-to-end tests. You can also find the code for today!
https://h.daily-dev-tips.com/revue-sendy-sync-webhook-routes
CC-MAIN-2022-33
refinedweb
658
58.69
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Est ce qu'il y a un rapport entre l'expiration de ma licence support et le fait que mon plugin agile JIRA est désactivé. I apologise for not being able to answer in French, to my shame, I am not able to speak or write it. Yes, your licence expiry means that you can no longer use the Agile functions provided by the add-on. If you renew it, they will return (all your data is safely stored).
https://community.atlassian.com/t5/Jira-questions/Impossible-d-activer-le-plugin-agile-jira/qaq-p/361043
CC-MAIN-2018-09
refinedweb
101
68.7
There are times I'd like to claim to be a specialist, but my resume suggests otherwise. For sure, I am not a specialist in web services. So when duty called for me to become the local ServiceMix and JBI expert, I approached it more from a real-time messaging perspective than a Web Services perspective. This article describes some of the surprises I had in store. Most of these fun facts to know and tell are about JBI and would probably apply to any ESB that was JBI-compliant. A few of them are about ServiceMix specifically. None of them have anything to do with the actual product that we developed. Our development began with ServiceMix 2.0, progressed to ServiceMix 3.0 for our commercial release, and proceeded to test with ServiceMix 3.0.1. The core portion of ServiceMix that implements the JBI spec was quite stable and usable in the releases we chose to use, particularly considering the relative immaturity of the product. Like all active open source projects, ServiceMix is a moving target. Depending on what specific Subversion trunk of ServiceMix you decide to use, your mileage may vary. In the sections below I cite the appropriate portions of the JBI spec for your reference. Service Engines vs. Binding Components [4.3, p. 14] The JBI spec, and most JBI presentations, seem to make a big distinction between a JBI bus component which is a Service Engine (SE) versus a component which is a Binding Component (BC). I find this to be mostly a conceptual distinction, depending on how you choose to think about the components that you develop for your application. The JBI API is exactly the same no matter what you call your component. (Former colleague Rick Block suggested that early in the development of the JBI spec this was not the case.) I think of an SE as a component that encapsulates the implementation of some service and accepts requests and generates responses for that service only over the ESB, using JBI normalized messages inside JBI message exchanges. It may maintain internal state about the service it provides. An SE might front-end a database used to maintain inventory. It might be a JBI wrapper for a legacy service like weather information. It might be an abstract interface to a vastly complex system sitting outside the ESB. It might do something dirt simple like return the time of day from a central clock. I think of BCs as purely protocol converters that serve as gatekeepers between the outside world and the ESB. A BC serves as a proxy between an external client that sits outside of the ESB and an SE that sits on the the ESB. If the BC maintains state, it is only about the transactions that are in progress between the outside client and the SE, or, in JBI-speak, about message exchanges that are in the active state. Once a Message Exchange reaches a terminal state like done or error, the job of the BC for that particular transaction is completed. A BC might convert between external clients using the Java Message Service (JMS) and internal services using JBI messaging. A Simple Object Access Protocol (SOAP) router on the ESB that receives SOAP requests from external web services clients (like your web browser), turns them into JBI message exchanges, and routes them to an SE on the ESB, is also a kind of BC. This is fuzzier than you might think, and discussions over whether a component is an SE or a BC can quickly devolve to how many angels can dance on the head of a pin. For example, suppose you had a component that incorporated a SIP protocol stack to implement complex VOIP control capabilities. You can think of this component as a container of all the SIP endpoints with which it will ever communicate, and the service it provides is a set of high-level communications capabilities. In this sense, it is an SE. You can also think of it as a complicated protocol converter between SIP endpoints that speak only the SIP protocol and SEs on the ESB which speak only JBI messages. In this sense it is a BC. In general, don't agonize too much over whether your component is a Service Engine or a Binding Component. In practice, the distinction isn't terribly important from a purely JBI point of view, although it may be important from an architectural point of view for your application. Separating BC and SE functionality makes your application more flexible if you can design it such that just by adding a new BC you can expose your SEs to a whole new domain of external clients, like SNA systems. Services vs. Endpoints [5.1.1, p. 21] I think of JBI as a fractal collection of containers: the JBI container (in our case, ServiceMix) contains JBI components. Each JBI component contains zero or more services. Each service contains one or more endpoints. Messages on the JBI ESB may be addressed to a service or to an endpoint within a service. For example, a time service on the ESB might be a single service with a single qualified name (a service name within a specific namespace). But that time service might expose multiple endpoints, one endpoint for any of several NTP servers, and each with an endpoint name unique within that service. Requests for time could be addressed to the time service itself, in which case the selection of which NTP server to use is left up to some other mechanism, or it could be addressed to a specific endpoint, so that the time would be provided by a specific NTP server. The JBI spec says that if you addresses a request to a service, the choice of endpoint is implementation dependent; in this case, it really means your implementation when you code the service. Because every service must have at least one endpoint, I sometimes use the terms service and endpoint interchangeably, but as we will find out when we discuss routing, the distinction is important. Providers vs. Consumers [5.1.1, p. 21] Given my background in real-time messaging, I really struggled with this JBI nomenclature, and it turns out to be vitally important to understand the distinction. I am used to thinking of messaging components has having the roles of producer and consumer, as in a message producer is that which sends the message, and a message consumer is that which receives the message. These are strictly roles played during a specific message exchange, so a single messaging component may be both a producer and a consumer at different times. In JBI, provider and consumer are also roles played during a specific message exchange, as in a service provider provides a service, and a service consumer makes a request of the service provider. In this context, the service consumer may never receive a message at all (other than, in JBI, getting a done back from the service provider to indicate the request was successfully received) and a service provider may never send a message (other than sending the done, which carries no payload). As above, a single component may be both a service provider and a service consumer. In receiving a request from a consumer it may act as a provider, but in servicing that request it may act as a consumer by making requests of other providers. Once I got my head around this fact, things got a little easier. A service provider must activate an endpoint on the ESB. The endpoint is one means through which messages exchanges are addressed to the service provider. (More on this later.) Once it does this, it has exposed its endpoint to receive message exchanges from service consumers. If a component does not activate at least one endpoint, it cannot act as a service provider, because service consumers have no way of addressing message exchanges to it. If a component never acts as a service provider, it need never activate an endpoint on the ESB. It can still address message exchanges to service providers, send those exchanges on the ESB, and receive responses. But no other component on the ESB can originate a new message exchange and send it to that consumer because the consumer is effectively invisible on the ESB. The pipe through which components on the ESB send and receive (or accept, in JBI-speak) message exchanges on the ESB is the delivery channel. Think of the delivery channel as a socket and you won't be too far off. The JBI container gives each component on the ESB a delivery channel. When a consumer sends a message exchange to a provider over the delivery channel, the message exchange only contains the address of the service and endpoint exposed by the provider that were used by the consumer to address the message exchange. There is no standard JBI mechanism for the provider to query what consumer sent the message, and in fact it isn't even meaningful to ask the question. Since the consumer isn't required to activate an endpoint on the ESB, it has no address to which new message exchanges to it may be addressed. Of course, the JBI container knows to whose delivery channel to send any response the provider may generate, but this is hidden inside the implementation. And of course, the consumer may also play the role of provider, expose an endpoint on the ESB, and send the address of this endpoint as part of the payload it sends to in its request. But from the point of view of the JBI container, this is the address of a provider on the ESB, not of the consumer that send request. Because there is one delivery channel per component, but a component may expose many services and endpoints to which message exchanges may be addressed, I like to think of components as sending requests, and as the endpoints inside the components as receiving requests. But this is just my way of thinking. Routing [5.1.7, p. 26] Message exchanges may be addressed three ways: to a service (implicit routing), to an endpoint within a service (explicit routing), and to an endpoint reference (dynamic routing). When I described my example of a time service fronting several NTP servers, it probably occurred to you that there might be perfectly legitimate reasons to do either implicit or explicit routing, and you would be quite right. Suppose your application was a hybrid of a Service Oriented Architecture (SOA) and an Event Driven Architecture (EDA). A client component acting as a consumer could make requests of a server component acting as a provider, and those requests would be addressed using implicit routing, that is, with just the service name of the provider. If the request for was for an event stream, the client component could provide a service and a specific endpoint to which those future events would be addressed by the server component. When the server component sends an event it would be acting as a consumer, sending an event to the client who was now acting as a provider, and those events would be addressed using explicit routing, that is, using both the service and the endpoint. (I never said this was simple, but it does illustrates how important it might be to get your nomenclature about roles straight in your mind.) For example, a client component might sent a request to the server component "Lassie" to "look after Timmie", and pass along the service "Mom" and the endpoint "in the kitchen". In the future, should circumstances warrant, "Lassie" would send events like "Timmie fell in the well" to "Mom" "in the kitchen". The events could have been addressed just to "Mom", but this would require the underlying implementation to resolve the specific endpoint, searching "in the barn", "in the kitchen", and "in the bedroom", and it might pick the wrong one. (For purposes of compliance with any hypothetical non-disclosures, any resemblance of "Mom" and "Lassie" to an actual product is purely coincidental.) Dynamic routing is a completely different animal, which is discussed in the following section. Dynamic Endpoint Reference [5.4.4, p. 36] [5.5.4.1, p. 50, Listing 4] Dynamic routing allows a component to be addressed using a fragment of XML that complies with a schema documented in the JBI spec. The schema is specified using Relax NG. This allows components to specify "call back" addresses for future message exchanges as part of, for example, their XML payloads inside of a JBI normalized message. This could have been used in the example above with for "Mom" to have specified the service and endpoint to which "Lassie" would send future events. Such addresses in XML form are referred to as endpoint references (EPR), and the mechanism through which such EPRs are resolved is called dynamic endpoint reference. Here is an example of an XML fragment that might be an EPR. <jbi:end-point-reference xmlns:jbi="" xmlns: In this example, the service name is "Mom", the namespace is "" which is associated purely within the context of this EPR with the XML tag "martin", and the endpoint name is "InTheKitchen". If your application supports dynamic routing and EPRs, it is up to you to write the code to parse this XML and determine what service and endpoint, if any, it identifies. Dynamic endpoint reference resolution isn't rocket science. A component gives an XML fragment to the JBI container and asks what service and endpoint it identifies, expecting to get either null or a service endpoint object in return. ServiceMix simply queries every component on the bus that has activated endpoints, passing it the same XML fragment, in effect asking "Is this yours?", and expecting either a null or a service endpoint in return. I wrote a simple XML parser using the Java Document Object Model (DOM) framework to do just this. You might think that would be the end of it. But you would be wrong. It turns out there are a lot of third-party JBI components out there that expect to use dynamic routing and EPRs, but whose XML fragments do not conform to the JBI spec. One such component is Intalio's implementation of the Business Process Execution Language (BPEL). (We reported this as a bug, so in all fairness this may have been fixed by now.) Intalio chose to format their service name and namespace using a very commonly used but non-standard form known as the James Clark format. Here is an example. <jbi:end-point-reference xmlns: Note that the namespace is part of the value of the service name attribute and not an XML namespace at all. So I modified my DOM parser to handle this format as well. And you would still be wrong. It turns out that ServiceMix itself exposes a managed bean (mbean) for each component on the ESB through which a query can be made and a EPR string identifying that component returned. And indeed, this EPR does not conform to the JBI spec either. Here is an example. <jbi:end-point-reference xmlns:jbi="" xmlns:martin="" jbi:service-name="martin:Mom" jbi: Note that the "jbi" namespace XML tag is prepended to the service name and endpoint name attributes. Maybe this is a valid variation (my XML books suggest it is not), but the DOM framework does not recognize it. So once again I modified my DOM parser to handle this variation as well. Thus far things are quiet on the EPR front. send vs. sendSync [5.5.2.1.3, p. 43] Initially, the messaging operations send versus sendSync seemed pretty straightforward. The former is asynchronous: a component could send a message exchange and go on its merry way doing other work, and any further response regarding that message exchange would be handled in the future when the exchange arrived on the component's delivery channel. The latter is synchronous: the component is blocked on the sendSync until the far end responds in whatever way is appropriate for that message exchange. These were familiar messaging patterns to the real-time developer in me. I have to admit, as a long-time real-time developer, I don't believe in synchronous message passing, even though it is the backbone of a lot of web services messaging frameworks like Axis. In thirty years of building message-based systems, I haven't found synchronous messaging to result in scalable, high-volume, robust systems, although it sure does simplify the coding. Having a really cheap, scalable thread implementation makes it more palatable. Several Java-based frameworks and containers help out in this regard, too. But synchronous messaging makes me nervous in a deadlock is really possible unless we are very very careful kind of way. Since I have a track record for producing successful, mission critical, 24x7 products, the thought that one design mistake might cause the whole shebang to go toes up makes me a little nervous. But with JBI, I discovered one really good reason to use synchronous messaging. When using asynchronous messaging, JBI does not require that order is preserved, and ServiceMix certainly does not guarantee it. That is, when using asynchronous messaging, the order in which one component sends message exchanges may not be the order in which the provider receives them. The UDP datagram socket developer in me said "Oh, yeah, sure". The real-time embedded messaging developer in me clutched his chest, seized, and has not been heard from since. I had made the mistake of thinking of JBI as a real-time messaging system, like any number of others I had used over the years. But while JBI looks like a duck, it sure as heck doesn't quack like a duck. No doubt about it, this is my fault completely, but I'm not exaggerating when I tell you that when I figured out what was happening in my extensive ServiceMix junit regression test suite, I broke out in a cold sweat and probably turned pale. Some digging into the JBI spec, more digging into the ServiceMix source code, and a brief e-mail discussion with Guillaume Nodet, one of the lead ServiceMix developers, verified that [1] there is no requirement in JBI that order is preserved, and [2] ServiceMix's use of a pool of threads for handling asynchronous delivery pretty much insures that order is a function of mostly-non-deterministic thread scheduling. I found this ultimately understandable, but very counter-intuitive. WSDL Binding [5.5.6.1, p. 57] Service providers on the ESB may choose to describe their messaging interface in the form of a service description. A service description is an XML document written using the Web Services Description Language (WSDL). WSDLs, as such service descriptions are casually referred, have an abstract part and a concrete part. The abstract part describes both the syntax and the context of any messages used by the service provider. The concrete part describes the nuts and bolts of where to find the service provider and what protocol to use to talk to it. Service providers may actually have more than one interface that they expose. They may expose one interface to clients external to the ESB. This interface describes a traditional web service and is only reachable through a BC. Service providers may expose another interface to service consumers on the ESB. This interface is available only on the ESB and may expose a much richer set of capabilities available only to other components on the ESB. The neat thing is, both interfaces can be described in a single WSDL. Such a WSDL would have a single abstract part, but two (or more) concrete parts. One concrete part might specify a SOAP binding so that a SOAP router on the ESB could serve as a proxy for the service provider and route SOAP requests from external web services clients across the ESB to the service provider and handle sending responses back. A second concrete part could specify a JBI binding which would tell internal JBI components, including the SOAP router, how to use the internal interface. When the JBI container parses the service description to extract the interfaces and JBI services and endpoints exposed by the service provider, it should (as ServiceMix does) only extract those interfaces, services and endpoints which are associated with the JBI binding. Any interfaces, services and endpoints associated with other bindings are purely a private matter between consenting components such as the service provider (an SE) and the SOAP router (a BC). I didn't personally need to make use of this feature, but I did write code using the wsdl4j tool kit to extract the JBI-bound interfaces from the service descriptions that other developers provided for their components. So it is likely that others may have more to say on this topic. Service Endpoints [ServiceEndpoint, p. 192] A service endpoint is an object which contains, among other things, the qualified name (service name plus namespace) of a service, and the endpoint name of an endpoint within that service, for an endpoint which has been activated on the ESB. It is not unusual for a component to have to keep track of the namespace, service name, and endpoint name of an endpoint which has not yet been activated, for example, based on configuration information gleaned from a properties file. You may be tempted to create your own class that conforms to the JBI service endpoint interface just for the purpose of managing such information. But do not be deceived into thinking that just because your class conforms to the service endpoint interface that you can pass instances of your class with the JBI container as service endpoints. The spec is quite clear on this: the JBI container is the only source of genuine service endpoints, and they are only doled out when an endpoint is newly activated by the container on behalf of the component. Just as only God can make a tree, only the JBI container may make a service endpoint. The underlying reason is of course because the JBI container implementation (ServiceMix) maintains private data inside its own implementation of the service endpoint interface to which you are not privvy. I did in fact make a class just to keep track of endpoints that were defined but not yet activated, but I deliberately did not implement the JBI service endpoint interface, even though doing so would have been very convenient, just so I couldn't accidentally try to pass an instance of this class into one of the JBI APIs. That's the current brain dump on JBI. More later as it occurs to me. Sources Ron Ten-Hove, Peter Walker, Java Business Integration (JBI) 1.0, JSR-208, Sun Microsystems Inc., August 2005 Peter Walker, private communication, 2006 Guillaume Nodet, private communication, 2006 6 comments: Thanks John, this was a great overview for somebody like me with only cursory knowledge of ESBs and JBI! Joel Thank you very much for this brain dump, reading between the lines of the JBI spec... I am using JBI for my thesis and found lots of useful practical information in this detailed blog post. I really enjoyed your post about servicemix. I was wondering and confusing about those concepts and you just cleared lots of things... Thanks a lot. couldn't agree more... if i would have found this bl**dy post months ago, me life would have been so much easier... thumbs up, nevertheless, thumbs up!! Really great article explained everything i need to know about servicemix and JBI. Thanks man :-) Extremely useful for a person trying to grasp the concepts on JBI and its corresponding implementation by ServiceMix. Great work!!!
http://coverclock.blogspot.com/2007/01/fun-facts-to-known-and-tell-java.html
CC-MAIN-2015-11
refinedweb
3,980
58.32
Q: Fast and simple way to store/manipulate pixels? #1 Members - Reputation: 157 Posted 09 August 2012 - 12:03 AM I'm currently experimenting with writing simple 3D engines and so far isn't going too bad. I'm coding with C++ and using SDL. So far I've been using SDL's functions to generate surfaces and to manipulate pixels. However I would like to write my own class to represent surfaces, like so: [source lang="cpp"]struct Color<!-preserve.newline-->{<!-preserve.newline--> Uint8 red;<!-preserve.newline--> Uint8 green;<!-preserve.newline--> Uint8 blue;<!-preserve.newline--> Uint8 alpha;<!-preserve.newline-->};<!-preserve.newline--><!-preserve.newline-->//Create a 1024*768 surface<!-preserve.newline-->Color* Screen = new Color[1024*768];[/source] I want to achieve easy and fast color manipulation, while removing much of the dependency of a specific rendering API. Using the above method I would simply need to convert 'Screen' to the Uint32 format SDL needs at the end of the game loop. I guess I'd like to hear some thoughts on this idea before I proceed. I'm concerned this might not end up being a very efficient way of doing things, however at present it should be faster than converting a Uint32 pixel format to RGB data and then back again (what I'm doing now); I'm only doing one conversion during runtime. Also, is there a common, generic way to represent images that isn't API specific? Frank #2 Moderators - Reputation: 47412 Posted 09 August 2012 - 12:12 AM e.g. Color* Screen = new Color[1024*768]; Uint32* converted = static_cast<Uint32*>(Screen);//no conversion, just telling fibs about the data type, because they're bitwise equivalents anyway.If the API uses a different byte-ordering, you can just rearrange the order of the members in your struct, e.g. struct Color { #if defined(API_ARGB) Uint8 alpha; Uint8 red; Uint8 green; Uint8 blue; #elif defined(API_BRGA) Uint8 blue; Uint8 green; Uint8 red; Uint8 alpha; #else #error "todo - more options" #endif }; Yep, an array of bytes, like you're suggesting ;)Yep, an array of bytes, like you're suggesting ;) Also, is there a common, generic way to represent images that isn't API specific? Edited by Hodgman, 09 August 2012 - 12:18 AM. #3 Crossbones+ - Reputation: 13417 Posted 09 August 2012 - 12:46 AM Just a hint before you dig into your framework and experience a rude awakening later on:Just a hint before you dig into your framework and experience a rude awakening later on: I want to achieve easy and fast color manipulation, while removing much of the dependency of a specific rendering API. If you want fast color manipulation you should not do it with the CPU. Performance wise there are lightyears between the processing power of CPU vs GPU when it comes down to pixel processing (you are literally comparing 1-8 CPU cores with hundreds of GPU cores !). Ashaman Gnoblins: Website - Facebook - Twitter - Youtube - Steam Greenlit - IndieDB - Gamedev Log #4 Members - Reputation: 157 Posted 09 August 2012 - 01:11 AM Ashaman73: I realise that however 1) I'm still fairly inexperienced, and 2) for the environments I'm rendering, the cpu should be enough I think. #5 Members - Reputation: 1224 Posted 10 August 2012 - 01:25 AM Hodgman: Thanks I think I get it. I'm unfamiliar with static_cast but it looks like you can read a section of memory as a different data type. I'm going to check it out. Memory is just blocks of bytes, nothing more. You can read it however you want, but to prevent people from shooting themselves in the foot somewhat, C based languages are type-strict - you have to be explicit when you want to treat memory as different types. In C++ there are 4 types of casts. static_cast, const_cast, dynamic_cast & reinterpret_cast. static_cast is the same as doing a cast in C, like (Uint32*)Screen; It will take the pointer and give the pointer to the memory of a new type, assuming that type is 'castable' from the previous type. For times where the types aren't castable (for example, casting Cheese* to Monkey*) you can call reinterpret_cast, which is like casting C see with a void* layer in between dynamic_cast is the akin to the "as" cast in C# const_cast will cast a const pointer to a non const pointer. #6 Moderators - Reputation: 47412 Posted 10 August 2012 - 01:34 AM static_cast is only valid when the types are allowed to be converted to each other. C++ doesn't know that your RGBA struct is equivalent to an Int32, so static_cast will give you an error. reinterpret_cast is saying "I know this conversion looks dodgy, but trust me", and lets you convert any type of pointer into any other type of pointer. #7 Crossbones+ - Reputation: 4178 Posted 10 August 2012 - 07:00 AM Edited by eppo, 10 August 2012 - 07:07 AM. #8 Members - Reputation: 157 Posted 12 August 2012 - 06:01 PM reinterpret_castwill prove useful. Also I think you're righ eppo. Working with UCHAR data seems to have a few limitations.
http://www.gamedev.net/topic/629345-q-fast-and-simple-way-to-storemanipulate-pixels/
CC-MAIN-2016-18
refinedweb
849
51.78
02 August 2011 10:51 [Source: ICIS news] SHANGHAI (ICIS)--Dushanzi Petrochemical, a subsidiary of ?xml:namespace> The sharp increases in the domestic PE and PP prices have motivated the producer’s change of plan, the source said. The weekly average prices of the benchmark film grade high density PE (HDPE) and yarn grade PP were at yuan (CNY) 11,850/tonne EXWH ($1,843/tonne EXWH) and CNY 12,675/tonne EXWH, respectively last week, which were 2.6% and 3.7% higher from the previous week, according to Chemease, an ICIS service in China. “The producer would have missed out on the current uptrend if it had shut the plant in end July," he added. The facilities, including a 1m tonne/year cracker, a 300,000 tonne/year high density polyethylene (HDPE) unit, a 600,000 tonne/year LLDPE/HDPE swing plant, a 300,000 tonne/year polypropylene (PP) unit and a 250,000 tonne/year PP unit, were originally scheduled to shut from end July for a two-month turnaround. ($1 = CNY6.43)
http://www.icis.com/Articles/2011/08/02/9481683/chinas-dushanzi-petrochemical-delays-pe-pp-shutdown-to-end-aug.html
CC-MAIN-2014-41
refinedweb
176
66.37
by Phoenix Perry and Jane Friedhoff additional edits by Kayla Lewis Game developers are, in greater and greater numbers, turning to openFrameworks' creative coding toolkit to develop their games. Unlike platforms such as Unity, GameMaker, and Construct2, OF was not specifically developed for game makers. However, OF's ability to port to mobile, manipulate video, utilize camera input, support generative graphics, and hook in with devices like Arduino and Kinect (among other features) makes it a very attractive option for developers who want to be able to rapidly produce compelling, unique games. In this chapter, we'll learn about game development in openFrameworks. We'll cover what goes into making a game, as well as how to code a simple space shooter. Finally, we'll put an experimental oF twist on our game by implementing OSC functionality, which will allow you to alter the difficulty of the game live (while the player is playing it). Ready? Let's go! There are as many ways to make games as there are game developers. However, many developers follow an iterative process: adding a single component, testing it, adding an additional component, testing it again, and so on. Regardless of the platform, this method allows game developers to quickly figure out what parts of the initial idea are worth keeping and test additions they think might be interesting without wasting time building a complete game that, in retrospect, isn't compelling. This iterative process can be done digitally or physically. Paper prototyping is the process of testing mechanics and interactions with paper models and analogs. Although these paper prototypes don't necessarily look like the final game, they can be mocked up quickly, allowing developers to experiment with core mechanics more rapidly than they could with code. For example, a puzzle game's board and pieces can be mocked up with paper and dice quicker than it can be implemented in even a basic mobile app. Similarly, when a developer makes a digital prototype, or one with code, they will start by refining game mechanics and keeping assets rough until they get closer to the end. Finally, developers enter the long process of tuning their game–tweaking various parameters until it feels just right. We're going to use openFrameworks to play with the final step of this process. In the game we're making, we're not going to settle on one set of parameters that stay static from game to game. We're going to use openFrameworks' OSC library to allow us to communicate wirelessly from another device (e.g. a smartphone or tablet) so we can tune those parameters live, giving our players experiences tailored just for them. OSC, or Open Sound Control, came about as an advancement to MIDI, so let's talk about MIDI first. MIDI is a data protocol that sends and receives information between devices, typically electronic musical instruments. MIDI is what allowed things like keyboards and drum machines to fire in sync. If you've heard pop music, you've heard MIDI in action. MIDI has data channels, on which you can send or receive single messages, or events. Programmers could associate these MIDI events with actions that their electronic instruments could take. For example, you could set up your keyboard to send data on channel 1, and receive data on MIDI channel 2. More specifically, you could program a specific key (say, the 'a' key) to send out a MIDI event on channel 1. If your drum machine is set up to receive on channel 1, it will receive that message and perform the appropriate action (e.g. playing). A pretty cool system, but one that was limited by its pre-defined and discrete message types. As time advanced, so did computers and the speed of data transfers, leading us to OSC. OSC was designed to allow for more expressive performance data, with different, flexible kinds of messages sent over networks. OSC is a thin layer on top of the UDP (User Datagram Protocol), and allows users to send information over networks just by specifying the network address and the incoming and outgoing ports. (UDP is used frequently in games, and it is possible to use both of these protocols at the same time in the same code base with no issues.) OSC messages consist of the following: /Address1). These patterns can effectively be anything you want (e.g. /EnemySpeed)--think of them as names for what you send. int, string). 6, "Hello world", etc.). There are plenty of inexpensive apps for smartphones and tablets that provide customizable GUIs (complete with buttons, sliders, etc.) for sending different kinds of MIDI messages. Download one (we like TouchOSC) so we have something to send our messages with. With this in mind, let's start making our game! OpenFrameworks handles OSC as an included addon, so our first step will be to run the project generator and create a project with the OSC addon. (If you haven't had a chance to read about addons, now would be a good time to jump over to [here] and do just that!) Launch the project generator, then, in the main menu, click the word "Addons." A popup will appear. Select ofxOsc and then click back. Now, next to the word Addons, you should see ofxOsc. Press "generate". When it completes the project creation process, close the generator and open up the project in either Visual Studio or Xcode. The project will be set up in your myApps folder. Open it now. Here's what our game will have: With all that written out, let's use OSC to affect the following: These three parameters will allow the developer to tailor the difficulty of the game to the individual playing it, second-by-second. Let's start with our testApp. There are a few things we definitely know we'll want classes for, so make corresponding .h and .cpp files for Player, Bullet, Life, Enemy, and LevelController. Remember to #include "ofMain.h" in each of those classes, and to include the .h file of each of those classes in testApp.h. First let's create the basic structure of our game. Games typically have at least three parts: a start screen, the game itself, and an end screen. We need to keep track of which section of the game we're in, which we'll do using a variable called game_state. In this example, our game_state variable is a string, and the three parts of our game are start, game, and end. Let's add a score and a player at this point as well. string game_state; int score; Player player_1; We'll then divide up testApp's update() and draw() loops between those game states: //-------------------------------------------------------------- void testApp::update(){ if (game_state == "start") { } else if (game_state == "game") { } else if (game_state == "end") { } } //-------------------------------------------------------------- void testApp::draw(){ if (game_state == "start") { } else if (game_state == "game") { } else if (game_state == "end") { } } Let's set the initial value of game_state to "start" right when the app begins. //-------------------------------------------------------------- void testApp::setup(){ game_state = "start"; score = 0; } Finally, let's make sure that we can move forward from the start screen. In this example, when the player is on the start screen and releases the space key, they'll be taken to the game. //-------------------------------------------------------------- void testApp::keyReleased(int key){ if (game_state == "start") { game_state = "game"; } else if (game_state == "game") { // blank for now } } Great! Let's move onto our player. Our player's class looks like this: class Player { public: ofPoint pos; float width, height, speed; int lives; bool is_left_pressed, is_right_pressed, is_down_pressed, is_up_pressed; void setup(ofImage * _img); void update(); void draw(); void shoot(); void calculate_movement(); bool check_can_shoot(); ofImage * img; }; Taking this one step at a time: ofPointcalled pos. ofPoints are handy datatypes that contain xand yvalues, letting us access our player's position through pos.xand pos.y. width, height, and speedvariables (which we'll use for collision detection and movement, respectively). setup, update, draw, shoot, and calculate_movementmethods. You may be wondering why we're using all these booleans--why not just check and see which keys are pressed? The problem is that, in openFrameworks, keyPressed() does not return all the keys currently being pressed--just the last key that was pressed. That means that if the player presses up and left (intending to move diagonally), openFrameworks will only report one of the keys being pressed. You can try printing out the result of keyPressed to see this in action. What we'll do to avoid this is instead base the player's movement on the booleans we wrote earlier. If the player presses a certain key, that boolean will be true; if they release that key, that boolean will be false. That way, if the player presses up and left, we'll report up and left as being true until those keys are released. Here's what our new keyPressed() and keyReleased() functions look like: //--------------------------------------------------------------; } } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ if (game_state == "start") { game_state = "game"; } else if (game_state == "game") { if (key == OF_KEY_LEFT) { player_1.is_left_pressed = false; } if (key == OF_KEY_RIGHT) { player_1.is_right_pressed = false; } if (key == OF_KEY_UP) { player_1.is_up_pressed = false; } if (key == OF_KEY_DOWN) { player_1.is_down_pressed = false; } } } Add ofImage player_image to testApp.h, then load the player's image and instantiate the player in testApp's setup(): void testApp::setup(){ game_state = "start"; player_image.loadImage("player.png"); player_1.setup(&player_image); } Finally, update and draw your player in the appropriate part of testApp::update() and testApp::draw(): //-------------------------------------------------------------- void testApp::update(){ if (game_state == "start") { } else if (game_state == "game") { player_1.update(); } } //-------------------------------------------------------------- void testApp::draw(){ if (game_state == "start") { } else if (game_state == "game") { player_1.draw(); } else if (game_state == "end") { } } You should have a player who moves around on-screen. Sweet! Let's make our bullets next. In order to have a variable number of bullets on screen at a time, we need to add a vector<Bullet> bullets to testApp.h. Let's also create a void update_bullets() function, which will update our vector of bullets (and, shortly, trigger the check for bullet collisions). We also want our player and enemy bullets to look different, so we'll add ofImage enemy_bullet_image and ofImage player_bullet_image to our testApp.h file. Our bullet class will look a lot like the player class and have a position, speed, width, pointer to an image, and various functions. The big difference is that the bullets will keep track of who they came from (since that will affect who they can hurt and which direction they move). class Bullet { public: ofPoint pos; float speed; float width; bool from_player; void setup(bool f_p, ofPoint p, float s, ofImage * bullet_image); void update(); void draw(); ofImage * img; }; Our Bullet.cpp will look like this: void Bullet::setup(bool f_p, ofPoint p, float s, ofImage * bullet_image) { from_player = f_p; pos = p; speed = s + 3; img = bullet_image; width = img->width; } void Bullet::update() { if (from_player) { pos.y -= speed; } else { pos.y += speed; } } void Bullet::draw() { img->draw(pos.x - width/2, pos.y - width/2); } Again, this is much like the code for the player, but with two differences: Now that our bullet class is implemented, we can go back to testApp::setup() and add enemy_bullet_image.loadImage("enemy_bullet.png"); and player_bullet_image.loadImage("player_bullet.png"); right underneath where we loaded in our player_image. For now, our update_bullets() function will call the update() function in each bullet, and will also get rid of bullets that have flown offscreen in either direction. //-------------------------------------------------------------- void testApp::update_bullets() { for (int i = 0; i < bullets.size(); i++) { bullets[i].update(); if (bullets[i].pos.y - bullets[i].width/2 < 0 || bullets[i].pos.y + bullets[i].width/2 > ofGetHeight()) { bullets.erase(bullets.begin()+i); } } // we'll call a collision check function here shortly } Our testApp::update() and testApp::draw() will now look like this: //-------------------------------------------------------------- void testApp::update(){ if (game_state == "start") { } else if (game_state == "game") { player_1.update(); update_bullets(); } } //-------------------------------------------------------------- void testApp::draw(){ if (game_state == "start") { } else if (game_state == "game") { ofBackground(0,0,0); player_1.draw(); for (int i = 0; i < bullets.size(); i++) { bullets[i].draw(); } } else if (game_state == "end") { } } Finally, let's add an if-statement to our keyPressed() so that when we press the spacebar during the game, we spawn a player bullet: //--------------------------------------------------------------; } if (key == ' ') { Bullet b; b.setup(true, player_1.pos, player_1.speed, &player_bullet_image); bullets.push_back(b); } } } Remember, the first parameter in the bullet's setup is whether it comes from the player (which, in this case, is always true). Run your app and fly around shooting for a bit to see how it feels. Let's move on to our enemy. This process should be familiar by now. Add an ofImage enemy_image and a vector<Enemy> enemies to testApp.h. Additionally, add float max_enemy_amplitude and float max_enemy_shoot_interval to testApp.h. These are two of the enemy parameters we'll affect with OSC. Your enemy class will look like this: class Enemy { public: ofPoint pos; float speed; float amplitude; float width; float start_shoot; float shoot_interval; void setup(float max_enemy_amplitude, float max_enemy_shoot_interval, ofImage * enemy_image); void update(); void draw(); bool time_to_shoot(); ofImage * img; }; Our enemy's horizontal movement will be shaped by the values fed to a sine wave (which we'll see in a moment). We'll keep track of our amplitude variable so different enemies can have different amplitudes. We'll also want to keep track of whether enough time has passed for this enemy to shoot again, which utilizes the start_shoot and shoot_interval variables. Both of these variables will actually be set in our setup() function. Finally, we'll have a boolean function that will tell us whether the enemy can shoot this frame or not. Our enemy class will look like this: void Enemy::setup(float max_enemy_amplitude, float max_enemy_shoot_interval, ofImage * enemy_image) { pos.x = ofRandom(ofGetWidth()); pos.y = 0; img = enemy_image; width = img->width; speed = ofRandom(2, 7); amplitude = ofRandom(max_enemy_amplitude); shoot_interval = ofRandom(0.5, max_enemy_shoot_interval); start_shoot = ofGetElapsedTimef(); } void Enemy::update() { pos.y += speed; pos.x += amplitude * sin(ofGetElapsedTimef()); } void Enemy::draw() { img->draw(pos.x - width/2, pos.y - width/2); } bool Enemy::time_to_shoot() { if (ofGetElapsedTimef() - start_shoot > shoot_interval) { start_shoot = ofGetElapsedTimef(); return true; } return false; } In update, we're using the current elapsed time, in frames, to give us a constantly increasing number to feed to the sine function, which in turn returns a value between -1 and 1. We multiply it by the amplitude of the wave, making this curve more or less exaggerated. In time_to_shoot(), we check to see whether the difference between the current time and the time this enemy last shot is greater than the enemy's shooting interval. If it is, we set start_shoot to the current time, and return true. If not, we return false. Let's integrate our enemies into the rest of our testApp.cpp: //-------------------------------------------------------------- void testApp::setup(){ game_state = "start"; max_enemy_amplitude = 3.0; max_enemy_shoot_interval = 1.5; enemy_image.loadImage("enemy0.png"); player_image.loadImage("player.png"); enemy_bullet_image.loadImage("enemy_bullet.png"); player_bullet_image.loadImage("player_bullet.png"); player_1.setup(&player_image); } //--------------------------------------------------------------); } } } else if (game_state =="draw") { } } //-------------------------------------------------------------- void testApp::draw(){ if (game_state == "start") { } else if (game_state == "game") { ofBackground(0,0,0); player_1.draw(); for (int i = 0; i < enemies.size(); i++) { enemies[i].draw(); } for (int i = 0; i < bullets.size(); i++) { bullets[i].draw(); } } else if (game_state == "end") { } } Let's implement our bullet collision checks. Add a void check_bullet_collisions() to your testApp.h, then write the following function: //-------------------------------------------------------------- void testApp::check_bullet_collisions() { for (int i = 0; i < bullets.size(); i++) { if (bullets[i].from_player) { for (int e = enemies.size()-1; e >= 0; e--) { if (ofDist(bullets[i].pos.x, bullets[i].pos.y, enemies[e].pos.x, enemies[e].pos.y) < (enemies[e].width + bullets[i].width)/2) { enemies.erase(enemies.begin()+e); bullets.erase(bullets.begin()+i); score+=10; } } } else { if (ofDist(bullets[i].pos.x, bullets[i].pos.y, player_1.pos.x, player_1.pos.y) < (bullets[i].width+player_1.width)/2) { bullets.erase(bullets.begin()+i); player_1.lives--; if (player_1.lives <= 0) { game_state = "end"; } } } } } This code is a bit nested, but actually pretty simple. First, it goes through each bullet in the vector and checks to see whether it's from the player. If it's from the player, it starts a for-loop for all the enemies, so we can compare the player bullet position against all the enemy positions. We use ofDist() to see whether the distance between a given bullet and a given enemy is less than the sum of their radii--if it is, they're overlapping. If a bullet is not from the player, the function does a distance calculation against the player, to see whether a given enemy bullet and the player are close enough to count it as a hit. If there is a hit, we subtract a player's life and erase that bullet. If the player has less than or equal to 0 lives, we change the game state to the end. Don't forget to call check_bullet_collisions() as part of update_bullets(): //-------------------------------------------------------------- void testApp::update_bullets() { for (int i = 0; i < bullets.size(); i++) { bullets[i].update(); if (bullets[i].pos.y - bullets[i].width/2 < 0 || bullets[i].pos.y + bullets[i].width/2 > ofGetHeight()) { bullets.erase(bullets.begin()+i); } } check_bullet_collisions(); } Great! Except… we don't have any enemies yet! Definitely an oversight. This is where our level controller comes in. Add LevelController level_controller; to your testApp.h. Our level controller class is super simple: class LevelController { public: float start_time; float interval_time; void setup(float e); bool should_spawn(); }; As you might guess, all it'll really do is keep track of whether it's time to spawn another enemy yet. Inside our LevelController.cpp: void LevelController::setup(float s) { start_time = s; interval_time = 500; } bool LevelController::should_spawn() { if (ofGetElapsedTimeMillis() - start_time > interval_time) { start_time = ofGetElapsedTimeMillis(); return true; } return false; } When we set up our level controller, we'll give it a starting time. It'll use this time as a baseline for the first enemy spawn. The should_spawn code should look familiar from the enemy bullet section. We'll wait to set up our level controller until the game actually starts, namely, when the game state changes from "start" to "game". void testApp::keyReleased(int key){ if (game_state == "start") { game_state = "game"; level_controller.setup(ofGetElapsedTimeMillis()); } ... } Next we'll integrate it into our testApp::update(): //--------------------------------------------------------------); } } } Awesome! We're close to done! Before we finish, let's add in our last OSC feature: the ability to throw in bonus lives on the fly. Add vector<Life> bonuses and ofImage life_image to your testApp.h. To keep our code modular, let's also add void update_bonuses() in the same place. Don't forget to life_image.loadImage("life_image.png") in testApp::setup(). Life.h should look like this: class Life { public: ofPoint pos; float speed; float width; ofImage * img; void setup(ofImage * _img); void update(); void draw(); }; It'll function like this (a lot like the bullet): void Life::setup(ofImage * _img) { img = _img; width = img->width; speed = 5; pos.x = ofRandom(ofGetWidth()); pos.y = -img->width/2; } void Life::update() { pos.y += speed; } void Life::draw() { img->draw(pos.x - img->width/2, pos.y - img->width/2); } Our update_bonuses() function works a lot like the bullet collision function: //-------------------------------------------------------------- void testApp::update_bonuses() { for (int i = bonuses.size()-1; i > 0; i--) { bonuses[i].update(); if (ofDist(player_1.pos.x, player_1.pos.y, bonuses[i].pos.x, bonuses[i].pos.y) < (player_1.width + bonuses[i].width)/2) { player_1.lives++; bonuses.erase(bonuses.begin() + i); } if (bonuses[i].pos.y + bonuses[i].width/2 > ofGetHeight()) { bonuses.erase(bonuses.begin() + i); } } } All that's left for our lives functionality is to alter testApp::update() and testApp::draw(). //-------------------------------------------------------------- void testApp::update(){ if (game_state == "start") { } else if (game_state == "game") { player_1.update(); update_bullets(); update_bonuses();); } } } //-------------------------------------------------------------- void testApp::draw(){ if (game_state == "start") { start_screen.draw(0,0); } else if (game_state == "game") { ofBackground(0,0,0); player_1.draw(); draw_lives(); for (int i = 0; i < enemies.size(); i++) { enemies[i].draw(); } for (int i = 0; i < bullets.size(); i++) { bullets[i].draw(); } for (int i = 0; i < bonuses.size(); i++) { bonuses[i].draw(); } } else if (game_state == "end") { } } Finally! We've been a bit stingy with visual feedback, so let's add in a start screen, a score, a visual representation of the lives left, and an end screen. Add ofImage start_screen;, ofImage end_screen;, void draw_lives();, and void draw_score(); to testApp.h. Change testApp::setup() to load in those assets: //-------------------------------------------------------------- void testApp::setup(){ ... player_1.setup(&player_image); start_screen.loadImage("start_screen.png"); end_screen.loadImage("end_screen.png"); score_font.loadFont("Gota_Light.otf", 48); } Draw them in the appropriate game states using start_screen.draw(0, 0) and end_screen.draw(0, 0). Add in the last two functions: //-------------------------------------------------------------- void testApp::draw_lives() { for (int i = 0; i < player_1.lives; i++) { player_image.draw(ofGetWidth() - (i * player_image.width) - 100, 30); } } //-------------------------------------------------------------- void testApp::draw_score() { if (game_state == "game") { score_font.drawString(ofToString(score), 30, 72); } else if (game_state == "end") { float w = score_font.stringWidth(ofToString(score)); score_font.drawString(ofToString(score), ofGetWidth()/2 - w/2, ofGetHeight()/2 + 100); } } By using stringWidth(), we can calculate the width of a string and shift the text over (handy for centering it). All that's left after that is to call draw_score() and draw_lives() during the testApp::draw()'s game state, and to call draw_score() during the end state. Congrats–you made a game! Now let's add in the OSC functionality. We are going to set our application up to receive messages from our iPad and then make changes in real-time while our game is running to test some possible player scenarios. As mentioned before, this can trump going into your application and making manual changes because you skip the need to recompile your game and playtest live. In fact, you can even use TouchOSC to open up new ways to interact with your players. TouchOSC is used to switch game levels on the fly and to run challenges. To accomplish this we are going to create a new class that will contain our OSC functionality. Create a .cpp and .h file for this class now and name it LiveTesting. Open LiveTesting.h And let's add the line to import the OSC at the top of your file after your preprocessor directives and also a line for using iostream for testing purposes. As we add the code we will explain inline in code comments. Add the following: #include <iostream> #include "ofxOsc.h" Next let's set up all of the variables we are going to use to receive OSC data and map it to game values. Add the following code into your class: class LiveTesting { public: LiveTesting(); //a default c++ constructor void setup(); //for setup void update(); //for updating ofxOscSender sender; //you can set up a sender! //We are going to use this network connection to give us //some visual feedback of our current game values. ofxOscReceiver receiver; //this is the magic! This is the port on which your game gets incoming data. ofxOscMessage m; //this is the osc message your application gets from your device. //these are the values we will be tweaking during testing float max_enemy_amplitude; int interval_time; float max_enemy_shoot_interval; bool triggerBonus; }; Now let's jump over to the LiveTesting.cpp file. In this file we are going to set up our network address and the ports we are sending and receiving data on as the first order of business. However, to go any further we are going to need to do some housekeeping and install additional software. For OSC to work it will need a local wifi network to send the messages across. (Note this tactic may not work for a network outside of your own because often a sysadmin will stop this kind of traffic from being transmitted on a very public network. We suggest bringing an Airport Express or something similar with you so you can quickly and wirelessly establish a local network for play testing.) For the purpose of this chapter and to allow us to create an experience that will work on both Android and iOS, we are going to use a piece of software called TouchOSC from this URL: The desktop editor software is free, however, the matching software for your device will be $4.99. Get both now. As a matter of principle, we endorse building your own tools and you could easily build a second oF project to be your OSC sender and receiver on your mobile device. With that said, nothing beats TouchOSC for speed, ease of use, and complete, platform independent flexibility. If you are someone who often moves between an iOS and Android device on both Windows and Mac, this tool will become indispensible to you. As a game's designer it can open up possibilities like changing levels on the fly, updating game variables, adjusting for-player feedback, and adding new features into and taking them out of your game as it's running. We highly endorse using it and support the continued advancement of the tool. You can also use it with music production tools like Ableton Live and it comes with great presets for things like DJing and mixing music live. Go to the app store of your device and purchase the mobile version now if you would like to continue down this route. After we get all of the tools downloaded and installed, let's start setting everything up. You are going to need two bits of information. You are going to need to know the IP address of your computer and the IP address of your laptop. If you are on a Mac, just open up your System Preferences. Go to the Network setting and click on your WiFi connection in the left sidebar. On the right side it will display your IP address. You can also get this setting by opening up Terminal and entering in the command "ifconfig." Terminal will list every network that's a possible connection for your machine from the past, even if it's not currently active. For example, if you have ever connected your phone, it will be in the list with some flag and listed as inactive. Look for the connection that's currently active. It will look something like this: en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 60:33:4b:12:e5:3b inet6 fe80::6233:4bff:fe12:e53b%en1 prefixlen 64 scopeid 0x5 inet 192.168.0.5 netmask 0xffffff00 broadcast 192.168.0.255 media: autoselect status: active The inet address is your current IP. On Windows, open the charms bar. In search type cmd and open the command prompt. Type in ipconfig. This information is much clearer than the data dump from terminal. The connected listed as your Wireless LAM adapter Wi-Fi will list your current IPv4 address. This is your IP address. Finally, obtain your mobile device's IP address as well from your device settings. Make a note of your IP address for the next section. At this point, go ahead and launch TouchOSC on your device and the TouchOSC desktop editor on your computer. If you are on Windows, you will need to make sure you have Java installed first. Once the software is open, click the open icon in the top tool bar. In the file containing the code for this chapter you will see a file called ofBook.touchosc. We are going to make this interface now and deploy it to our phone. We will make this interface to control certain parameters in our game: //these are the values we will be tweaking during testing float max_enemy_amplitude; int interval_time; float max_enemy_shoot_interval; bool triggerBonus; To build the app, let's start by adding our first knob. Right click in the black empty space to the right. Choose to make a rotaryH. Next make two labelH objects. The first one will be the name of our knob. The second one will be for displaying the value of the current variable in our game. Place one label above the knob and one below. It should look like this: Now look to the left side of the app. At this point, it's time to set all of the values this knob will be sending and what the labels will display. Let's start with label1. We will name our knob on screen to make things easier to read. The first value in our game we want to control, the level controller interval time, should be what this label reads onscreen. Changing the name field in the app interface will do little. However, note under the name field you can change the color of the label. For this example, use yellow. Next, jump down to the next to last field on screen called Text. You will want to set this to 'level controller interval time'. Moving on, select the knob. This one will require more set up because it will actually be sending values to our game. Color it yellow first. In the dark grey OSC box set all of the values we need to receive for the game. If auto is checked, uncheck it. Now customize the text in that box to /game/interval_time. In the From fields set the parameters to a range of values to try out in the game during a playtest. We will use from 0 to 300. These two elements, the tag, and the parameters will get packed up into a message and sent over our OSC network to our game when values change. The last thing to set up will be the bottom label to display what our interval variable is currently set to in our running game. Select it. We will change the settings and the address tag to reflect that it is not game data being sent to our game but rather data being sent out of our game. Select the label on screen to pull up the parameters for it on the right. In the darkened OSC box change the parameters to those below: This is the pattern we are going to use for all of our knobs and labels. Essentially, the pattern is: Do this now for the other two knobs. The settings are below for each one. Label / Knob Set Two Label / Knob Set Three We are going to add one more but this one will be a Push Button instead of a RotaryH. Right click to create it just like the knob. Make the Push Button and two labels. Here are the settings: Save your file to your hard drive desktop and name it PlaytestInterface. You are done building your interface for play testing. Now let's deploy it! On your mobile device, launch TouchOSC. It will launch and open a settings screen. This is when we need the network address of your computer we retrieved earlier. Under Connections, touch OSC: [KL: Is this colon intentional? Unfortunately I can't follow this part of the tutorial right now to know for sure.] and set it to the IP address of your computer to link the two. It should look something like 192.165.0.3. The ports also need set. Tap each one and set them to these values: Port (outgoing) 8001 Port (incoming) 8000 Next tap TouchOSC in the upper left corner of the app to go back to the settings. Now click on Layout. Then tap Add. It will start to search for your computer. Switch back over to your computer now and into the TouchOSC Editor. Press the green Sync arrow. Switch back to your device. You should see your computer listed under FOUND HOSTS. Select it. It will pop back to the settings screen. Scroll down and find PlaytestInterface in the list of interfaces. Select it and it will take you back to the main menu. Press Done in the upper left corner and your interface will now launch. If you want to get back to the settings screen at any point, the white dot in the upper right-hand corner will return the user interface to that screen. Finally, TouchOSC is set up! Let's link it to our game and run our very first playtest. Go back to the programming IDE. Open LiveTesting.cpp. In our default constructor, we will now set up our game to send and receive values over the network. To do this we will need to know which IP address and port on our device we will send to as well as set up a port on our local computer's network to receive incoming data. Your computer will have only one IP address but it can send and receive data on thousands of ports. We aren't going into too much detail about ports, but you can think of the IP address like a boat pier. Lots of boats can be docked at a single pier. This is no different. Your ports are your docks and your IP address is your pier. You can think of the data like the people departing and arriving. You'll need a separate port for each activity in this scenario. If a port isn't used by your operating system, you can send and receive data there. [KL: since IP addresses were mentioned earlier, maybe this analogy should also be introduced earlier.] We are going to use 8000 and 8001. The final thing to establish is the address pattern. It will look like a file path and allow us to specify that our messages match to their right values. Add this code: #include "LiveTesting.h" LiveTesting::LiveTesting(){ sender.setup("192.168.0.11", 8000); //this is the IP address of your iOS/Android device and the port it should be //set to receive on receiver.setup(8001); /*this is the port your game will receive data on. For us this is the important one! Set your mobile device to send on this port.*/ m.setAddress("/game"); /*This is OSC's URL like naming convention. You can use a root URL address like structure and then everything under that address will be accessible by that message. It's very similar to a folder path on your hard drive. You can think of the game folder as your root directory and all the bits that are /game/someOtherName are inside of it.*/ } In the above code we simply set up our network address, incoming and outgoing ports and created a default address pattern. From here we should be good to set up the messages we'd like to send and receive in our code. Let's move on to the next major function we want to write. We need to run an update function in this class to update every frame so we can make sure that if we move a slider on our mobile device that change becomes reflected within the game. Also, we might want to send that value back out once we receive it so we can get some visual feedback on our device to let us know what our current settings are. Each time we make a change on our device, it will send over the updates to our code via TouchOSC. We want to make sure we get all of the incoming messages that are being sent so we will create a simple while loop. We will loop through the whole list of messages that came into our game that frame and match it to the corresponding variable in our game via if statements. while (receiver.hasWaitingMessages()) { //get the next message ofxOscMessage m; receiver.getNextMessage(&m); Every incoming message will come with its own unique address tag and new arguments. You can get access to a message's address via the getAddress function. For example, if(m.getAddress() == "/game/max_enemy_amplitude"), will test to see if the message address is /game/max_enemy_amplitude. If it is, set the variable equal to that value in your game's codebase so they are linked together. Every swipe of the knob will translate to direct changes in your game. We do this for every single value we want to set. if(m.getAddress() == "/game/max_enemy_amplitude") { max_enemy_amplitude = m.getArgAsFloat(0); //these values send back to OSC to display the //current settings for visual feedback sendBack.addFloatArg(max_enemy_amplitude); sendBack.setAddress("/updatedVals/max_enemy_amplitude"); sender.sendMessage(sendBack); cout << max_enemy_amplitude << endl; } At the same time, we are also going to send those exact same values back out to our device so we can see the numbers that the settings in our game are currently at. [KL: You might want to make this sentence more concise, preferably not ending with "at."] This is handy for two reasons. One, you get visual feedback of the current variables' values on your device. Two, if you happen to land on settings that feel right in your game, you can take a screen cap on your device. After stopping the game, go back and change the variables to match in your code and the next time you run your program, it will start with those parameters. To pack up all of the values in our current running game and send them back to the device every frame, we will create a variable of type ofxOscMessage called sendBack. When we have a string match for the address in the ofxOscMessage m, we just copy the arguments over to sendBack via the right function (in this case usually addFloatArg) and set the address pattern using the setAddress function. Finally, we use the built in sendMessage function to send the message out over OSC. Here's the complete code to add to your LiveTesting.cpp file void LiveTesting::update() { //our simple while loop to make sure we get all of our messages while (receiver.hasWaitingMessages()) { //Get the message, which will hold all of our arguments inside of it. //It's a collection of data ofxOscMessage m; //Pass a reference to that message to the receiver //we set up above using the getNextMessage function in the OSC add on. receiver.getNextMessage(&m); //This will be the message we send back from our game //to our device letting it know what value we received //from it and displaying that back to us so we know what our //current game settings are at. ofxOscMessage sendBack; //Remember our address tags are unique. //We set up the /game tag as our root address and each "/" denotes a sub tag. //If these strings are a match, we know the message that came in is our //amplitude. if(m.getAddress() == "/game/max_enemy_amplitude") { //This is critical. //Each type must match if you want to be able to run your code. //We know the first argument in our array of messages //will be a float if the above if statement evaluates to true. max_enemy_amplitude = m.getArgAsFloat(0); //Now we are going to pack up a collection of data to send back to //our device. //sendBack is also a collection of data we //add arguments to. //Add the value we set for our amplitude to the message and move on. sendBack.addFloatArg(max_enemy_amplitude); sendBack.setAddress("/updatedVals/max_enemy_amplitude"); sender.sendMessage(sendBack); cout << max_enemy_amplitude << endl; } else if (m.getAddress() == "/game/interval_time") { //This is exactly the same as above. //We are simply testing to see if the address //tag is this value, and if so, doing the exact //process of setting our ingame value to match the value of the //incoming argument and sending back our interval_time to our device. interval_time = m.getArgAsInt32(0); //Send visual feedback. sendBack.addIntArg(interval_time); sendBack.setAddress("/updatedVals/interval"); sender.sendMessage(sendBack); } else if (m.getAddress() == "/game/max_enemy_shoot_interval") { //again the same process of testing the address tag max_enemy_shoot_interval = m.getArgAsFloat(0); //Send visual feedback. sendBack.addFloatArg(max_enemy_shoot_interval); sendBack.setAddress("/updatedVals/max_enemy_shoot_interval"); sender.sendMessage(sendBack); } else if (m.getAddress() == "/game/triggerBonus") { //Finally we wrap it up. This is last test. triggerBonus = m.getArgAsInt32(0); cout << triggerBonus << endl; //Send visual feedback. sendBack.addIntArg(triggerBonus); sendBack.setAddress("/updatedVals/triggerBouns"); sender.sendMessage(sendBack); } } You have reached the end of the tutorial. [KL: Make this statement more congratulatory. It's a great accomplishment!] Now do a real testing session. Run the game and have a friend play it while you change the knobs. Once you have settings you like, quit the game and add those values into the code to make them permanent updates. For a bonus challenge, find a few settings you like and create a difficulty ramp for the game using those values of time. We've reached the end of the chapter but not the end of the journey. A few great resources for independent games scene are listed here: Come Out And Play Kill Screen Indiecade Babycastles Polygon IDGA Game Dev Net Game Dev Stack Exchange Gamasutra Digra Different Games This chapter was written by two members of the Code Liberation Foundation, Phoenix Perry and Jane Friedhoff. This organization teaches women to program games for free. Featuring game art by Loren Bednar. We build community, create safe spaces for women who want to learn to program in a non-male dominated setting and generally rock.
http://openframeworks.cc/ofBook/chapters/game_design.html
CC-MAIN-2017-04
refinedweb
6,806
65.12
Following our announcements about namespace separation, we are now offering the chance for customers to auto-convert their ‘Messaging’ type namespaces that contain eventhub entities into ‘EventHub’ type only namespaces in the Azure portal. As a pre-requisite in doing this, your ‘Messaging’ type namespace can only contain eventhub entities. If the namespace also contains queues, topics, or relays we cannot auto-convert this for you. These other entities besides eventhubs must be deleted before opting into auto-converting. Once you are ready, please follow these steps after logging into the Azure portal. Please note to log in with admin access for the account you will be making the namespace changes with. 1. Select the Messaging type namespace with the eventhub entity (or entities) you want to auto-convert 2. On that Namespace blade make sure ‘Overview’ is selected from the menu items and next select the option to ‘Convert’ 3. You will then be asked to opt-into converting your namespace, please check the box and enter the name of the namespace you wish to convert 4. Once ‘Convert’ is clicked it will take a few minutes for us to change the type. You will also need to refresh the portal to see the actual changes to the namespace into an ‘EventHub’ type. This namespace can now be found under your Event Hubs resources and won’t be visible under Service Bus 5. Following this, we recommend that if you use ARM templates to make the appropriate changes to the resource provider, this will be a change from ‘Microsoft.ServiceBus’ to ‘Microsoft.EventHubs’. Additional info regarding this is discussed in this blog post.
https://blogs.msdn.microsoft.com/eventhubs/2016/11/09/namespace-auto-convert-from-messaging-type-to-eventhub-type/
CC-MAIN-2018-05
refinedweb
274
61.97