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 |
|---|---|---|---|---|---|
This article is the first of a series of three articles.
Part 1: Necessity of Pragmatic Front-End Testing Strategies
Part 2: Testing Visual Components Using Storybook
Part 3: Testing Logic in State Management Using Cypress
It is the height of JavaScript. For the past couple of years, JavaScript has maintained its championship title as the most popular programming language, and is still rapidly developing. As someone who began on a path of a front-end developer more than a decade ago, in a lawless wasteland without the simplest concept of the Web Standard, I can’t help but feel humbled by JavaScript’s achievements. Observing the stunning evolution of web development, from having development environments that do not deserve their names to being inundated with cornucopia of resources, tis truly the golden age.
Among all of the shining accomplishments, the improvement in testing methodology and tools is the most encouraging. For years, front-end testing seemed to me like a glorious castle in the sky. No matter how desperately I tried to apply the existing testing methods, none were suitable to test front-end codes, and the meek test results after arduous testing procedures left me insatiable. However, recently emerging tools are providing developers with excellent solutions to the problems of the past, as if to boast the experience gained through years of trial and error.
In this series of articles, I will humbly introduce Storybook and Cypress, the two tools most worthy of the attention, and discuss effective strategies for real-world front-end testing.
Before we get started, let’s all agree on something, here. To roughly define “test” within the software realm, it is “an act to verify that the application functions appropriately under given requirements.” Most of the times, Quality Assurance (QA) is a mandatory step before the product is actually delivered to the hands of the users, and this process basically summarizes the core idea behind testing. However, if you inspect the development cycle more holistically, such testing occurs at every step of the way. For example, validating and improving the UX during the prototype phase, calling the API from the server and cross-checking the expected value, and comparing the final design and the markup result after the first draft of the program are all examples of said tests.
Let’s look at more examples to see how frequent testing really is in the real workplace environment. Say I’m working on a simple Todo Application with React, and currently working on a “Finish Task” feature. I would have to write a code to take the user’s click event to change the state of the task to “Completed.” In order to verify that the state has been changed according to plan, I click on the task and in my developer tools, I verify that the component’s state has successfully changed to “Completed.” Since the “Completed” tasks have to be checked and cancelled out in the UI, I add the appropriate CSS to the component, and click on the task again to make sure that it runs correctly. Upon figuring out that the “Completed” state has to be managed not within the component, but in the Redux’s store, I do some refactoring, and I do the whole thing all over again.
In the example in the previous paragraph, clicking on the component and verifying the results are all parts of a test. In reality, developers “run tests” during the development cycle, and most of tasks habitually carried out by developers after saving the code are related to testing.
The main problem is that such tests are repetitive. As you can clearly see in the previous example, the testing consists of repeatedly “clicking” and “verifying” tasks. If these tasks are carried out manually every time, as the application complexity grows, so will the cost of testing. If testing cost increases, you naturally and gradually put off testing, and the performance of the product plummets. Also, the pressure from having to run such tests will make you more unwilling when it comes to changing the code to improve it, and this also leads to the performance of the product taking a nosedive.
If these tedious tests are automated, it could seriously cut down on the testing time, and prevent forgetting to run tests or making mistakes during testing. Also, automated testing eliminates the fear of refactoring, and will eventually lead to better codes.
(From this point on, I will only refer to "tests" to refer to “automated tests that are written by developers.”)
I’m certain that most of you will agree with me when I say that “testing is important.” However, it is not to say that all of the tests have to be automated. I say that because writing tests costs resources. Therefore, if the opportunity-cost of writing the test is low, don’t bother writing automated codes, and just do it manually. Sometimes, people set overly ambitious goals like pursuing 100% coverage or writing automated test codes for simple actions with close to no logic, and such goals are wasteful of resources that could otherwise be valuable.
It is better to boldly remove any piece of code that you think is redundant, even if it is a part of an existing test code. This is because as the application keeps on changing, the test codes must change as well. As it is considered to be a good practice to remove unnecessary codes from the product, it is also encouraged to actively remove unnecessary test codes to reduce maintenance cost. Even Kent Beck, the rediscoverer of Test-Driven Development has expressed his thoughts on the matter.
I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence … If I don't typically make a kind of mistake, I don't test for it. From Stack Overflow
Trying to test for perfection is the easiest way to write codes that will inevitably become complicated program that is also prone to error … If the program is too simple to have any or little possibility of error, it is better not to test. From Extreme Programming Explained
Because different test codes have different maintenance cost and benefits, in order to properly weigh opportunity cost for tests, it is imperative that you know what makes a good test.
So, what makes a good test? This question is extremely difficult to answer because tests are affected by numerous variants including application’s characteristics, tools and languages used in development, and user environments. While it may be difficult to definitively say what makes a perfect test, I have organized five key properties of a good test.
Faster tests mean faster feedback every time you edit your code. This will inevitably make the entire development process faster, while allowing you to run tests more frequently. If you need to wait for hours just to see the test results, what good are the tests, really?
In other words, “write the test with the interface in mind” or “do not write implementation dependent tests.” To look at it from another angle, this also applies to chunking the test units into too many small chunks. If the test cracks even at the slightest refactoring, not only does it deprive the test of its credibility, but also demands more time and resources to fix the test codes.
To put it differently, “tests that validate buggy codes should fail.” If the expectations are not specified in detail, or if the program does not test through every imaginable scenario, some bugs could go unnoticed. Also, excessive usage of mock objects can make it difficult to detect errors that could occur during the connection stages even the dependent objects are edited. Therefore, test specs must be comprehensive, and refrain from using mock objects as much as possible.
If the test that worked perfectly yesterday suddenly doesn’t work today, or if the test that had no problem with certain devices but doesn’t run on other devices, you’d probably lose faith in the test. Good tests should minimize the external and environmental effects on the results, as to produce the same results no matter the given conditions. The environmental aspects include time, device OS, and network status, and good tests should be designed so that such elements can be directly manipulated using mock objects or external tools.
By now, I think everyone acknowledges that code readability is important. One of the defining characteristics of good codes is that “people” can easily read and understand the code, not “machines.” Test codes should be held to the same standards; anyone should be able to look at the test code and tell you the purpose of the test. Illegible codes demand more resources when the code eventually has to be edited or removed. If the test requires repetitious and lengthy codes need to be constantly called or if validation codes are unnecessarily verbose, it is better to simply create a function or use assertion statements to handle such tasks.
Individual criterion is easy to satisfy. However, the problem rises when they start to inevitably contradict each other. For example, writing tests with smaller units allow faster execution and comprehensive validation through suite segmentation. However, such tests are prone to malfunctioning even at the slightest refactoring, thereby raising the maintenance cost, and with increased number of necessary mock objects, they are more susceptible to undetected errors. Furthermore, incredibly thorough testing specs are excellent for detecting bugs, but the very same intricacy render the purpose opaque.
With everything said, it’s probably impossible to build the perfect test that fits every single criterion mentioned above. Therefore, it is paramount to strategically decide what kind of compromises you are willing to make. Especially since front-end codes are closely related to the Graphic User-Interface (GUI), and must carefully consider various environments of users, each platform demands different codes and different strategies. Each segments of the product, including visual elements, server communication, user interface (UI), and etc., requires personal meticulous strategizing.
When it comes to front-end testing strategies, one of the most important factors of consideration is the tools. At the beginning of the article, I mentioned the modern advancements in testing tools not because I was overly sentimental looking back, but because these tools are extremely helpful when designing effective testing strategies. For example, while previous E2E (End to End) testing tools were a double-edged sword because they offered user-perspective tests that were not affected by implementation detail, but they also were complicated to write and were extremely slow, Cypress, a modern E2E tool, offers the same benefits of the ancestors while being intuitive, fast, and stable. Therefore, the advancement of testing tools leads to better testing strategies.
Welp! What an introduction. I think I’m finally done with rambling about why I decided to title this article “Pragmatic Front-End Testing Strategies.” To summarize, effective tests require effective strategies suited to the front-end environment, and the latest tools facilitate coming up with such strategies.
Finally, let’s get into what efficient testing strategies are using a simple Todo app as an example.
Throughout the article I will refer to the renowned TodoMVC, and I used React and Redux to build my own for testing purposes. However, the contents of this article are not restricted to certain libraries, so the same strategies should be applicable do applications not written in React as well. The application, when executed, will look like something in the following image.
(Image 1: TodoMVC Application)
(While the original TodoMVC uses localStorage to store lasting data, but to test communication with the real server, I used a different local server.)
Assuming that data already exist on the server, let’s imagine we’re adding new to-do items after launching the app for the first time. The internal execution procedure can be broken down in the following order.
That looks like a lot, but the entire process can be broken down into two main categories. Steps 1,3, and 7 fall into the first category, displaying visual state of the application on the window. The second category, changing the current state of the application with the given external input (user input, server transmission,) include steps 2,4,5, and 6. This should remind you of models and views, frequently used in the MVC pattern.
Such categorization is important because each segment requires different strategies when testing. Especially, since it is difficult to write a code to automate tests for visual elements, testing visual elements and state changes at the same time would be incredibly costly. Therefore, it is important to design the application so that such tests can be conducted separately. Latest frameworks like React and Vue provide features to separately manage visual elements and state changes as default.
First, let’s look at how we should go about testing visual elements.
Often, when people talk about testing the View within the MVC pattern used in front-end, it is most common to test the structure of the HTML codes. Given that HTML and CSS determine the visual representation of the application, CSS is rarely dynamically controlled, so it makes sense. The simplest test would be to compare the parts of the resulting HTML with what you expect to happen in string format. If testing for components in the header area, it would look something like the following.
import React from "react"; import { render } from "react-dom"; import prettyHTML from "diffable-html"; import { Header } from "../components/header"; it("Header component - HTML", () => { const el = document.createElement("div"); render(<Header />, el); const outputHTML = prettyHTML(` <header class="header"> <h1>todos</h1> <input class="new-todo" placeholder="What needs to be done?" value="" /> </header> `); expect(prettyHTML(el.innerHTML)).toBe(outputHTML); });
The
diffable-html library from the example above formats the input text so that it would be easier to compare to an HTML text. This way, you can clearly see how the result of failed test differs from what you expected it to be, and solves the issue that the returned value of
innerHTML may differ from browser to browser because of inner representation of different browsers. Also, you can write more readable test codes because you don’t have to worry about basic styling of the HTML like indentation and line changes.
It turns out that manually hardcoding the expected HTML text to compare to the resulting code is quite difficult. It only works out like it did because the example above has a simple structure, but if the structure of the code were even a little more complicated, the complexity of the test code would have increased drastically. Therefore, when conducting tests of similar nature, it is more common to simply copy and paste the HTML created by the real component using the console.log() found in the browser’s testing tools.
Such method does not conform to the Test-Driven Development (TDD) methodology where you define what you expect before the test. This kind of testing does not provide any feature that improves the development speed by offering prompt feedbacks, and truthfully, is just a simple regression test. Also, it can become ridiculously tedious copying and pasting the result of the test every time there is a change to the code. Testing tools like Jest, recently introduced the Snapshot testing to solve such issues.
For snapshot tests, you don’t need to hardcode the expected data, but the tool saves the first result of your program as a file. Then, every time the test is ran, the result is compared to the previously saved file. While it still acts as a regression test, it eliminated the hassle of writing the expected results manually. The code below is an example of comparing the previous view using the snapshot testing method.
import React from "react"; import { render } from "react-dom"; import prettyHTML from "diffable-html"; import { Header } from "../components/header"; it("Header component - Snapshot", () => { const el = document.createElement("div"); render(<Header />, el); expect(el.innerHTML).toMatchSnapshot(); });
Now, doesn’t that look much simpler? Although you can’t directly verify the expected results in the test program, instead you can see that
*.js.snap. file has been created in the
__snapshot__ folder, and the file contains the expected result as such.
exports[`Header component - Snapshot 1`] = ` " <header class=\\"header\\"> <h1> todos </h1> <input class=\\"new-todo\\" placeholder=\\"What needs to be done?\\" value > </header> " `;
Actually, React component doesn’t return real HTML, but a virtual DOM called React Element. Creating and editing the actual HTML code is
react-dom’s task, so strictly speaking, is not included in the testing scope of individual components. Therefore, it is more common to simply test the returned React element’s tree structure when testing React components.
To facilitate testing React components, React provides
react-test-renderer library, and this library lets you test how the component works without actually having to render it.
import React from "react"; import renderer from "react-test-renderer"; import { Header } from "../components/header"; it("Header component - Snapshot", () => { const tree = renderer.create(<Header />).toJSON(); expect(tree).toMatchSnapshot(); });
In the example above, it uses
react-test-renderer’s
toJSON() function instead of creating the DOM element to directly render from it. This function can be useful because now the browser’s rendering engine is no longer needed, and we can test in the Node.js environment without the help of JSDom.
Jest provides more functionalities to support snapshot comparisons and update. To learn more about snapshot testing, refer to the official Jest documentation.
Both HTML Difference method and Snapshot testing compare the HTML structure to test the visual elements of the product (even React element tree can be considered to be HTML structure.) However, considering the five conditions of a good test, HTML structure comparison has these following flaws.
The second category dictates that for good tests, “altering the implementation detail should not break the code.” Hence, the tests should validate “what” the code does instead of “how” the code does. However, HTML is, strictly speaking, not the result of visual elements, but is more of implementation detail--how the visual element is represented. This is because the final product of the visual components are the images displayed on the screen, not the HTML structures.
Such implementation dependent tests are easy to malfunction even at tiniest changes to the code, so it costs more to maintain. Let’s take the
Header component as an example. If a
div tag was used instead of the
header tag, or if the
new-todo class was renamed as
add-todo, the test would break despite the fact that the final product would look and function the same. As such, the test code has to be updated even when refactoring HTML and CSS codes, and this slows down the entire operation down.
Another requirement is that the “purpose of the test should be clear.” However, the HTML structure does not fully represent the resulting image that is displayed on the screen. Even if you include the CSS in the test, it is almost impossible to perfectly picture the resulting image just by looking at the code. This is also why we can’t hardcode the expected HTML values when writing test codes. You can only be certain that the code you wrote does what you wanted it to do, only after displaying the result on the browser.
These kinds of codes are hard to manage. Other developers, or even you, who actually wrote the test code, can have trouble pinpointing what the purpose of the test was. Eventually, you mindlessly copy and paste the results and update the snapshot every time the test fails, and this has murderous effects on the credibility of the test.
The most accurate test for visual components would be to compare the images displayed on the screen down to each pixel, and other tests cannot be described to be cost-effective. Then, our only hope would be to load the view component, take a screen shot, and the compare it to the expectation. If you decide to use the final draft of the design as the expected value, for most precise test results, you could actually take a screenshot and compare the two images every time you edit your code.
The technique I just described, while it sounds tedious, would produce the most accurate test results. Tragically, however, final design handed to you do not comprise every possible scenario, so such method, as a mean of testing every state of the application, cannot be suitable. Considering other elements like display resolution, browser rendering methodology, size of device viewport, and etc., it makes comparing each pixel idea sound even more ridiculous in terms of technical difficulties.
While it may seem anticlimactic, in my opinion, no technology has yet to triumph over the “developer’s eyes” when it comes to visual testing. Despite the fact that many tools are still being developed constantly, our innate sense and instincts have not yet been beaten. Even when programming HTML and CSS codes, you habitually check the result of the change you’ve made to the code, and expect a change to have happened each time. I personally think that technology has yet to produce a tool that can aptly replicate this series of events.
Does that mean visual tests cannot be automated? It’s 50:50. While complete automation is still not realistically achievable, UI development process itself can be improved. The tool that provides a new way of developing the UI is the Storybook.
(It is true that recently, tools like Applitools and Chromatic have reconciled the different rendering methods of different browsers, and drastically improved the visual testing method of comparing image files. However, these tools are used to conduct regression tests, and are more effective when used together with the tool that I’m going to introduce now--the Storybook. In part 2 of this series, I will briefly introduce using Storybook and regression testing tools.)
In the official website, it labels the Storybook as “UI development environment.” To be fair, Storybook is more of a tool that provides developers with a better environment in which to work on UI development than a testing tool. It is, as you can see, is a sort of a component gallery. As you can see in the following image, it allows you to register collection of components used in your application for each page, and provides a way for you to easily visually check the product using the navigator.
(Image 2: Storybook Example – Components used in TOAST File)
Now you might be wondering how this tool can help us with running our visual tests. Remember how I said everything you do to check the result of the code after saving can be classified as testing? If every possible combinations and input values of the components are already saved and registered, much of the process I mentioned earlier can be automated.
For a more specific example, let’s refer to a situation where you have to change the size of the icon in the “File Upload Complete” pop-up. To check the result, you would have to change the code, upload it, and actually wait for it to finish uploading. But alas, upon checking the results, you can see that the icon has become too big and it has covered the text. Now, you repeat the process of changing the code and waiting to check for results only to find out that now the icon is too small. Guess what? You do the same thing all over again.
These series of events are results of the fact that the visual elements are linked directly to the state of the entire application. The process of uploading and waiting for the file is simply to make sure that the state of the application is acceptable to you. If the Storybook has “Upload Complete pop-up” component individually registered, the tedious repetitions would no longer be necessary.
So far, I have illustrated the importance of test automation, qualities of good tests, and also the importance of testing strategies. Furthermore, I have discussed why it is difficult to automate visual element testing, and how Storybook provides an attractive alternative. True, there are numerous ways to test front-end codes, and information presented in this document may not always head in the right direction. This article is merely my attempt at discovering, alongside you, realistic and efficient testing methods.
In Part 2, I will actually use Storybook to conduct more detailed visual element tests and discuss more in depth strategies.
(“Application State Management” will be handled in Part 3 along with Cypress) | https://ui.toast.com/posts/en_20190405/ | CC-MAIN-2022-40 | refinedweb | 4,134 | 50.46 |
In today’s Programming Praxis exercise, our goal is to write a function to calculate partition numbers and to determine the 1000th partition number. Let’s get started, shall we?
Since the recursion in the algorithm is not as simple as in for example the Fibonacci numbers a simple zip will not suffice. To store previous results, we use an IntMap.
import Data.IntMap ((!), fromList, insert, findWithDefault)
Since we’re guaranteed to need every partition number below the one we’re looking for, we simply calculate all of them, starting from 1. This is done by folding over the numbers 1 through x with the IntMap as the accumulator.
partition :: Int -> Integer partition x = if x < 0 then 0 else foldl p (fromList [(0,1)]) [1..x] ! x where p s n = insert n (sum [(-1)^(k+1) * (r pred + r succ) | k <- [1..n], let r f = findWithDefault 0 (n - div (k * f (3 * k)) 2) s]) s
Let’s see if we did everything correctly.
main :: IO () main = print $ partition 1000 == 24061467864032622473692149727991
Yup. After compiling it runs in about 0.4 seconds on my machine.
Tags: bonsai, code, Haskell, intmap, kata, numbers, partition, praxis, programming | https://bonsaicode.wordpress.com/2011/04/15/programming-praxis-partition-numbers/ | CC-MAIN-2017-30 | refinedweb | 197 | 65.52 |
Gestalt.
View the full docs or Check out the Gestalt playground
Install
npm i gestalt --save or
yarn add gestalt
Usage
Gestalt exports each component as ES6 modules and a single, precompiled CSS file:
import { Text } from 'gestalt'; import 'gestalt/dist/gestalt.css';
That syntax is Webpack specific (and will work with Create React App), but you can use Gestalt anywhere that supports ES6 module bundling and global CSS.
Development
Gestalt is a multi-project monorepo. The docs, components and integration tests are all organized as separate packages that share similar tooling.
Install project dependencies and run tests:
yarn yarn test
Build and watch Gestalt & run the docs server:
yarn start
Visit and click on a component to view the docs.
Using the Masonry playground:
cd test && yarn start open ""
Running Masonry's integration tests. This will leave lots of Firefox processes hanging around, so please be warned.
./run_integration_tests
Codemods
When a release will cause breaking changes — in usage or in typing — we provide a codemod to ease the upgrade process. Codemods are organized by release in
/packages/gestalt-codemods. We recommend using jscodeshift to upgrade.
Prerequisite:
Install
jscodeshift globally if you haven't already.
yarn global add jscodeshift
Usage:
Clone the Gestalt repo locally if you haven't already. Run the relevant codemod(s) in the relevant directory of your repo (not the Gestalt repo): anywhere the component to be updated is used. Example usage for a codebase using Flow:
jscodeshift --parser=flow -t={relative/path/to/codemod} relative/path/to/your/code
For a dry run to see what the changes will be, add the
-d (dry run) and
-p (print output) flags (pipe stdout to a file for easier inspection if you like).
Releasing
If you haven’t already, you’ll first need to create an npm account. Once you've done that
you can setup your username and email in Yarn using
yarn login.
The following outlines our release process:
- Bump package version in
packages/gestalt/package.json& update
CHANGELOG.md.
- Open a pull request with the new version and land that in master.
- Once the version is bumped in master, checkout that commit locally.
- Run
npm loginusing your npm username and password.
- Run the release script from the root directory of the project
./scripts/publish.jsto publish the tag, npm package, and docs.
- Draft a new release from the tag at.
Typescript Support
Install the DefinitelyTyped definitions.
Install
npm i --save @types/gestalt
or
yarn add @types/gestalt | https://nicedoc.io/pinterest/gestalt | CC-MAIN-2019-35 | refinedweb | 413 | 65.01 |
Hosting Flask and Node WebApp for free - Heroku Alternative
Heroku is a great platform unless your web app becomes big or if you don’t want to get into the hassle of environment and workers setup. (Altho it’s quite not a big deal)
So, some of you may surely be thinking about any “free” alternative to Heroku!
Here, I will tell you about one site which is free and provides a lot of features to make your web app online in few minutes or less.
Deta.sh
Hold up! Don’t see the Pricing tab (as it's free forever!)
Deta was developed by developers for developers, students, hackathon participants, etc.
The parent company is based in Berlin, Germany.
Let’s come to its feature part.
Features
Deta Micros
So the first feature is “Deta Micros”.
Deta Micros are like small instances where you can host your nodejs web app or any other python web app
Deta Base
And Second “Deta Base”.
The name is quite enough to explain itself.
Deta Drive
Again as the name says, it’s for hosting images and files on their server which you can, later on, integrate into your web app.
Cons
So, now after discussing all this you may be thinking about the cons.
Altho the site provides everything for free and is quite good for newcomers to web development but it lacks more advanced settings and features. And Django web app is still not directly supported.
But cmmon this site is meant for those who want easiness right?
Let’s come to the interesting part! Hosting a web app.
Hosting Your Web App
Here, we will install a flask webapp.
Step 1. Make an account on deta.sh
So, the first and the foremost. Make an account on deta.sh.
Step 2. Setting up their client.
After signup, you will arrive at a handy dandy portal with few starter tips.
Click on Deta Micros (if you aren’t already there). Click on Windows(or Mac/Linux if you are on those systems) and copy the command.
Open your terminal as stated there like in the case of windows open Powershell.
Paste the command there and wait for some moment to let it download the client and install it.
Step 3. CLI Login
In the same terminal type
deta login
It will pop up a browser window where you need to login into your deta.sh account.
Step 4. Creating WebApp
Choose where you want to keep your code files.
Switch to that directory and open VScode there (VScode ❤️).
In the terminal in VSCode type
deta new --python myApp
(Change myApp to anything you want)
Step 5. requirements.txt
cd into the directory or manually create a requirements.txt inside the myApp folder.
Paste all the requirements which we will need.
Like
flask
Altho you can add anything but we are building a Flask app, right?
Step 6. Coding
Cmmon this you can do on your own. Add your code in main.py file.
Here’s a small snippet of “Hello World” (enjoy 🍻)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
Step 7. Deploying
deta deploy
then
deta auth disable
(This will make it public)
and then go to the site
If you forget the site details just type
deta details
Kudos! 🎉 Your Flask server is online!
Note: Currently there is no direct way to host a Django WebApp on Deta. Altho there is some workaround but still I don't recommend hosting Django Webapp on Deta.
Thanks for reading patiently and coming to this part! Feel Free to add a comment!
If you liked the post add a 👏 to keep me motivated!
Github: | https://aps09.medium.com/hosting-flask-and-node-webapp-for-free-heroku-alternative-75671cdedc05?source=post_internal_links---------4---------------------------- | CC-MAIN-2021-43 | refinedweb | 620 | 75.81 |
Hi Jeff,
1. points 7 and 8, when initSharedMem returns error, I call
freeSharedMem which should free any partially alloced memory.
2. For point 17 and 33
We do support IPV6 checksum offload. There is one issue though,
our hardware only says whether the checksum is Ok or not it does
not actually return the checksum values!
The value I put into skb->csum is a dummy value and hence set
ip_summed as UNNECESSARY in Rx path if checksums are reported OK..
Regards
Koushik
-----Original Message-----
From: Jeff Garzik [mailto:jgarzik@xxxxxxxxx]
Sent: Tuesday, February 17, 2004 5:59 AM
To: Leonid Grossman
Cc: netdev@xxxxxxxxxxx; raghavendra.koushik@xxxxxxxx; 'ravinandan arakali'
Subject: Re: Submission for S2io 10GbE driver
1) use ULL suffix on u64 constants.
static u64 round_robin_reg0 = 0x0001020304000105;
static u64 round_robin_reg1 = 0x0200030106000204;
static u64 round_robin_reg2 = 0x0103000502010007;
static u64 round_robin_reg3 = 0x0304010002060500;
static u64 round_robin_reg4 = 0x0103020400000000;
2) you'll want to (unfortunately) add #ifdefs around the PCI_xxx_ID
constants, because a full submission to the kernel includes a patch to
include/linux/pci_ids.h.
/* VENDOR and DEVICE ID of XENA. */
#define PCI_VENDOR_ID_S2IO 0x17D5
#define PCI_DEVICE_ID_S2IO_WIN 0x5731
#define PCI_DEVICE_ID_S2IO_UNI 0x5831
3) AS_A_MODULE is incorrect.
/* Load driver as a module */
#define AS_A_MODULE
First, it is defined unconditionally. Second, it should not even exist.
The kernel module API is intentionally designed such that the source
code functions whether a kernel module or built into vmlinux, without
#ifdefs. So, simply remove the ifdefs.
As a general rule, Linux kernel source code tries to be as free of
ifdefs as possible.
4) You will of course need to change CONFIGURE_ETHTOOL_SUPPORT,
CONFIGURE_NAPI_SUPPORT to Kconfig-generate CONFIG_xxx defines, when
submitting.
5) again, follow the kernel's no-ifdef philosophy:
#ifdef KERN_26
static irqreturn_t s2io_isr(int irq, void *dev_id, struct pt_regs *regs); #else
void s2io_isr(int irq, void *dev_id, struct pt_regs *regs); #endif /** KERN_26
**/
The "irqreturn_t" type was designed specifically to work without #ifdefs
in earlier kernels. Here is the proper compatibility code, taken from
release kernel 2.4.25's include/linux/interrupt.h:
/* For 2.6.x compatibility */
typedef void irqreturn_t;
#define IRQ_NONE
#define IRQ_HANDLED
#define IRQ_RETVAL(x)
I hope you notice a key philosophy emerging ;-) You want to write a
no-ifdef driver for 2.6, and then use the C pre-processor, typedefs, and
other tricks to make the driver work on earlier kernels with as little
modification as possible.
Look at module "kcompat" for an example
of a toolkit which allows you to write a current driver, and then use it
on older kernels.
6) delete, not needed
#ifdef UNDEFINED
suspend:NULL,
resume:NULL,
#endif
7) memory leak on error
/* Allocating all the Rx blocks */
for (j = 0; j < blk_cnt; j++) {
size = (MAX_RXDS_PER_BLOCK + 1) * (sizeof(RxD_t));
tmp_v_addr = pci_alloc_consistent(nic->pdev, size,
&tmp_p_addr);
if (tmp_v_addr == NULL) {
return -ENOMEM;
}
memset(tmp_v_addr, 0, size);
8) memory leak on error
/* Allocation and initialization of Statistics block */
size = sizeof(StatInfo_t);
mac_control->stats_mem = pci_alloc_consistent
(nic->pdev, size, &mac_control->stats_mem_phy);
if (!mac_control->stats_mem) {
return -ENOMEM;
}
9) if you store a pointer for your shared memory, it is wasteful to
store an -additional- flag indicating this memory has been allocated.
simply check for NULL.
if (nic->_fResource & TXD_ALLOCED) {
nic->_fResource &= ~TXD_ALLOCED;
pci_free_consistent(nic->pdev,
mac_control->txd_list_mem_sz,
10) ULL suffix
write64(&bar0->swapper_ctrl, 0xffffffffffffffff);
val64 = (SWAPPER_CTRL_PIF_R_FE |
11) ditto this for other 64-bit constants
12) never mdelay() for this long. Either create a timer, or make sure
you're in process constant and sleep via schedule_timeout().
/* Remove XGXS from reset state*/
val64 = 0;
write64(&bar0->sw_reset, val64);
mdelay(500);
13) memory writes without memory reads following them are often the
victims of PCI write posting bugs. At the very least, this driver
appears to have many PCI write posting issues.
write64(&bar0->dtx_control, 0x8000051500000000);
udelay(50);
write64(&bar0->dtx_control, 0x80000515000000E0);
udelay(50);
write64(&bar0->dtx_control, 0x80000515D93500E4);
udelay(50);
write64(&bar0->dtx_control, 0x8001051500000000);
udelay(50);
write64(&bar0->dtx_control, 0x80010515000000E0);
udelay(50);
write64(&bar0->dtx_control, 0x80010515001E00E4);
udelay(50);
You are not guaranteed that the write will have completed, by the end of
each udelay(), unless you first issue a PCI read of some sort.
14) another mdelay(500) loop to be fixed
/* Wait for the operation to complete */
time = 0;
while (TRUE) {
val64 = read64(&bar0->rti_command_mem);
if (!(val64 & TTI_CMD_MEM_STROBE_NEW_CMD)) {
break;
}
if (time > 50) {
DBG_PRINT(ERR_DBG, "%s: RTI init Failed\n",
dev->name);
return -1;
}
time++;
mdelay(10);
15) you obviously mean TASK_UNINTERRUPTIBLE here:
/* Enabling MC-RLDRAM */
val64 = read64(&bar0->mc_rldram_mrs);
val64 |= MC_RLDRAM_QUEUE_SIZE_ENABLE | MC_RLDRAM_MRS_ENABLE;
write64(&bar0->mc_rldram_mrs, val64);
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(HZ / 10);
16) get this from struct pci_dev, not directly from the PCI bus:
/* SXE-002: Initialize link and activity LED */
ret =
pci_read_config_word(nic->pdev, PCI_SUBSYSTEM_ID,
(u16 *) & subid);
17) question: do you not support more advanced checksum offload? like
ipv6 or "hey I put the packet checksum <here>"
18) waitForCmdComplete can mdelay() an unacceptably long time
19) ditto s2io_reset.
20) your driver has its spinlocks backwards! Your interrupt handler
uses spin_lock_irqsave(), and your non-interrupt handling code uses
spin_lock(). That's backwards from correct.
21) s2io_close could mdelay() for unacceptably long time. Fortunately,
you -can- sleep here, so just replace with schedule_timeout() calls.
22) remove the commented-out MOD_{INC,DEC}_USE_COUNT.
23) your tx_lock spinlock is completely unused. oops. :) the spinlock
covers two areas of code, both of which are mutually exclusive.
Given this and #20... you might want to make sure to build and test on
SMP. Even SMP kernels on uniprocessor hardware helps find spinlock
deadlocks.
24) your tx_lock does not cover the interrupt handler code. I presume
this is an oversight?
25) delete s2io_set_mac_addr. It's not needed. It is preferred to use
the default eth_mac_addr. Follow this procedure, usually:
a) During probe, obtain MAC address from "original source",
usually EEPROM / SROM.
b) Each time dev->open() is called, write MAC address to h/w.
26) check and make sure you initialize your link to off
(netif_carrier_off(dev)), in your dev->open() function. In the
background, your phy state machine should call netif_carrier_on() once
it is certain link has been established.
this _must_ be an asynchronous process. You may not sleep and wait for
link, in dev->open().
27) for current 2.4 and 2.6 kernels, please use struct ethtool_ops
rather than a large C switch statement.
28) are you aware that all of s2io_tx_watchdog is inside the
dev->tx_lock spinlock? I am concern s2io_tx_watchdog execution time may
be quite excessive a duration to hold a spinlock.
29) never call netif_wake_queue() unconditionally. only call it if you
are 100% certain that the net stack is allowed to add another packet to
your hardware's TX queue(s).
30) do not call netif_stop_queue() and netif_wake_queue() on link
events, in s2io_link. Simply call netif_carrier_{on,off}.
31) ULL suffix
} else if (!pci_set_dma_mask(pdev, 0xffffffff)) {
32) missing call to pci_disable_device() on error:
if (pci_set_consistent_dma_mask
(pdev, 0xffffffffffffffffULL)) {
DBG_PRINT(ERR_DBG,
"Unable to obtain 64bit DMA for \
consistent allocations\n");
return -ENOMEM;
33) if you use CHECKSUM_UNNECESSARY, you should be using the
less-capable NETIF_F_IP_CSUM.
dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM;
NETIF_F_HW_CSUM requires the actual checksum value. | http://oss.sgi.com/archives/netdev/2004-02/msg00460.html | CC-MAIN-2016-40 | refinedweb | 1,168 | 55.44 |
Posted 07 Apr 2015
Link to this post
We've added the RadMap control to our WPF application. I have a custom tile provider that interfaces with a home-grown tile service. Tee provider basically makes HTTP calls to a custom URL in order to retrieve tiles. This provider does no caching of its own.
However, a tester here had map data for the US only, then uninstalled that map data and installed map data for Peru. When they went back into our application, they were able to see roads on Long Island, which they shouldn't have seen. For this reason, we believe that the RadMap control itself is caching tiles.
Does RadMap cache tiles? If so, where is this cache and how can we empty it?
Here is the code for the custom tile provider. As you can see, there's no code for caching in here at all.
public class SelexTileSource : TiledMapSource {
public string BaseURL { get; set; }
public SelexTileSource() : base( 1, 20, 256, 256 ) { }
public override void Initialize() {
this.RaiseIntializeCompleted();
}
protected override Uri GetTile( int tileLevel, int tilePositionX, int tilePositionY ) {
int zoomLevel = ConvertTileToZoomLevel( tileLevel );
string url = string.Format( BaseURL,
zoomLevel.ToString( CultureInfo.InvariantCulture ),
tilePositionX.ToString( CultureInfo.InvariantCulture ),
tilePositionY.ToString( CultureInfo.InvariantCulture ) );
return new Uri( url );
}
public class SelexMapProvider : TiledProvider {
public TiledMapSource Source {
get { return iSource; }
set {
if ( iSource != null && MapSources.ContainsKey( iSource.UniqueId ) )
MapSources.Remove( iSource.UniqueId );
iSource = value;
MapSources.Add( iSource.UniqueId, iSource );
private TiledMapSource iSource;
public override ISpatialReference SpatialReference {
get { return new MercatorProjection(); }
Posted 09 Apr 2015
in reply to
Tony
Link to this post
I've found the answer to my own question.
If you do not set the MapProvider's IsTileCachingEnabled to true, tiles are not cached at all. If you do set it to true, tiles get cached in
%USERPROFILE%\AppData\Local\TelerikMapCache\<Map Provider Class Name>
So in my case, they're cached in C:\Users\tony.vitabile\AppData\Local\TelerikMapCache\SelexMapProvider.
Posted 10 Apr 2015
Link to this post
See What's Next in App Development. Register for TelerikNEXT.
Posted 04 Oct
in reply to
Petar Marchev
Link to this post
I noticed that even if I disable caching on the tile provider and then disconnect from the network, some tile data would still be displayed. It seems that map data is also stored in the Internet Explorer browser cache - is that correct?
Thanks
Pete | http://www.telerik.com/forums/where-does-radmap-cache-tiles | CC-MAIN-2016-50 | refinedweb | 395 | 55.54 |
C# Comments
When writing code, you might want to add some text that will serve as a reminder or a note for you or for anyone who will read your code. In C# (and most programming languages), you can do that using comments. Comments add documentation or notes to anyone who will read your code including yourself. Comments are ignored by the compiler and are not part of the actual C# code. Suppose you want to describe what a particular code is going to do, then you can place a comment above or beside it. Here is an example of a program with a c# comments:
namespace CommentsDemo { class Program { public static void Main(string[] args) { // This line will print the message hello world System.Console.WriteLine("Hello World!"); } } }
Line 7 shows an example of a single line comment. There are two types of comments, single line comments and multiline comments as presented below:
// single line comment /* multi line comment */
Single line comments, as the name implies, are used for commenting a single line of code. A single line comment starts with // and everything after // will be part of the comment. Single line comments are often placed above or to the right of a single line of code. These comments are ideal for describing the functionality for a single line of code.
If your comment is longer and requires multiple lines, use the multiline comment. A multiline comment starts with /* and ends with */. Everything between /* and */ will be considered as comments. This type of comment is useful for adding details about the program at the source code’s header or any long comments that spans multiple lines.
There is another type of comment which is called XML comment. It is represented by three slashes (///). It typically functions as a single line comment but it is commonlly used for creating documenation for your code. You will learn more about XML comment and how to use it in a separate lesson. | https://compitionpoint.com/csharp-comments/ | CC-MAIN-2021-31 | refinedweb | 329 | 71.04 |
I can successfully access one of our local samba shares, which is on a windows pc (called marina) as follows:
$ sudo /usr/bin/smbclient \\\\marina\\resource_library <my password>
Domain=[MARINA] OS=[Windows 5.1] Server=[Windows 2000 LAN Manager]
smb: \>
So, that works. I'm now trying to mount the above location (the resource_library folder on marina) to /mnt/resource_library (as a read only folder), but it keeps failing - i've tried a few variations of specifying the location:
$ sudo smbmount \\\\marina\\resource_library /mnt/resource_library -o username=max,password=<my password>,r
mount error: could not resolve address for marina: No address associated with hostname
No ip address specified and hostname not found
and
$ sudo smbmount //marina/resource_library /mnt/resource_library -o username=max,password=<my password>,r
mount error: could not resolve address for marina: No address associated with hostname
No ip address specified and hostname not found
and both of the above with MARINA instead of marina. It's bound to be some dumb mistake i'm making, can anyone see it?
cheers, max
This question came from our site for professional and enthusiast programmers.
sudo
smbclient
smbmount
//servername/sharename
I've found a non-workaround solution that worked for me, on debian (found it originally in some ubuntu forum, but this config file exists even in fedora, so I guess it's probably universal). I had to add "wins" on the /etc/nsswitch.conf file (and have "wins" installed). The line is now as follows:
hosts: files mdns4_minimal [NOTFOUND=return] dns wins mdns4
Actually i found an answer, i'm not sure if it will work for everyone though. I'll put it up here in case anyone browses to the page. Basically i just needed to provide the ip address with the smbmount command, which i got with
$ nmblookup marina
querying marina on 192.168.0.255
192.168.0.15 marina<00>
Now, as it happens my life is easier here as 192.168.0.15 has been assigned to the associated mac address as a fixed network ip, so it will never change. So now i can just do
$sudo smbmount //marina/resource_library /mnt/resource_library -o ip=192.168.0.15,username=max,password=<my password>,r
and it's sorted. If i was dealing with a randomly assigned ip for this smb share then i'm not sure what i'd do but it's not an issue here fortunately. :/
Try the command nmblookup marina. It queries the NetBIOS namespace (not DNS) and should return marina's IP address.
nmblookup marina
If it works, and you are sure that the IP address is static, you can use this address in your smbmount.
If it works, and you have DHCP addresses changing from time to time, try this command:
nmblookup marina \
| grep -vi querying \
| grep marina \
| awk '{print $1}' \
| uniq
It should return the IP address. If it works, you can change your command
You could do
sudo smbmount //marina/resource_library \
/mnt/resource_library \
-o ip=$(nmblookup marina \
| grep -vi querying \
| grep marina \
| awk '{print $1}' \
| uniq),username=max,password=foobar,r
Of course, this is a long command to remember. But then, you could define an 'alias' named mntmarina in your .bashrc, and you only have to type mntmarina...
mntmarina
.bashrc
Substituting my IP address for hostname worked for me. My share is called 'schnack'.
sudo smbmount //192.168.0.103/schnack ~/pipmnt
By posting your answer, you agree to the privacy policy and terms of service.
asked
5 years ago
viewed
3043 times
active
4 years ago | http://superuser.com/questions/174535/why-isnt-this-smbmount-attempt-working | CC-MAIN-2016-18 | refinedweb | 593 | 52.6 |
Cubes workspace configuration is stored in a .ini file with sections:
Note
The configuration has changed. Since Cubes supports multiple data stores, their type (backend) is specifien in the store configuration as type property, for example type=sql.
Simple configuration might look like this:
[workspace] model: model.json [store] type: sql url: postgresql://localhost/database
log - path to a log file
warn, info, debug
If not specified otherwise, all cubes share the same default namespace. There names within namespace should be unique. For simplicity and for backward compatibility reasons there are two cube lookup methods: recursive and exact. recursive method looks for cube name in the global namespace first then traverses all namespaces and returns the first cube found. exact requires exact cube name with namespace included as well. The option that affects this behavior is: lookup_method which can be exact or recursive.
The info JSON file might contain:
Section [models] contains list of models. The property names are model identifiers within the configuration (see [translations] for example) and the values are paths to model files.
Example:
[models] main: model.json mixpanel: mixpanel.json
If root models_directory is specified in [workspace] then the relative model paths are combined with the root. Example:
[workspace] models_directory: /dwh/cubes/models [models] main: model.json events: events.json
The models are loaded from /dwh/cubes/models/model.json and /dwh/cubes/models/events.json.
Note
If the root_directory is set, then the models_directory is relative to the root_directory. For example if the workspace root is /var/lib/cubes and models_directory is models then the search path for models will be /var/lib/cubes/models. If the models_directory is absolute, for example /cubes/models then the absolute path will be used regardless of the workspace root directory settings.
allow_cors_origin – Cross-origin resource sharing header. Other related headers are added as well, if this option is present.
authentication – authentication method (see below for more information)
pid_file – path to a file where PID of the running server will be written. If not provided, no PID file is created.
There might be one or more store configured. The section [store] of the cubes.ini file describes the default store. Multiple stores are configured in a separate stores.ini file. The path to the stores configuration file might be specified in a variable stores of the [workspace] section
Properties of the datastore:
Example SQL store:
[store] type: sql url: postgresql://localhost/data schema: cubes
For more information and configuration options see SQL Backend.
Example mixpanel store:
[store] type: mixpanel model: mixpanel.json api_key: 123456abcd api_secret: 12345abcd
Multiple Slicer stores:
[store slicer1] type: slicer url: [store slicer2] type: slicer url:
The cubes will be named slicer1.* and slicer2.*. To use specific namespace, different from the store name:
[store slicer3] type: slicer namespace: external url:
Cubes will be named external.*
To specify default namespace:
[store slicer4] type: slicer namespace: default. url:
Cubes will be named without namespace prefix.
Example configuration file:
[workspace] model: ~/models/contracts_model.json [server] reload: yes log: /var/log/cubes.log log_level: info [store] type: sql url: postgresql://localhost/data schema: cubes
Logging handlers for server requests have sections with name prefix query_log. All sections with this prefix (including section named as the prefix) are collected and chained into a list of logging handlers. Required option is type. You might have multiple handlers of the same time.
Logging types:
CSV request logger options:
SQL request logger options:
Tables are created automatically.
Simple configuration:
[workspace] model = model.json [store] type = sql url = postgresql://localhost/cubes
Multiple models, one store:
[models] finance = finance.cubesmodel customer = customer.cubesmodel [store] type = sql url = postgresql://localhost/cubes
Multiple stores:
[store finance] type = sql url = postgresql://localhost/finance model = finance.cubesmodel [store customer] type = sql url = postgresql://otherhost/customer model = customer.cubesmodel | http://pythonhosted.org/cubes/configuration.html | CC-MAIN-2018-05 | refinedweb | 628 | 50.84 |
How to load a custom QQuickItem from inside a library so that it gets registered & updated like other QQuickItems in the application
I have a
MyQuickItemclass derived from
QQuickItemas below
// MyQuickItem.hpp class MyQuickItem : public QQuickItem { Q_OBJECT public: MyQuickItem(); virtual ~ MyQuickItem(); protected: QSGNode* updatePaintNode(QSGNode *, UpdatePaintNodeData *) override; };
Following is
MyQuickItem.qml.
import QtQuick 2.0 import MyQuickItem 1.0 Item { MyQuickItem { id: my_quick_item objectName: "MyQuickItemObject" visible: false } }
Point to be noted is that all of above in a separate static library. And the library has a
qrcwhich has
MyQuickItem.qmlin it. This library has access to the global
QQmlApplicationEngineobject of the app as well.
My question: How can I load
MyQuickItemfrom inside my library so that it gets registered with QML like the other
QQuickItems in app's
main.qml?
I am trying something around the following way from inside my library in a C++ method called after main.qml is loaded by the application:
MyQuickItem * myItem = new MyQuickItem(); myItem->setParent(m_qml_engine->parent()); myItem->setParentItem(qobject_cast<QQuickItem*>(m_qml_engine->parent())); QQmlEngine::setObjectOwnership(myItem, QQmlEngine::JavaScriptOwnership); myItem->setHeight(500); // But myItem is NULL here !!! myItem->setHeight(500); // But myItem is NULL here !!!
Firstly, I don't know how to link
QUrl(QStringLiteral("qrc:/qml/MyQuickItem.qml"))to
myItempointer.
Secondly, doing the above does not seem to load
MyQuickItemcorrectly as I don't get a call to
updatePaintNodewhich I have overridden. I need the
Qt/QMLwindow system to call my
MyQuickItem ::updatePaintNodeas I have important logic there.
So, How can I correctly load
MyQuickItemfrom inside my library so that it gets registered & updated like other
QQuickItems?
Hi,
just a wild guess since I am a noob. Have you tried to include the header file from your lib in your main.cpp? If not try that and look up qmlRegisterType.
@Sikarjan I tried including
MyLibrary/MyQuickItem.hpp/ do a
qmlRegisterType<MyQuickItem>("MyQuickItem", 1, 0, "MyQuickItem"). But that does not help. I think this only works if I was doing an
import MyQuickItem 1.0to embed
MyQuickIteminto the Application's
main.qmlor any of its child. Here
MyQuickItem.qmlis inside a library. So struggling to make it visible under the application's qml tree
- SGaist Lifetime Qt Champion
Hi and welcome to devnet,
Did you already saw the QML Modules chapter in Qt's documentation ?
@SGaist I saw this example. but that one is not deriving the class from a
QQuickItem. In my case everything is working if I define
MyQuickItemin
main.qml& call
qmlRegisterTypefrom main.cpp. All I want to do is, move the
MyQuickIteminto its own
MyQuickItem.qmlinside my library without the app defining it. The goal is that the app should get
MyQuickItemfrom the library.
Isn't this possible without going into the QML module technique?
By the way, I can create a
QQuickitemin the following way.
QQuickItem * dynamic_quick_item = new QQuickItem(); dynamic_quick_item->setObjectName("DynamicQuickItemObject"); dynamic_quick_item->setHeight(500); dynamic_quick_item->setWidth(500);
I also have access to qml_engine & everything in
main.cpp.
But my problem is that : How can I add this
dynamic_quick_itemto the children list of qml objects?
- SGaist Lifetime Qt Champion
Then isn't the Creating C++ Plugins for QML chapter what you are looking for ?
- Roby Brundle | https://forum.qt.io/topic/82606/how-to-load-a-custom-qquickitem-from-inside-a-library-so-that-it-gets-registered-updated-like-other-qquickitems-in-the-application | CC-MAIN-2017-39 | refinedweb | 526 | 50.43 |
Introduction to Graphs and Charts
Introduction to Graphs and Charts
Why Charts and Graphs?
Graphs... difficult and tedious process.
All forms of Graphs and Charts embodies some Visual
graphs/charts - JSP-Servlet
graphs/charts hi frens,
How to create a bar graph by reading values from mysql database. Please help me out... Hi Friend,
We have...:
Here
Chart & Graphs Tutorials in Java
;
Best collection of Graphs and Charts Tutorials... to Charts & Graphs
Graphs and Charts is the most efficient method...;
Types of Charts
There are many types of graphs and charts
graphs/charts - JSP-Servlet
graphs/charts hi,
How to create a graph/chart in java by reading values from my sql database. Hi Friend,
Try the following code:
import java.sql.* ;
import java.io.* ;
import org.jfree.chart.ChartFactory
Good Looking Java Charts and Graphs
Good Looking Java Charts and Graphs Is there a java chart library that will generate charts and graphs with the quality of visifire or fusion charts?
The JFreeChart graph quality is not professional looking. Unless it can
Types of Graphs and Charts
Types of Graphs and Charts
... applications charts and graphs are extensively
used for visualizing the data.
In Java... the data and call the few methods to generate the charts or graphs
of your
Doubt regarding charts and jsp
Doubt regarding charts and jsp Hi,
I successfully executed... files in tomcat lib and project libraries. Restart the tomcat server and visit the following links:
maths
Graphs - Struts
implementation, I would suggest Google charts.
How to create charts in Java?
How to create charts in Java? Is there any example of creating charts and graphs in Java?
thanks
Hi,
check the tutorial: Chart & Graphs Tutorials in Java
Thanks
Drawing Graphs - Java3D
Drawing Graphs how to draw graphs using certain parameters Hi Friend,
To draw a graph using JfreeChart library, please visit the following link:
Here you
Doubt Regarding Charts
charts and graphs...Doubt Regarding Charts Hi,
Can you please help me out by answering "hoe to include charts in core java code and struts code"
thanks in advance
Doubt regarding charts and jsp
Doubt regarding charts and jsp Hi
in the of the code
(new StandardEntityCollection());
final File file1 = new File("../webapps/jspchart/web/barchart.png
Charts in JSP - JSP-Servlet
Charts in JSP Hi Roseindia team,
This is ragav.. I am currently in a project where i must display the database results in terms of charts in JSP.. So, Can i know the pre requirement for that? Do i need
Drawing Graphs - Swing AWT
Drawing Graphs hi i am doing a small project in java swings . there is a database table having two columns A,B i want to plot a graph to that values in database the graph must be interactive graph
Graphs using JFreeChart - Java Beginners
Graphs using JFreeChart Hi Friend,
I need to draw a graph of the powerconsumed by a consumer in specific dates with a const line showing the max... the following link:
Thanks
project
project hi , we r working on one project related to our results. we using java and for back end sqlserver 2005.
In dis we are trying to retrieve... one , we r also planning to do pi-charts or bar charts for this, can any body
gantt charts - Swing AWT
gantt charts Hello, i am doing project on project management tool there i need to generate a gantt chart for daily activity done by developer regarding how many hours they have spent for each activity. If the database contains
JFreeChart - An Introduction
JFreeChart - An Introduction
... library.
David Gilbert founded the JFreeChart project in February 2000. Now a days, it is
used
by around 40000 to 50000 developers. It is used to generate the charts
importing excel file and drawing multiple graphs from one excel file
importing excel file and drawing multiple graphs from one excel file thanks a lot sir for replying with code for importing excel file... I'll be highly thankful to you:)
I want to draw multiple charts at the same
flow charts
flow charts draw a flow chart program with a user prompt of 5 numbers computing the maximum, minimum and average
PHP Introduction
and takes less time to master.
PHP Introduction
The word PHP stands... to develop Object-oriented graphs.
Open Flash Chart
Use this to develop flash based charts.
MagpieRSS
Read and manipulate the RSS feeds in your
jree charts
jree charts i have to use jfree charts how to download its api and where to keep it in
jdk order to execute
Please visit the following link:
Download JFreechart
Download jfreechart-1.0.13.zip from the given link
graphs in jsp - Java3D
graphs in jsp i want to present my data from database in graphs how can i present in jsp and servlet.please guide me.thanz in advance
fusion charts
JSF Introduction - An Introduction to JSF Technology
JSF Introduction - An Introduction to
JSF Technology...
Introduction section introduces you with cool JSF technology. ... the reasons that initiated the JSF project and
why JSF is so hot these days
generate charts using JSP
generate charts using JSP any one know coding for generate bar chart or pie chart using JSP
java charts - Development process
java charts Hi,i want to create charts wrt database by using jsp?please help me
java bar charts and jsp
java bar charts and jsp Hi,
Can any one help me out in how to create java bar charts using jsp with the help of data base table values?
thanks in advance
Have a look at the given link:
Bar charts and jsp
Bar charts and jsp Hi,
How to generate Dynamic Bar Chart Images using jsp with placing any image location in weebroots?
Thanks in advance
java charts - JSP-Servlet
java charts Hi,can any one tell me how to create dyanamic charts wrt database contents by using jsp-servlet
Merge XYLine and XYArea Charts
Merge XYLine and XYArea Charts I wonder how to merge two charts... (this website) how to use two XYLine Charts and display them. Please, see screenshot... appreciate any help. Please, bear in mind I am new to charts plotting in java
Charts in JSP - JSP-Servlet
Charts in JSP Hi,
Thanks for replying for the chart query I made 2 days back.. Can u plz provide me an example for creating a series bar chart with the datas coming from the database? Series chart in the sense, If I have x
Introduction to Hibernate Framework
Hibernate Tutorial: an introduction to Hibernate
Framework, its features... based open source project for persisting the Java objects
(POJO's... the developers efficiency working on the project.
As mentioned above Hibernate
Introduction
Introduction
This Shopping Cart Application is written in Java and set up using Hibernate
and Struts. Hibernate and Struts are popular open source tools
Statistical charts in JSP - problem
Statistical charts in JSP - problem hey! i get this error when i run the code (with slight changes in query)!
HTTP Status 500 -
type Exception report
description The server encountered an internal error
Introduction
Applet
Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs
on the java enables web browsers such as mozila and internet explorer
gantt charts - Java Beginners
Multiline graphs in java - Java Beginners
Multiline graphs in java How to draw a multiline graph in java, One will b constant straight line and the other is changing Hi Friend,
Try the following code:
import java.awt.*;
import org.jfree.ui.*;
import
Introduction to Generics in Java
Introduction to Generics in Java: What are the benefits of using Generics in
Java?
The Generics Features was added to the Java with the release of Java 5.0.... development project bugs are get introduced due to human
error or simply missing
java project - Java Beginners
java project HAVE START A J2ME PROJECT WITH NO CLEAR IDEA .. ANY ONE... proposal & Requriment is given below
PROPSAL:::
INTRODUCTION
Our project titled, as ?M-News Application? is basically a mobile news application
Introduction to Apache Myfaces and Tomahawk
Introduction to Apache Myfaces and Tomahawk
... among JSF
developers. Apache MyFaces is an Apache Software Foundation's
project... is a sub-project of Apache that is a set of JSF components.
These components
project
project suggest a network security project based on core java with explanation
PROJECT
PROJECT i want online polling system project codding
project
project i need a project in java backend sql
Outsourcing Definition,Introduction to Outsourcing,Define Outsourcing
Outsourcing Defined
Introduction
Despite receiving a lot of attention in the last decade,
outsourcing is still a term many people... usual or more complicated project at hand
Introduction to DbUnit
Introduction to DbUnit
DbUnit is an open source Framework created
by Manuel Laflamme. This is a powerful tool for simplifying Unit Testing
Introduction to ANT
Introduction to ANT
... developing the java software.
To understand more clearly, Let?s view a project development scenario without the ant tool where you need to work on a large Java project
Project
=(String) vdata.get(1);
String project_name=(String) vdata.get(2);
String project
Introduction To Application
Introduction To Application
The present application is an online test application, which takes online
tests on programming languages. In this application you will learn a lot of
thing of Struts2, such as session management, chaining
project
in project
Project
j2me project guide - Java Beginners
:::
INTRODUCTION
Our project titled, as ?M-News Application? is basically a mobile news application Project. In our project we are going to develop a Mobile Application...j2me project guide i HAVE START A J2ME PROJECT WITH NO CLEAR IDEA
Project Communications Management
Project communication is a two way process of exchange of information related to the project between the sender and the receiver with the emphasis... is very essential for the successful completion of the project, which is done
Introduction to XSLT
Introduction to XSLT
Extensible Stylesheet Language Transformations (XSLT) is an XML-based language... is the Apache XML Project's XSLT engine. This processor is available at http
javascript introduction for programmers
javascript introduction for programmers A brief Introduction of JavaScript(web scripting language) for Java Programmers
AN INTRODUCTION TO JSTL
on JSTL, the author gives a brief introduction to JSTL and
shows why and how...-Standard Tag Library (JSTL) project.
Though there are a number of popular... Community Project! Why?
This enables , clean separation of Page
Introduction to HTML
Introduction to HTML
...;This is another paragraph. This will give you<br>an introduction of HTML... paragraph.
This is another paragraph. This will give youan introduction of HTML
Introduction to Data Structures
, Stacks, Queues, Trees, and Graphs which are related with the data
structures
java with jsp and dynamic database retrival for bar charts
Introduction to Maven 2
Introduction to Maven 2
... to automate the project's build infrastructure since maven uses a standard
directory... of the heavy cost of every project setup.
Maven 2.0 was first released on 19
Introduction to Facelets
In this section, you will find the brief introduction of Facelets technology of JSF
Graph
Graph What is the code to generate the following graphs?
1.Simple Bar diagram
2.Sub-divided Bar diagram
3.Pie chart
Please Help!!!!
Please visit the following link:
Java charts and graphs
Ruby on Rails-Introduction
Ruby on Rails-Introduction
... of all start NetBeans IDE.
Create new project via File >> New Project
Select Ruby from Categories and select Ruby on
Rails Application from
Introduction to java arrays
Introduction to java arrays
In this section you will be introduced to the concept
of Arrays in Java Programming language. You will learn how the Array class
XML: An Introduction - Brief History
XML: An Introduction - Brief History
In the 1970?s, Charles Goldfarb, Ed Mosher... Bosak with his team began
work on a project for remoulding SGML | http://www.roseindia.net/tutorialhelp/comment/94725 | CC-MAIN-2015-11 | refinedweb | 1,963 | 61.06 |
This article was contributed by Havoc Pennington
Havoc Pennington is a developer at Typesafe, the Scala company. In the past he's worked on everything from web apps to Linux UI toolkits to JavaScript runtimes.
Scaling Out with Scala and Akka on Heroku
Table of Contents
This article is a guided tour of an application called Web Words illustrating the use of Scala and Akka on Heroku’s Cedar stack. Web Words goes beyond “Hello, World” to show you a sampler of the technology you might use in a real-world application:
- organizing a scalable application with Akka actors, rather than with explicit threads and
java.util.concurrent
- the power of functional programming and parallel collections in Scala
- dividing an application into separate web and worker processes, using RabbitMQ to send jobs to the worker
- caching worker results in a MongoDB capped collection
- embedding a Jetty HTTP server
- forwarding Jetty requests to Akka HTTP to handle them asynchronously without tying up a thread
- many small details along the way: using a Java library from Scala, using Akka actor pools, using Akka’s Future class, some cute Scala tricks, and more.
Because this sampler application shows so many ideas, you may want to skip around the article to the topics you’re most interested in.
Don’t forget, if the article skips a detail you’d like to know more about, you can also jump to the source code to see what’s what.
The README over on GitHub has instructions for running Web Words locally or on Heroku.
This article is not a ground-up tutorial on any of the technologies mentioned; the idea is to give you a taste. So don’t worry if some of the details remain unclear, just follow the links and dig deeper!
Sample code for the Web Words demo app is available on GitHub.
Web Words
The sample application, Web Words, takes a site URL and does a “shallow spider” (following just a few of the same-site links at the URL). It churns through the HTML on the site, calculating word frequencies and scraping links, then presents results:
Web Words includes both IO-bound and CPU-bound tasks, illustrating how Scala and Akka support both.
The application is split into a web process, which parses HTTP requests and
formats results in HTML, and a worker process called
indexer which does
the spidering and computes the results.
Overview: a request step-by-step
If you follow an incoming request to Web Words, here’s what the app shows you:
- an embedded Jetty HTTP server receives requests to spider sites
-
- requests are forwarded to Akka HTTP, which uses Jetty Continuations to keep requests from tying up threads
-
- the web process checks for previously-spidered info in a MongoDB capped collection which acts as a cache. This uses the Heroku MongoHQ addon.
-
-
- if the spider results are not cached, the web process sends a spider request to an indexer process using the RabbitMQ AMQP addon
-
- RabbitMQ add-on now available on Heroku
- the app talks to RabbitMQ using Akka AMQP
-
- the indexer process receives a request from AMQP and shallow-spiders the site using an Akka actor that encapsulates AsyncHttpClient
-
- the indexer uses Akka, Scala parallel collections, and JSoup to grind through the downloaded HTML taking advantage of multiple CPU cores
-
-
- the indexer stores its output back in the MongoDB cache and sends an AMQP message back to the web process
- the web process loads the now-cached data from MongoDB
- the web process unsuspends the Jetty request and writes out the results
Akka: actor and future
Almost all the code in Web Words runs inside Akka actors.
An actor is the fundamental unit of organization in an Akka application. The actor model comes from Erlang, where it’s said to support code with nine “9"s of uptime.
An actor is:
- an object
- that sends and receives messages
- that’s guaranteed to process only one message on one thread at a time
Because actors work with messages, rather than methods, they look like little network servers rather than regular objects. However, since they’re (often) in-process, actors are much lighter-weight than a separate server daemon would be. In fact, they’re much lighter-weight than threads. One JVM process could contain millions of actors, compared to thousands of threads.
Toy actor example
A trivial, toy example could look like:
import akka.actor._ class HelloActor extends Actor { override def receive = { case "Hello" => self reply "World" } }
This is an actor that receives a string object "Hello” as a message and sends back the string object “World” as a message.
There are only two steps to create an actor:
- extend the
Actorbase class
- override
receiveto handle your messages
The whole point of an
Actor is that
receive need not be thread-safe; it
will be called for one message at a time so there’s no need for locking on
your actor’s member variables, as long as you only touch the actor’s state
from inside
receive. (If you spawn your own threads and have those touch
the actor outside Akka’s control, you are on your own. Don’t do that.)
To use this actor, you could write:
import akka.actor._ import akka.actor.Actor.actorOf val actor = actorOf[HelloActor] actor.start val future = actor ? "Hello" println("Got: " + future.get) actor.stop
The method
Actor.actorOf creates an ActorRef, which is a
handle that lets you talk to an actor. The idea is to forbid you from
calling methods on the actor; you can only send messages. (Also: the
ActorRef may refer to an actor running on another machine, or due to actor
restarts may refer to different actor instances over time.)
Actor references have a
start method which registers the actor with the
Akka system and a
stop method which unregisters the actor.
The operator
? (also known as
ask) sends a message to an actor and
returns a
Future containing the reply to that message.
Future.get blocks
and waits for the future to be completed (a bad practice! we’ll see later
how to avoid it), returning the result contained in the
Future.
If you don’t need a
Future for the reply, you can use the
! operator
(also known as
tell) to send a message instead. If you use
! from within
another actor, the sending actor will still receive any reply message, but
it will be handled by the actor’s
receive method rather than sent to a
Future.
Real actors and futures in Web Words
Now let’s look at a real example.
URLFetcher actor
In URLFetcher.scala, an actor encapsulates
AsyncHttpClient. The actor supports only one message,
FetchURL, which asks it to download a URL:
sealed trait URLFetcherIncoming case class FetchURL(u: URL) extends URLFetcherIncoming
While messages can be any object, it’s highly recommended to use immutable objects (immutable means no “setters” or modifiable state). In Scala, a case class makes an ideal message.
The
URLFetcherIncoming trait is optional: it gives you a type shared by
all messages coming in to the actor. Because the trait is
sealed, the
compiler can warn you if a match expression doesn’t handle all message
types.
The
URLFetcher actor supports only one outgoing message, a reply to
FetchURL:
sealed trait URLFetcherOutgoing case class URLFetched(status: Int, headers: Map[String, String], body: String) extends URLFetcherOutgoing
The actor itself holds an
AsyncHttpClient object from the
AsyncHttpClient library and uses it to handle
FetchURL
messages, like this:
class URLFetcher extends Actor { private val asyncHttpClient = URLFetcher.makeClient override def receive = { case incoming: URLFetcherIncoming => { val f = incoming match { case FetchURL(u) => URLFetcher.fetchURL(asyncHttpClient, u) } self.channel.replyWith(f) } } override def postStop = { asyncHttpClient.close() } }
Of course the real work happens in
URLFetcher.fetchURL() which maps the
AsyncHttpClient API onto an Akka future. Check out
URLFetcher.scala to see that code.
postStop is a hook method actors can override to clean up when the actor
shuts down, in this case it closes the
AsyncHttpClient object.
Akka automatically sets up a
self field, referring to an actor’s own
ActorRef.
self.channel refers to the current message’s sender. A
Channel can
receive messages, and may be either a
Future or an
Actor.
replyWith is a utility method kept in the Web Words
common project. It’s
added to Akka’s
Channel using the so-called
“Pimp my Library” pattern, so its implementation
illustrates both that pattern and the use of
Future:
// Class that adds replyWith to Akka channels class EnhancedChannel[-T](underlying: Channel[T]) { /** * Replies to a channel with the result or exception from * the passed-in future */ def replyWith[A <: T](f: Future[A])(implicit sender: UntypedChannel) = { f.onComplete({ f => f.value.get match { case Left(t) => underlying.sendException(t) case Right(v) => underlying.tryTell(v) } }) } } // implicitly create an EnhancedChannel wrapper to add methods to the // channel implicit def enhanceChannel[T](channel: Channel[T]): EnhancedChannel[T] = { new EnhancedChannel(channel) }
The above code is in the
package.scala for the common project. In it, you
can see how to set up an
onComplete callback to be invoked when a
Future
is completed.
Important caution: a
Future will always invoke callbacks in another
thread! To avoid concurrency issues and stick to the actor model, use
callbacks only to send messages to actors, keeping the real work in an
actor’s
receive method.
SpiderActor
URLFetcher doesn’t do all that much; it’s a simple proxy giving the
AsyncHttpClient object an Akka-style API.
Let’s look at SpiderActor, which uses the
URLFetcher to shallow-spider a site.
Again this actor has one request and one reply to go with it:
sealed trait SpiderRequest case class Spider(url: URL) extends SpiderRequest sealed trait SpiderReply case class Spidered(url: URL, index: Index)
Given a site URL, the
SpiderActor computes an
Index (see
Index.scala) to go with it.
SpiderActor delegates to two other actors, one of which is the
URLFetcher:
class SpiderActor extends Actor { private val indexer = actorOf[IndexerActor] private val fetcher = actorOf[URLFetcher] override def preStart() = { indexer.start fetcher.start } override def postStop() = { indexer.stop fetcher.stop }
SpiderActor ties the two other actors to its own lifecycle by overriding
preStart and
postStop, ensuring that the entire “tree” of actors starts
and stops together.
Composing futures
SpiderActor offers a nice illustration of how to use
map and
flatMap
with
Future. First, in a
fetchBody method, we send a request to the
URLFetcher then use
map to convert the
URLFetched reply into a
simple string:
private def fetchBody(fetcher: ActorRef, url: URL): Future[String] = { val fetched = fetcher ? FetchURL(url) fetched map { case URLFetched(status, headers, body) if status == 200 => body case URLFetched(status, headers, body) => throw new Exception("Failed to fetch, status: " + status) case whatever => throw new IllegalStateException("Unexpected reply to url fetch: " + whatever) } }
This example does not block. The code after
map runs asynchronously,
after the
URLFetched reply arrives, and extracts the reply body as a
string. If something goes wrong and the exceptions here are thrown, the
returned
Future[String] would be completed with an exception instead of a
result.
Once a reply body comes back,
SpiderActor will want to index it (a task
performed by IndexerActor). Indexing is itself an
asynchronous operation. To “chain” two futures, use
flatMap.
Both
map and
flatMap return a new future. With
map, you provide a
function to convert the original future’s value, when available, into a new
value. With
flatMap, you provide a function to convert the original
future’s value, when available, into yet another future.
flatMap is useful
if you need to do something else asynchronous, once you have a value from
the original future.
This code from
SpiderActor uses both
map and
flatMap to chain the
Future[String] from
fetchBody (shown above) into a
Future[Index].
private def fetchIndex(indexer: ActorRef, fetcher: ActorRef, url: URL): Future[Index] = { fetchBody(fetcher, url) flatMap { body => val indexed = indexer ? IndexHtml(url, body) indexed map { result => result match { case IndexedHtml(index) => index } } } }
Nothing here is blocking, because the code never uses
Future.await or
Future.get. Instead,
map and
flatMap are used to transform
futures… in the future.
The nice thing about this is that
map and
flatMap are standard methods
as seen in Scala’s normal collections library, and as seen in Scala’s
Option class.
Future is like a one-element collection that automatically
keeps itself asynchronous as it’s transformed.
Other collection operations such as
filter and
foreach work on
Future,
too!
Actor pools
IndexerActor, used by SpiderActor, is an example of an actor pool. An actor pool is an actor that contains a pool of identical delegate actors. Pools can be configured to determine how they load-balance messages among delegates, and to control when they create and destroy delegates.
In Web Words, actor pools are set up in two abstract utility classes, CPUBoundActorPool and IOBoundActorPool. These pools have settings intended to make sense for delegates that compute something on the CPU or delegates that perform blocking IO, respectively.
Many of the settings defined in these utility classes were not arrived at scientifically; you’d need to run benchmarks are on your particular application and hardware to know the ideal settings for sure.
Let’s look at CPUBoundActorPool, then its subclass IndexerActor.
First, CPUBoundActorPool mixes in some traits to select desired policies:
trait CPUBoundActorPool extends DefaultActorPool with SmallestMailboxSelector with BoundedCapacityStrategy with MailboxPressureCapacitor with Filter with BasicRampup with BasicBackoff {
Reading from the top down, this actor pool will:
SmallestMailboxSelector: send each message to the delegate with the smallest mailbox (least message backlog)
BoundedCapacityStrategy: computes the number of delegates within an upper and a lower limit, based on a
pressureand a
filtermethod.
pressurereturns the number of “busy” delegates, while
filtercomputes a change in actual number of delegates based on the current number and the current pressure.
MailboxPressureCapacitor: provides a
pressuremethod which counts delegates as “busy” if they have a backlog of messages exceeding a certain threshold
Filter: provides a
filtermethod which delegates to
rampupand
backoffmethods. These compute proposed increases and decreases in capacity, respectively.
BasicRampup: implements the
rampupmethod to compute a percentage increase in delegates when pressure reaches current capacity.
BasicBackoff: implements the
backoffmethod to compute a percentage decrease in delegates when pressure falls below a threshold percentage of capacity.
CPUBoundActorPool configures its mixin traits by overriding methods:
// Selector: selectionCount is how many pool members to send each message to override def selectionCount = 1 // Selector: partialFill controls whether to pick less than selectionCount or // send the same message to duplicate delegates, when the pool is smaller // than selectionCount. Does not matter if lowerBound >= selectionCount. override def partialFill = true // BoundedCapacitor: create between lowerBound and upperBound delegates in the pool override val lowerBound = 1 override lazy val upperBound = Runtime.getRuntime().availableProcessors() * 2 // MailboxPressureCapacitor: pressure is number of delegates with >pressureThreshold messages queued override val pressureThreshold = 1 // BasicRampup: rampupRate is percentage increase in capacity when all delegates are busy override def rampupRate = 0.2 // BasicBackoff: backoffThreshold is the percentage-busy to drop below before // we reduce actor count override def backoffThreshold = 0.7 // BasicBackoff: backoffRate is the amount to back off when we are below backoffThreshold. // this one is intended to be less than 1.0-backoffThreshold so we keep some slack. override def backoffRate = 0.20
Each message will go to just one delegate. The pool will vary between 1 and (2x number of cores) delegates. We’ll ramp up by 20% if all delegates have a backlog of 1 already. We’ll back off by 20% if only 70% of delegates have a backlog of 1. Again, the exact settings are not scientific; you’d have to tune this in a real application.
To subclass CPUBoundActorPool,
IndexerActor has to implement just one more thing, a
method called
instance which generates a new delegate:
override def instance = Actor.actorOf(new Worker())
Actor pools have a method
_route which just forwards to a delegate, so
IndexerActor can implement
receive with that:
override def receive = _route
Optionally, an actor pool could look at the message and decide whether to
send it to
_route or do something else instead.
akka.conf
Akka has a configuration file
akka.conf, automatically loaded from the
classpath. Typically you might want to configure the size of Akka’s thread
pool and the length of Akka’s timeouts. See
the akka.conf for the web process for an example.
Scala
While this article is not an introduction to Scala, the Web Words example does show off some nice properties of Scala that deserve mention.
Working with Java libraries
If you had to rewrite all your Java code, you’d never be able to switch to Scala. Fortunately, you don’t.
For example, IndexerActor uses a Java library, called JSoup, to parse HTML.
In general, you import a Java library and then use it, like this:
import org.jsoup.Jsoup val doc = Jsoup.parse(docString, url.toExternalForm)
The most common “catch” is that Scala APIs use Scala’s collections library, while Java APIs use Java’s collections library. To solve that, Scala provides two options.
The first one adds explicit
asScala and
asJava methods to collections,
and can be found in
JavaConverters:
import scala.collection.JavaConverters._ val anchors = doc.select("a").asScala
The second option, not used in IndexerActor, adds
implicit conversions among Scala and Java collections so things “just work”;
the downside is, you can’t see by reading the code that there’s a conversion
going on. To get implicit conversions, import
scala.collection.JavaConversions._ rather than
JavaConverters.
The choice between explicit
asScala and
asJava methods, and implicit
conversions, is a matter of personal taste in most cases. There may be some
situations where an explicit conversion is required if the Scala compiler
can’t figure out which implicit to use.
The converters work efficiently by creating wrappers around the original collection, so in general should not add much overhead.
Functional programming
With CPUs getting more cores rather than higher clock speeds, functional programming becomes more relevant than ever. Akka’s actor model and Scala’s functional programming emphasis are two tools for developing multithreaded code without error-prone thread management and locking.
(What is it, anyway?)
You may be wondering what “functional programming” means, and why it’s important that Scala offers it.
Here’s a simple definition. Functional programming emphasizes transformation (take a value, return a new value) over mutable state (take a value, change the value in-place). Functional programming contrasts with imperative or procedural programming.
The word function here has the sense of a mathematics-style function. If
you think about f(x) in math, it maps a value
x to some result
f(x).
f(x) always represents the same value for a given
x. This “always the
same output for the same input” property also describes program subroutines
that don’t rely upon or modify any mutable state.
In addition to the core distinction between transformation and mutation,
“functional programming” tends to imply certain cultural traditions: for
example, a
map operation that transforms a list by applying a function to
each list element.
Functional programming isn’t really a language feature, it’s a pattern that can be applied in any language. For example, here’s how you could use add one to each element in a list in Java, by modifying the list in-place (treating the list as mutable state):
public static void addOneToAll(ArrayList<Integer> items) { for (int i = 0; i < items.size(); ++i) { items.set(i, items.get(i) + 1); } }
But you could also use a functional style in Java, transforming the list into a new list without modifying the original:
public static List<Integer> addOneToAll(List<Integer> items) { ArrayList<Integer> result = new ArrayList<Integer>(); for (int i : items) { result.add(i + 1); } return result; }
Unsurprisingly, you can use either style in Scala as well. Imperative style in Scala:
def addOneToAll(items : mutable.IndexedSeq[Int]) = { var i = 0 while (i < items.length) { items.update(i, items(i) + 1) i += 1 } }
Functional style in Scala:
def addOneToAll(items : Seq[Int]) = items map { _ + 1 }
You might notice that the “functional style in Scala” example is shorter than the other three approaches. Not an uncommon situation.
There are several advantages to functional programming:
- it’s inherently parallelizable and thread-safe
- it enables many optimizations, such as lazy evaluation
- it can make code more flexible and generic
- it can make code shorter
Let’s look at some examples in Web Words.
Collection transformation
In SpiderActor, there’s a long series of transformations to choose which links on a page to spider:
// pick a few links on the page to follow, preferring to "descend" private def childLinksToFollow(url: URL, index: Index): Seq[URL] = { val uri = removeFragment((url.toURI)) val siteRoot = copyURI(uri, path = Some(null)) val parentPath = new File(uri.getPath).getParent val parent = if (parentPath != null) copyURI(uri, path = Some(parentPath)) else siteRoot val sameSiteOnly = index.links map { kv => kv._2 } map { new URI(_) } map { removeFragment(_) } filter { _ != uri } filter { isBelow(siteRoot, _) } sortBy { pathDepth(_) } val siblingsOrChildren = sameSiteOnly filter { isBelow(parent, _) } val children = siblingsOrChildren filter { isBelow(uri, _) } // prefer children, if not enough then siblings, if not enough then same site val toFollow = (children ++ siblingsOrChildren ++ sameSiteOnly).distinct take 10 map { _.toURL } toFollow }
(The syntax
{ _ != uri } is a function with one parameter, represented by
_, that returns a boolean value.)
This illustrates some handy methods found in the Scala collections API.
maptransforms each element in a collection, returning a new collection of transformed elements. For example,
map { new URI(_) }in the above converts a list of strings to a list of
URIobjects.
filteruses a boolean test on each element, including only the elements matching the test in a new collection. For example,
filter { _ != uri }in the above includes only those URIs that aren’t the same as the original root URI.
sortBysorts a collection using a function on each element as the key, so to sort by path depth it’s
sortBy { pathDepth(_) }.
distinctunique-ifies the collection.
takepicks only the first N items from a collection.
The
childLinksToFollow function might be longer and more obfuscated if you
wrote it in Java with the Java collections API. The Scala version is also
better abstracted:
index.links could be any kind of collection (Set or
List, parallel or sequential) with few or no code changes.
Better refactoring
First-class functions are a powerful feature for factoring out common code. For example, in the AMQPCheck class (incidentally, another nice example of using an existing Java API from Scala), several places need to close an AMQP object while ignoring possible exceptions. You can quickly and easily do this in Scala:
private def ignoreCloseException(body: => Unit): Unit = { try { body } catch { case e: IOException => case e: AlreadyClosedException => } }
Then use it like this:
ignoreCloseException { channel.close() } ignoreCloseException { connection.close() }
You could also use a more traditional Java-style syntax, like this:
ignoreCloseException(channel.close()) ignoreCloseException(connection.close())
In Java, factoring this out to a common method might be clunky enough to keep you from doing it.
Parallel collections
Parallel collections have the same API as regular Scala collections, but operations on them magically take advantage of multiple CPU cores.
Convert any regular (sequential) collection to parallel with the
par
method and convert any parallel collection to sequential with the
seq
method. In most situations, parallel and sequential collections are
interchangeable, so conversions may not be needed in most code.
Two important points about Scala’s collections library that may be surprising compared to Java:
- immutable collections are the default; operations on immutable collections return a new, transformed collection, rather than changing the old one in-place
- when transforming a collection, the new collection will have the same type as the original collection
These properties are crucial to parallel collections. As you use
map,
filter,
sortBy, etc. on a parallel collection, each new result
you compute will itself be parallel as well. This means you only need to
convert to parallel once, with a call to
par, to convert an entire chain
of computations into parallel computations.
Parallel collections are enabled by functional programming; as long as you only use the functional style, the use of multiple threads doesn’t create bugs or trickiness. Parallel looks just like sequential.
Returning to IndexerActor, you can see parallel collections in action. We want to perform a word count; it’s a parallelizable algorithm. So we split the HTML into a parallel collection of lines:
val lines = s.split("\\n").toSeq.par
(
toSeq here converts the array from
java.lang.String.split() to a Scala
sequence, then
par converts to parallel.)
Then for each line in parallel we can break the line into words:
val words = lines flatMap { line => notWordRegex.split(line) filter { w => w.nonEmpty } }
The
flatMap method creates a new collection by matching each element in
the original collection to a new sub-collection, then combining the
sub-collections into the new collection. In this case, because
lines was a
parallel collection, the new collection from
flatMap will be too.
The parallel collection of words then gets filtered to take out boring words like “is”:
splitWords(body.text) filter { !boring(_) }
And then there’s a function to do the actual word count, again in parallel:
private[indexer] def wordCount(words: ParSeq[String]) = { words.aggregate(Map.empty[String, Int])({ (sofar, word) => sofar.get(word) match { case Some(old) => sofar + (word -> (old + 1)) case None => sofar + (word -> 1) } }, mergeCounts) }
The
aggregate method needs two functions. The first argument to
aggregate is identical to the one you’d pass to
foldLeft: here it adds
one new word to a map from words to counts, returning the new map. In fact
you could write
wordCount with
foldLeft, but it wouldn’t use multiple
threads since
foldLeft has to process elements in sequential order:
// ParSeq can't parallelize foldLeft in this version private[indexer] def wordCount(words: ParSeq[String]) = { words.foldLeft(Map.empty[String, Int])({ (sofar, word) => sofar.get(word) match { case Some(old) => sofar + (word -> (old + 1)) case None => sofar + (word -> 1) } }) }
The second argument to
aggregate makes it different from
foldLeft: it
allows
aggregate to combine two intermediate results. The signature of
mergeCounts is:
def mergeCounts(a: Map[String, Int], b: Map[String, Int]): Map[String, Int]
With this available,
aggregate can:
- subdivide the parallel collection (split the sequence of words into multiple sequences)
- fold the elements in each subdivision together (counting word frequencies per-subdivision in a
Map[String,Int])
- aggregate the results from each subdivision (merging word frequency maps into one word frequency map)
When
wordCount returns, IndexerActor computes a
list of the top 50 words:
wordCount(words).toSeq.sortBy(0 - _._2) take 50
toSeq here converts the
Map[String,Int] to a
Seq[(String, Int)]; the
result gets sorted in descending order by count; then
take 50 takes up to
50 items from the start of the sequence.
Full disclosure: it’s not really a given that using parallel collections for IndexerActor makes sense. That is, it’s completely possible that if you benchmark on a particular hardware setup with some particular input data, using parallel collections here turns out to be slower than sequential. Fortunately, one advantage of the parallel collections approach is that it’s trivial to switch between parallel and sequential collections as your benchmark results roll in.
XML Support
In WebActors.scala you can see an example of Scala’s inline XML support. In this case, it works as a simple template system to generate HTML. Of course there are many template systems available for Scala (plus you can use all the Java ones), but a simple application such as Web Words gets pretty far with the built-in XML support.
Here’s a function from WebActors.scala that returns the
page at
/words:
def wordsPage(formNode: xml.NodeSeq, resultsNode: xml.NodeSeq) = { <html> <head> <title>Web Words!</title> </head> <body style="max-width: 800px;"> <div> <div> { formNode } </div> { if (resultsNode.nonEmpty) <div> { resultsNode } </div> } </div> </body> </html> }
You can just type XML literals into a Scala program, breaking out into Scala
code with
{} anywhere inside the XML. The
{} blocks should return a
string (which will be escaped) or a
NodeSeq. XML literals themselves are
values of type
NodeSeq.
Bridging HTTP to Akka
There are lots of ways to serve HTTP from Scala, even if you only count Scala-specific libraries and frameworks and ignore the many options inherited from Java.
Web Words happens to combine embedded Jetty with Akka’s HTTP support.
Embedded Jetty: web server in a box
Heroku gives you more flexibility than most cloud JVM providers because you
can run your own
main() method, rather than providing a
.war file to be
deployed in a servlet container.
Web Words takes advantage of this, using embedded Jetty to start up an HTTP server. Because Web Words on Heroku knows it’s using Jetty, it can rely on Jetty Continuations, a Jetty-specific feature that allows Akka HTTP to reply to HTTP requests asynchronously without tying up a thread for the duration of the request. (Traditionally, Java servlet containers need a thread for every open request.)
There’s very little to this; see WebServer.scala, where
we fire up a Jetty
Server object on the port provided by Heroku (the
PORT env variable is picked up in WebWordsConfig.scala):
val server = new Server(config.port.getOrElse(8080)) val handler = new ServletContextHandler(ServletContextHandler.SESSIONS) handler.setContextPath("/") handler.addServlet(new ServletHolder(new AkkaMistServlet()), "/*"); server.setHandler(handler) server.start()
ServletContextHandler is a handler for HTTP requests that supports the
standard Java servlet API. Web Words needs a servlet context to
add
AkkaMistServlet to it. (Akka HTTP is also known as Akka Mist, for
historical reasons.)
AkkaMistServlet forwards HTTP requests to a special
actor known as the
RootEndpoint, which is also created in
WebServer.scala.
By the way, the use of Jetty here is yet another example of seamlessly using a Java API from Scala.
Akka HTTP
The
AkkaMistServlet from Akka HTTP suspends incoming requests using
Jetty Continuations and forwards each request as a
message to the
RootEndpoint actor.
In WebActors.scala, Web Words defines its own actors to
handle requests, registering them with
RootEndpoint in the form of the
following
handlerFactory partial function:
private val handlerFactory: PartialFunction[String, ActorRef] = { case path if handlers.contains(path) => handlers(path) case "/" => handlers("/words") case path: String => custom404 } private val handlers = Map( "/hello" -> actorOf[HelloActor], "/words" -> actorOf(new WordsActor(config))) private val custom404 = actorOf[Custom404Actor]
Request messages sent from Akka HTTP are subclasses of
RequestMethod;
RequestMethod wraps the standard
HttpServletRequest and
HttpServletResponse, and you can access the request and response directly
if you like. There are some convenience methods on
RequestMethod for
common actions such as returning an
OK status:
class HelloActor extends Actor { override def receive = { case get: Get => get OK "hello!" case request: RequestMethod => request NotAllowed "unsupported request" } }
Here
OK and
NotAllowed are methods on
RequestMethod that set a
status code and write out a string as the body of the response.
The action begins in WordsActor which generates HTML
for the main
/words page of the application, after getting an
Index
object from a ClientActor instance:
val futureGotIndex = client ? GetIndex(url.get.toExternalForm, skipCache) futureGotIndex foreach { // now we're in another thread, so we just send ourselves // a message, don't touch actor state case GotIndex(url, indexOption, cacheHit) => self ! Finish(get, url, indexOption, cacheHit, startTime) }
ClientActor.scala contains the logic to check the
MongoDB cache via IndexStorageActor and kick off an
indexer job when there’s a cache miss. When the
ClientActor replies, the
WordsActor sends itself a
Finish message with the information necessary
to complete the HTTP request.
To handle the
Finish message,
WordsActor generates HTML:
private def handleFinish(finish: Finish) = { val elapsed = System.currentTimeMillis - finish.startTime finish match { case Finish(request, url, Some(index), cacheHit, startTime) => val html = wordsPage(form(url, skipCache = false), results(url, index, cacheHit, elapsed)) completeWithHtml(request, html) case Finish(request, url, None, cacheHit, startTime) => request.OK("Failed to index url in " + elapsed + "ms (try reloading)") } }
A couple more nice Scala features are illustrated in
handleFinish()!
- keywords are allowed for parameters:
form(url, skipCache = false)is much clearer than
form(url, false)
- pattern matching lets the code distinguish a
Finishmessage with
Some(index)from one with
None, while simultaneously unpacking the fields in the
Finishmessage
Connecting the web process to the indexer with AMQP
Separating Web Words into two processes, a web frontend and a worker process
called
indexer, makes it easier to manage the deployed application. The
web frontend could in principle serve something useful (at least an error
page) while the indexer is down. On a more complex site, some worker
processes might be optional. You can also scale the two processes separately
as you learn which one will be the bottleneck.
However, having two processes creates a need for communication between them. RabbitMQ, an implementation of the AMQP standard, is conveniently available as a Heroku add-on. AMQP stands for “Advanced Message Queuing Protocol” and that’s what it does: queues messages.
Web Words encapsulates AMQP in two actors, WorkQueueClientActor and WorkQueueWorkerActor. The client actor is used in the web process and the worker actor in the indexer process. Both are subclasses of AbstractWorkQueueActor which contains some shared implementation.
Akka AMQP module
Akka’s AMQP module contains a handy
akka.amqp.rpc package, which layers a
request-response remote procedure call on top of AMQP. On the server
(worker) side, it creates an “RPC server” which replies to requests:
override def createRpc(connectionActor: ActorRef) = { val serializer = new RPC.RpcServerSerializer[WorkQueueRequest, WorkQueueReply](WorkQueueRequest.fromBinary, WorkQueueReply.toBinary) def requestHandler(request: WorkQueueRequest): WorkQueueReply = { // having to block here is not ideal // (self ? request).as[WorkQueueReply].get } // the need for poolSize>1 is an artifact of having to block in requestHandler above rpcServer = Some(RPC.newRpcServer(connectionActor, rpcExchangeName, serializer, requestHandler, poolSize = 8)) }
While on the client (web) side, it creates an “RPC client” which sends requests and receives replies:
override def createRpc(connectionActor: ActorRef) = { val serializer = new RPC.RpcClientSerializer[WorkQueueRequest, WorkQueueReply](WorkQueueRequest.toBinary, WorkQueueReply.fromBinary) rpcClient = Some(RPC.newRpcClient(connectionActor, rpcExchangeName, serializer)) }
WorkQueueClientActor and WorkQueueWorkerActor are thin wrappers around these server and client objects.
Akka’s AMQP module offers several abstractions in addition to the
akka.amqp.rpc package, appropriate for different uses of AMQP.
In Web Words, the web process does not heavily rely on getting a reply to RPC requests; the idea is that the web process retrieves results directly from the MongoDB cache. The reply to the RPC request just kicks the web process and tells it to check the cache immediately. If an RPC request times out for some reason, but an indexer process did cache a result, a user pressing reload in their browser should see the newly-cached result.
With multiple indexer processes, RPC requests should be load-balanced across them.
Message serialization
To send messages over AMQP you need some kind of serialization; you can use anything - Java serialization, Google protobufs, or in the Web Words case, a cheesy hand-rolled approach that happens to show off some neat Scala features:
def toBinary: Array[Byte] = { val fields = this.productIterator map { _.toString } WorkQueueMessage.packed(this.getClass.getSimpleName :: fields.toList) }
Scala case classes automatically extend a trait called
Product, which is
also extended by tuples (pairs, triples, and so on are tuples). You can walk
over the fields in a case class with
productIterator, so the above code
serializes a case class by converting all its fields to strings and
prepending the class name to the list. (To be clear, in “real” code you
might want to use a more robust approach.)
On the deserialization side, you can see another nice use of Scala’s pattern matching:
override def fromBinary(bytes: Array[Byte]) = { WorkQueueMessage.unpacked(bytes).toList match { case "SpiderAndCache" :: url :: Nil => SpiderAndCache(url) case whatever => throw new Exception("Bad message: " + whatever) } }
The
:: operator (“cons” for the Lisp crowd) joins elements in a list, so
we’re matching a list with two elements, where the first one is the string
"SpiderAndCache". You could also write this as:
case List("SpiderAndCache", url) =>
Checking AMQP connectivity
In AMQPCheck.scala you’ll find some code that uses RabbitMQ’s Java API directly, rather than Akka AMQP. This code exists for two reasons:
- it verifies that the AMQP broker exists and is properly configured; once Akka AMQP starts, you’ll get a deluge of backtraces if the broker is missing as Akka continuously tries to recover. The code in AMQPCheck.scala gives you one nice error message.
- it lets the web process block on startup until the indexer starts up, so startup proceeds cleanly without any backtraces.
More on AMQP
AMQP is an involved topic. RabbitMQ has a nice tutorial that’s worth checking out. You can use the message queue in many flexible ways.
Heroku makes it simple to experiment and see what happens if you run multiple instances of the same process, as you architect the relationships among your processes.
Caching results in MongoDB
Web Words uses AMQP as a “control channel” to kick the indexer process to index a new site, and tell a web process when indexing is completed. Actual data doesn’t go via AMQP, however. Instead, it’s stored in MongoDB by the indexer process and retrieved by the web process.
MongoDB is a convenient solution for caching object-like data. It stores collections of JSON-like objects (the format is called BSON since it’s a compact binary version of JSON). A special feature of MongoDB called a capped collection is ideal for a cache of such objects. Capped collections use a fixed amount of storage, or store a fixed number of objects. When the collection fills up, the least-recently-inserted objects are discarded, that is, it keeps whatever is newest. Perfect for a cache! MongoDB is pretty fast, too.
IndexStorageActor
IndexStorageActor encapsulates MongoDB for Web
Words. An
IndexStorageActor stores
Index objects: simple.
IndexStorageActor uses the Casbah library, a Scala-friendly
wrapper around MongoDB’s Java driver.
Much of the code in IndexStorageActor.scala
deals with converting
Index objects to
DBObject objects. This code could
be replaced with a library such as Salat, but it’s done by hand in
Web Words to show how you’d do it manually (and avoid another dependency).
IndexStorageActor is an actor pool, extending
IOBoundActorPool. Because Casbah is a blocking API,
each worker in the pool will tie up a thread for the duration of the request
to MongoDB. This can be dangerous; by default, Akka has a maximum number of
threads, and running out of threads could lead to deadlock. At the same
time, you don’t want to have too few threads in your IO-bound pool because
you can do quite a bit of IO at once (since it doesn’t use up CPU). Tuning
this is an application-specific exercise.
IndexStorageActor could override the
upperBound method to adjust the
maximum size of its actor pool and thus the maximum number of simultaneous
outstanding MongoDB requests.
An asynchronous API would be a better match for Akka, and there’s one in development called Hammersmith.
Using a capped collection
IndexStorageActor’s use of MongoDB may be pretty self-explanatory.
To set up a capped collection:
db.createCollection(cacheName, MongoDBObject("capped" -> true, "size" -> sizeBytes, "max" -> maxItems))
To add a new
Index object to the collection:
cache.insert(MongoDBObject("url" -> url, "time" -> System.currentTimeMillis().toDouble, "index" -> indexAsDBObject(index)))
To look up an old
Index object:
val cursor = cache.find(MongoDBObject("url" -> url)) .sort(MongoDBObject("$natural" -> -1)) .limit(1)
The special key
"$natural" in the above “sort object” refers to the order
in which objects are naturally positioned on disk. For capped collections,
this is guaranteed to be the order in which objects were inserted. The
-1
means reverse natural order, so the sort retrieves the newest object first.
Build and deploy: SBT, the start-script plugin, and ScalaTest
The build for Web Words illustrates:
- SBT 0.11
-
- xsbt-start-script-plugin
-
- testing with ScalaTest
-
Here’s a quick tour of each one, as applied to Web Words.
Simple Build Tool (SBT)
SBT build configurations are themselves written in Scala; you can find the
Web Words build in project/Build.scala. This is an example
of a “full” configuration; there’s another (more concise but less
flexible) build file format called “basic” configuration. Full
configurations are
.scala files while basic configurations are in special
.sbt files. While full configurations require more typing, basic
configurations have the downside that you need to start over with a full
configuration if you discover a need for more flexibility.
SBT build files are concerned with lists of settings that control the build. An SBT build will have a tree of projects, where each project will have its own list of settings.
In project/Build.scala, you can see there are four
projects; the project called
root is an aggregation of the
web,
indexer, and
common projects that contain the actual code.
Here’s the definition of the
common project, which is a library shared
between the other two projects:
lazy val common = Project("webwords-common", file("common"), settings = projectSettings ++ Seq(libraryDependencies ++= Seq(akka, akkaAmqp, asyncHttp, casbahCore)))
According to this configuration,
- The project is named “webwords-common”; this name will be used to name the jar if you run
sbt package, so the prefix
webwords-is intended to avoid a jar called
common.jar.
- The project will be in the directory
common(each project directory should contain a
src/main/scala,
src/test/scala, etc. for a Scala project, or
src/main/java,
src/main/resources, and so on).
- The project’s settings will include
projectSettings(a list of settings defined earlier in the file to be included in all projects), plus some library dependencies.
Settings are defined with some special operators. In project/Build.scala you will see:
:=sets a setting to a value
+=adds a value to a list-valued setting
++=concatenates a list of values to a list-valued setting
xsbt-start-script-plugin
Have a look at the Procfile for Web Words, you’ll see it contains the following:
web: web/target/start indexer: indexer/target/start
The format is trivial:
NAME OF PROCESS: SHELL CODE TO EXECUTE
Heroku will run the given shell code to create each process. In this case,
the
Procfile launches a script called
start created by SBT for each
process.
These scripts are generated by xsbt-start-script-plugin as
part of its
stage task.
stage is a naming convention that could be
shared by other plugins and means “prepare the project to be run, in an
environment that deploys source trees rather than packages.” In other words,
stage does what you want in order to compile and run the application
in-place, using the class files generated during the compilation. While
sbt
package (built in to SBT) creates a
.jar and
sbt package-war (provided
by xsbt-web-plugin) creates a
.war,
sbt stage gives
you something you can execute (from
Procfile or its non-Heroku equivalent).
If you run
sbt stage and have a look at the generated
start script,
you’ll see that it’s setting up a classpath and specifying which main
class the JVM should run.
The xsbt-start-script-plugin README explains how to use it in
a project, in brief you add its settings to your project, for example
the
indexer project in Web Words:
lazy val indexer = Project("webwords-indexer", file("indexer"), settings = projectSettings ++ StartScriptPlugin.startScriptForClassesSettings ++ Seq(libraryDependencies ++= Seq(jsoup))) dependsOn(common % "compile->compile;test->test")
startScriptForClassesSettings defines
stage to run a main method found
in the project’s
.class files. The plugin can also generate a script to
run
.war files and
.jar files, if you’d rather package the project and
launch from a package.
ScalaTest
It’s possible to use
JUnit with a Scala project, but there are a few
popular Scala-based test frameworks (you can use them for Java projects too,
by the way). Web Words uses ScalaTest, two other options are
Specs2 and ScalaCheck.
ScalaTest gives you a few choices for how to write test files. An example from Web Words looks something like this:
it should "store and retrieve an index" in { val storage = newActor cacheIndex(storage, exampleUrl, sampleIndex) val fetched = fetchIndex(storage, exampleUrl) fetched should be(sampleIndex) storage.stop }
ScalaTest provides a “domain-specific language” or DSL for testing. The idea is to use Scala’s flexibility to define a set of objects and methods that map naturally to a problem domain, without having to give up type-safety or write a custom parser. (SBT’s configuration API is another example of a DSL.)
The ScalaTest DSL lets you write:
it should "store and retrieve an index" in
or
fetched should be(sampleIndex)
rather than something more stilted.
There are quite a few tests in Web Words, illustrating one way to go about testing an application. You may find TestHttpServer.scala useful: it embeds Jetty to run a web server locally. Use this to test HTTP client code.
If you declare a project dependency with
"compile->compile;test->test",
then the tests in that project can use code from the dependency’s tests.
For example, in Build.scala, the line
dependsOn(common % "compile->compile;test->test")
enables the
web and
indexer projects to use
TestHttpServer.scala located in the
common project.
Often it’s useful to define tests in the same package as the code you’re testing. This allows tests to access types and fields that aren’t accessible outside the package.
Summing it up
A real application has quite a few moving parts. In Web Words, some of those are traditional Java libraries (JSoup, Jetty, RabbitMQ Java client, AsyncHttpClient) while others are shiny new Scala libraries (Akka, Casbah, ScalaTest).
Scala and Akka are pragmatic tools to pull the JVM ecosystem together and write horizontally scalable code, without the dangers of rolling your own approach to concurrency. Programming in functional style with the actor model naturally scales out, making these approaches a great fit for cloud platforms such as Heroku.
About Typesafe
Typesafe, a company founded by the creators of Scala and Akka, offers the commercially-supported Typesafe Stack. To learn more, or if you just want to hang out and talk Scala, don’t hesitate to look us up at typesafe.com.
Keep reading
Your feedback has been sent to the Dev Center team. Thank you. | https://devcenter.heroku.com/articles/scaling-out-with-scala-and-akka | CC-MAIN-2015-27 | refinedweb | 7,750 | 53.31 |
Difference between revisions of "Wikimedia Cloud Services team/EnhancementProposals/Toolforge Buildpack Implementation"
Revision as of 23:13, 12 October 2021
Task T194332
Overview
Building on Wikimedia Cloud Services team/EnhancementProposals/Toolforge push to deploy and initial PoC at Portal:Toolforge/Admin/Buildpacks, this is an effort at delivering a design document and plan for the introduction of a buildpack-based workflow.
Toolforge is a Platform-as-a-Service concept inside Cloud VPS, but it is burdened heavily by technical debt from outdated designs and assumptions. Since the latest implementations of Toolforge's most effectively curated services are all cloud native structures that are dependent on containerization and Kubernetes, moving away from shell logins and compute batch processing (like Grid Engine) that is heavily tied to NFS, the clear way forward is a flexible, easy-to-use container system that launches code with minimal effort on the part of the user while having a standardized way to contribute to the system itself. Today, the community-adopted and widely-used solution is Cloud Native Buildpacks, a CNCF project that was originally started by Heroku and Cloud Foundry based on their own work in order to move toward industry standardization (partly because those platforms and similar ones like Deis pre-dated Kubernetes, OCI and similar cloud native standards therefore relying on LXC, tarballs and generally incompatible-with-the-rest-of-the-world frameworks). Since it is a standard and a specification, there are many implementations of that standard. The one used for local development is the
pack command line tool, which is also orchestrated by many other integrations such at Gitlab, Waypoint and CircleCI. Separate implementations are more readily consumed if not using those tools such as kpack (which is maintained mostly by VMWare) and a couple tasks built into to Tekton CI/CD that are maintained by the Cloud Native Buildpacks group directly (like
pack). Because Tekton is designed to be integrated into other CI/CD solutions and is fairly transparent about it's backing organizations, it is a natural preference for Toolforge as it should work with Jenkins, Gitlab, Github, etc.
To get an idea of what it "looks like" to use a buildpack, it can be thought of as simply an alternative to using a Dockerfile. It's an alternative that cares about the specific OCI image (aka Docker image) layers that are created and exported to prevent not only an explosion of space used by them but to make sure that the lower layers stay in a predictable state that can be rebased on top of when they are updated. The example used is almost always using the pack command to deploy an app locally (see). This looks either like magic (if you are used to creating Dockerfiles) or like just another way to dockerize things. That really doesn't explain a thing about what buildpacks are or why we'd use them. A better example would be to create a Node.js app on Gitlab.com, enable "Auto DevOps" (aka buildpacks), add a Kubernetes cluster to your Gitlab settings and watch it magically produce a CI/CD pipeline all the way to production without any real configuration. That's what it kind of looks like if you get it right. The trickier part is all on our end.
Concepts
Buildpacks are a specification as well as a piece of code you can put in a repository. It is somewhat necessary to separate these two ideas in order to understand the ecosystem. Part of the reason for this is that buildpacks don't do anything without an implementation of the lifecycle in a platform. A "buildpack" applies user code to a "stack" via a "builder" during the "lifecycle" to get code onto a "platform", which is also the term used to describe the full system. So when we talk about "buildpacks" we could be talking about:
- the buildpacks standard and specification
- a specific buildpack, like this one for compiling golang
- a platform that implements the specification (like pack, Tekton or kpack)
This is not made easier to understand by the ongoing development of the standard (which now includes stackpacks, which can take root actions on layers before handing off to buildpacks--such as running package installs).
Design
Requirements
- Must run in a limited-trust environment
- Elevated privileges should not be attainable since that breaks multi-tenancy and the ability to use Toolforge as a curated environment
- This might seem obvious, but it needs to be stated since so many implementations of this kind of thing assume a disposable sandbox or a trusted environment.
- Storage of artifacts must have quotas
- Bad actors are not needed to fill disks by mistake
- Selection of builders must be reviewed or restricted
- Since the buildpack lifecycle is effectively contained in your builder, the builder selects the stack you use, what you can do and how you do it. Without controlling builder selection, the system is unable to maintain security maintenance, deduplication of the storage via layer control and rebasability during security response.
- The system must at least be available in toolsbeta as a development environment if not usable or at least testable on local workstations.
- It must be possible for it to coexist with the current build-on-bastion system.
- This implies that webservice is aware of it. See task T266901
- This is really two problems: Build and Deploy
- Once you have a build, we might need to decide how to deploy it. For now, that could just be a webservice command argument.
- Deployment is much more easily solved depending on how we want things to roll. It could be automatic.
Nice-to-haves
- A dashboard (or at least enough prometheus instrumentation to make one)
- A command line to use from bastions that simplifies manual rebuilds
Components
Build Service
The specification and lifecycle must be implemented in a way that works with our tooling and enables our contributors without breaking the multitenancy model of Toolforge entirely. Effectively, that means it has to be integrated in a form of CI in Kubernetes (as it is or in a slightly different form). Buildpacks are not natively implemented in Jenkins without help, and Gitlab may be on its way, but in order to build out with appropriate access restrictions, security model and full integration into WMCS operations we likely need to operate our own small "CI" system to process buildpacks.
The build service is itself the center piece in the setup. The build service must be constructed so that is the only user-accessible system that has credentials to the artifact (OCI) repository. Otherwise, you don't need to deal with it and can push whatever you want. This is quite simple to accomplish if builds happen in a separate namespace where users (and potentially things like Striker) pipelines for Tekton (in this case). Tool users have no access to pods or secrets in that namespace. At that point, as long as the namespace has the correct secret placed by admins, the access will be available. An admission webhook could insist that the creating user only be talking about their own project in Harbor, is in group Toolforge, only uses approved builders, etc. The namespace used is named
image-build.
Tekton CI/CD provides a good mechanism for this since it is entirely build for Kubernetes and is actively maintained with buildpacks in mind. It does have a dashboard available that may be useful to our users. Tekton provides tasks maintained by the cloud-native buildpacks organization directly and is the direction Red Hat is moving OpenShift as well, which guarantees some level of external contribution to that project. It is also worth noting that KNative dropped their "build" system in favor of Tekton as well.
Because we are not able to simply consume Auto DevOps from Gitlab (some issues include with the expectation of privileged containers and DinD firmly embedded in the setup), we are pursuing Tekton Pipelines.
Artifact Repository
Since Docker software is getting dropped from many non-desktop implementations of cloud native containers, it is usually talked about as OCI images and registries that we are working with. Docker is a specific implementation and extension of the standard with its own orchestration layers that are separate from the OCI spec. All that said, we need a registry to work with, and right now, Toolforge uses the same basic Docker registry that is used by production, but we use local disk instead of Swift for storage. This is highly limiting. Since WMCS systems are not limited exclusively to Debian packaging, it is possible we could deploy the vastly popular and much more business-ready Harbor that is maintained mostly by VMWare. Harbor is deployed via docker compose or (in better, more fault tolerant form) helm since it is distributed entirely as OCI images built on VMWare's peculiar Photon OS. That's why it was rejected by main production SRE teams because repackaging it would be a huge piece of work. Despite this odd deployment style, it enjoys wide adoption and contributions now and is at 2.0 maturity. It can also be used to cache and proxy to things like Quay.io. The downside of Harbor is that it is backed by Postgresql, and it doesn't solve the storage problem inherently. While it would be ideal to deploy that with Trove Postgresql and Swift storage. We could deploy it initially with a simple postgres install and cinder storage volumes. Ultimately, only Harbor has no real potential concerns with licensing and has quotas.
Edit: We are testing Harbor as the most complete open source implementation of what we need. It has quotas, multi-tenancy and a solid authentication model that allows for "robot" accounts just like Quay and Docker Hub. We don't need to link it to LDAP, since ideally, users cannot write to it directly, anyway. Users should go through the build system only. Right now it is running on for initial build and testing. It should be deployed using helm on Kubernetes in the end, and it has the ability to back up to Quay.io. As long as we are consuming the containerized version directly, this is a solved problem.
Dashboards and UX
This is going to depend on the implementation of build service a bit.
Deployment Service
If this sounds like "CD", you'd be right. However, initially, it may be enough to just allow you to deploy your own images with
webservice. Once you have an image, you can deploy however you want. Tekton is entirely capable of acting as a CD pipeline as well as CI, while kpack is a one-trick pony. We may want something entirely different as well, but when everyone still has shell accounts anyway in Toolforge, this seems like the item that can be pushed down the road.
Build Service Design
Tekton Pipelines is a general purpose Kubernetes CRD system with a controller, another namespace and a whole lot of capability. To use it as a build system, we are consuming a fair amount of what it can do.
The currently functional (but not ready for production) manifests that are live in Toolsbeta are reviewable at
Namespacing
The controller and mutating webhook live in the
tekton-pipelines namespace. Those are part of the upstream system. The webhook has a horizontal pod autoscaler to cope with bursts. The CRDs interact with those components to coordinate pods using the ClusterRole tekton-pipelines-controller-tenant-access (see RBAC).
Actual builds happen in the
image-build namespace. Tool users cannot directly interact with any core resources there--only:
- pipelines (where parameters to the git-clone task and buildpacks task are defined)
- pipelineruns (which actually make pipelines do things)
- PVCs (to pass the git checkout to the buildpack)
- pipelineresources (to define images) will be accessible to Toolforge users.
Those resources need further validation (via webhook) and are probably best defined by convenience interfaces (like scripts and webapps).
The required controller for the NFS subdir storage class is deployed into the
nfs-provisioner namespace via helm.
Triggers for automated builds from git repos might be defined in tool namespaces.
Deployments are simply a matter of allowing the harbor registry for tool pods. Automated deployment might be added as optional finishes to pipelines when we are ready.
RBAC by subject
- tekton-pipelines-controller service account
- A ClusterRole for cluster access applied to all namespaces
- A ClusterRole for tenant access (namespaced access) -- this provides access to run Tasks and Pipelines in the
image-buildnamespace
- tekton-pipelines-webhook service account
- Uses a ClusterRole for mutating and validating webhook review
- default service account in image-build namespace
- git-clone task will run as this service account
- tool accounts
- require read access to task, taskruns, pipelines, pipelineresources and conditions in the
image-buildnamespace
- require read-write access to pipelineruns and persistent volume claims in
image-build
- buildpacks-service-account service account (for buildpack pods)
- Will need root for an init container so it needs a special PSP as well as other appropriate rights
- Has access to the basic-user-pass secret in order to push to Harbor.
Pod Security Policy (later to be replaced by OPA Gatekeeper)
Sorted out mostly, but to be added here.
Storage
To pass a volume from the git-clone task to the buildpacks task, you need a Tekton
workspace. The workspace is backed by a persistent volume claim. It is much simpler to have a StorageClass manage the persistent volumes and automatically provision things than to have admins dole them out. The NFS subdir provisioner works quite well. The basic idea is giving it a directory from an NFS share the workers have access to and it will happily create subdirectories and attach them to pods, deleting them when the volume claim is cleaned up. For the most part, storage size provisioning seems to have little effect on unquota'd NFS volumes. As usual, tool users will need to simply be polite about storage use. This can later be replaced by cinder volumes (using the openstack provider) or at least an NFS directory with a quota on it to prevent harm.
The image can be cached in our standard image repo, but an example values file would look like this:
It's deployed using (for example)
helm --kube-as-user bstorm --kube-as-group system:masters --namespace nfs-provisioner install nfs-provisioner-beta-1 nfs-subdir-external-provisioner/nfs-subdir-external-provisioner -f volume-provisioner-values.yaml
Secrets
- webhook-certs
- In the
tekton-pipelinesnamespace. This may need renewal from time to time, and it is populated during installation of Tekton Pipelines. If this doesn't have a self-renewal setup, having a renewal workflow is a requirement for deployment in tools.
- basic-user-pass
- This is the main reason the buildpacks-service-account is needed. That's what has access to this secret. It should be the robot account for Harbor.
Tasks
The tasks needed are both snitched right from the tekton catalog with slight modification in the case of the buildpacks task.
- git-clone 0.4
- buildpacks phases 0.2
- Using the buildpacks-phases task splits each phase into a distinct container. That means the docker credentials are only exposed by Tekton to the export phase, not detect and build (where user code is being operated on).
Deployment
These topics are presented in the relative order needed for deployment.
Harbor
Harbor is going to need a service (such as maintain-kubeusers or something else) that creates projects and default quotas for Toolforge users. Each tool should have 1 project (same name as the tool) and a quota. Otherwise, it is going to need people creating accounts by hand, and that sounds like a bad thing. Accounts are mostly not needed since all users have read access and a robot account for the build service will maintain the write access. Tools admins can have admin-level accounts to manipulate quotas and shared images (like the old school images for tools k8s). Harbor has a REST API for managing quotas and projects.
It is theoretically possible to break down and Debian package Harbor. It is also theoretically possible to build a synthetic life form out of chemicals. While it may not be quite that hard to package since it's all golang, it's also intended to run in VMWare's photonOS inside a container anyway. It's best to deploy it in a container as intended by upstream. Two methods are offered: helm (for HA production deployments) and docker-compose (for people using compose in production and every other use case). Since we don't have swift as a backend for storage yet, we should not use helm until we do. When we do, that's probably the lowest-friction method.
For now, keeping the docker-compose installer setup on a cinder volume seems sensible, especially if that cinder volume gets backed up or snapshotted eventually. The cinder volume will also hold the images, redis snaps and so forth until we have appropriate storage.
If you aren't running harbor for testing, you want to have the postgresql database separate and replicated. Redis running separately is needed for real HA and for helm (for worker processes, mostly used during replication of images to places like quay.io or other harbor instances), but we can get away with using a local container if we only run a standalone server at this time with cinder storage.
PostgreSQL
This is best a puppet-controlled pair right now. Trove postgresql is terrible in OpenStack Victoria. I hope that changes in time.
Harbor itself
All other services can be managed by docker-compose. The installation process is described at the installation page on goharbor.io. A puppet-mangaged harbor.yml file to preserve rebuild-ability seems like a good way of maintaining the basic design.
Harbor services
Harbor offers more services that we need or want. Notary is unlikely to be useful in Toolforge with anything approaching current processes, but it can do that if that is ever wanted in the future. Trivy is kind of awesome, and I see no reason not to use it for vulnerability scanning of images. The chart museum is not used at this time, but again, it can do it if you want. In the interest of simplicity, we will initially be running with an initial install of
sudo ./install.sh --with-trivy per. Running additional services other than notary is mostly a change in what docker-compose launches and can be done later. Notary requires two additional postgresql databases as well to manage signers and such.
Tekton
While the triggers aren't set up yet anywhere (maybe soon?) which is the essential feature that actually allows the start of a build from pushing to a repo on GitHub, Gitlab and (with some coding) Gerrit, we can set up the skeleton which does everything else and can be launched by creating a
PipelineRun object in k8s.
The build service repository is currently, so be added probably to the control plane nodes for Kubernetes via puppet. Deployment instructions are on the README.md file. It is notable that most of it is upstream TektonCD controllers and CRDs with the appropriate access restrictions and controls to operate in Toolforge with a slightly customized version of the buildpacks pipeline maintained by the buildpacks project itself for Tekton.
It does also require a custom validating webhook controller in order to prevent people from committing built images to someone else's Harbor project. Tekton should not be enabled using those manifests without immediately setting the controller running for that reason. The controller may or may not deploy cleanly first since it is looking for the CRD objects that Tekton defines. It is probably best to deploy it immediately following Tekton.
buildpacks-admission-controller
The code is stored on Github here because Brooke was impatient about setting up the repo quickly. The structure of the repo is a bit more standardized (only slightly) for a golang project, but otherwise, it works much like the other controllers we have. Instructions are on the README.md.
To make this useful with current Toolforge and webservice
The existing system is extremely intertwined with ssh shell usage, LDAP, NFS and related tooling. Tool accounts are not logged into directly but are rather a sudo special-case using
become. There are many interesting consequences to this. Buildpacks solve the problem of allowing people to create OCI images in a controlled fashion that can be quota'd and budgeted for, but they break the mold of existing Toolforge by being totall independent of the LDAP UID, unix shell user way of existing. This is a set of suggestions for making a first iteration into a deployable and useful solution for elimination of dependence on Gridengine and it's toolchain (whether grid is a part or not).
- Trigger builds (PipelineRun objects) with something like
webservice --build myimage:tag --source github.com/myuser/mycoolappwhich is ultimately sufficient for us to guess the rest. This could also be placed in the service.template files. The only other value we might want is the builder, and we could have a default builder included.
- Deploying said build is a bit more interesting because a buildpack cannot access LDAP or NFS because of the need for the toolchain to all use the same UID/GID.
- Have a standard location for config or secrets on NFS. And when webservice runs a buildpack-based image, it loads them into configmaps or secrets that are mounted into the container. This would make webservice a strangely cloud native application at that point that would have functions you could actually test locally. It might even be useful outside the foundation at that rate.
- You could also modify default behavior using the existing service.template mechanism in webservice.
- This would mean you could have
webservice start $imagename:$tagand as long as you have config in the right places, and it is well understood that they will be mounted in the same places in the container (or something like that), people could work almost like they do now while having NFS just be a source for where the info is copied from into k8s.
- maintain-dbusers needs to create k8s secrets for wikireplicas access to be mounted into the containers.
- This still needs maintain-kubeusers (or similar, but that prevents race conditions) to create projects and default quotas in harbor instances that are based on toolnames.
- The plan was basically to replace tools-docker-registry with a harbor instance.
- An easy hack to allow access to the logs of the system is to run the read-only version of the tekton dashboard such as. It works very nicely in local testing.
why?
This makes NFS, LDAP and shell access something of an implementation detail and not the platform itself regardless of whether or not you get to delete it all on day one. One day, the same workflow could be done, for instance, from a PAWS terminal with just about any cloud storage solution backing it to upload your configmap sources with a persistent volume claim (cinder, EBS volumes, any of the countless "enterpries" storage options, rook, etc). That would remove some of the locked-in parts of our tech debt and allow some flexibility in future decision making while giving users the ability make complex, custom, multi-runtime containers without making a ticket and increasing the size of containers for everyone else or just containers that actually contain code instead of using containers as extremely heavy ways to operate on NFS. This is presuming you never trigger a build from a webhook or deploy it automatically from a web console that lets you upload secrets or something. | https://wikitech-static.wikimedia.org/w/index.php?title=Wikimedia_Cloud_Services_team/EnhancementProposals/Toolforge_Buildpack_Implementation&curid=277045&diff=584139&oldid=583998 | CC-MAIN-2021-49 | refinedweb | 3,956 | 50.16 |
This is a WPF application on the front end which is the migration tool.
I have a dll which i'm trying to reference both an older version and new version.
The purpose is to use it for migration and de-migration purposes between versions of the product.
example (versions numbers are an example)
I have a release 1.0.15 of the product (.exe file) and it refernces an assembly with some pocos (this assembly version is 2.0.1.0, dll file) which are serialised to json and stored in the database. I then modify the poco object in version 1.0.16 of the product (poco assembly version now is 2.0.2.0). Now when i try to desrealised the json object it longer works as json can't deserialise to the class (json is using strongly typed classes to serialise to interface).
One way i though of was to deserialise the json to the poco in version 2.0.1.0 and then remap to version 2.0.2.0 and save to database.
So i followed this Using two DLLs with same name and same namespace
this didnt work fully as it was complaining about that the name already exists in the project requesting i either sign my assemly or remove it.
i then signed my assemblies using (brutal developer signing) using unsigned assemblies in signed ones. Though when it's signed is says delayed signing for some reason
this let me build with no errors. however now when i run and get to the class which is about to run the migration it fails with Fiel Load Exception Could not load file or assembly ........... The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
So any ideas how i can solve this problem? i've been on a hunt the for 2 days looking through forums and posts
User contributions licensed under CC BY-SA 3.0 | https://windows-hexerror.linestarve.com/q/so63198215-How-to-reference-a-unsigned-dll-with-different-versions-in-visual-studio-2019 | CC-MAIN-2020-40 | refinedweb | 330 | 72.87 |
A collection of data for demographics and housing from the Census planning database. Files are broken into counties, for San Diego and Los Angeles
sandiegodata.org-planning-tracts-9
Resources | Packages | Documentation| Contacts| References| Data Dictionary
Resources
- planning_db_sd. San Diego county planning database tracts
- planning_db_la. Los Angeles county planning database tracts
Documentation
The Planing Database is a Census product that combines a range of data from the American Community Survey and 2010 Decenial Census into a single file, with one row per census tract. This version of the file includes only tracts in San Diego County. The file is linked to ACS format geoids to identify tracts, so it can be easily linked to other tracts data. This data package includes links to two such files, one for San Diego communities, and one for tract geographics.
The planning database has about 450 columns. For full definitions of the columns, refer to the upstream documentation for the source file. In general, the column names in the documentation must be lowercased for use with the file in this data package.
Use patterns
In Python, use metapack to open the data package.
import metapack as mp pkg = mp.open_package('')
To display a simple map, link in the tract boundaries from the communities
dataset and use the Geopandas .plot() function. The
column argument names
the column to use for coloring regions. Note that the column name is copied
from the documentation with mixed case, then lowercased to index the dataset.
tracts = pkg.reference('communities').geoframe().set_index('geoid').fillna('') df = tracts.join(cpdb) fig, ax = plt.subplots(1, figsize=(15,10)) df.plot(ax=ax, column='pct_MLT_U10p_ACS_12_16'.lower())
After linking in the communities, you can also use the community id columns to group by city or community:
seniors = dfg.df.groupby('city_name').pop_65plus_acs_12_16.sum()
Versions
- First Release
- Clean more currency columns
- Extended schema metadata.
- Added ‘group’ to metadata.
Documentation Links
- Tract PDB Documentation. documentation and data dictionaryplanning_db
planning_db
References
Urls used in the creation of this data package.
- census_planning_database. Source file for the planning database.
- metapack+. Links communities to tracts
- metapack+. TRACT BOUNDARIES
Last Modified 2019-01-03T22:48:33 | https://data.sandiegodata.org/dataset/sandiegodata-org-planning-tracts/ | CC-MAIN-2019-51 | refinedweb | 355 | 50.84 |
In this tutorial, you will learn how to configure an Nginx server on Ubuntu with the Django web framework and WSGI as the web server gateway interface. The server configuration will be production-ready and set up for public release.
Throughout the tutorial, concepts will be introduced and demonstrated so you can gain an understanding of how each piece works.
Before you begin:
- I will be using the domain name micro.domains throughout this tutorial.
- It is recommended that you configure your domain name’s DNS A records to point to the IP address of your server. Here’s a tutorial on how to do that. Don’t have a server? I’ll be using Linode to deploy a server running Ubuntu 20.04.
- It is recommended that you use a user other than root. Here’s a tutorial about how to add users to Ubuntu.
1. Update Your Server
It’s always a good idea to start by updating your server.
sudo apt-get update sudo apt-get upgrade
Now we have the latest and greatest packages installed on the server.
2. Use a Virtual Environment for Python
The venv module allows you to create virtual Python environments. This allows you to isolate installed packages from the system.
After installing venv, make a directory to house your virtual environments, and then create a virtual environment named
md using venv. You can call your virtual environment whatever you prefer.
apt-get install python3-venv mkdir /home/udoms/env/ python3 -m venv /home/udoms/env/md
Now activate your virtual environment.
source /home/udoms/env/md/bin/activate
You will see the name of your virtual environment in parenthesis as a prefix to your username and server name in your terminal window.
You can also verify that you are working from within your virtual environment by taking a look at where the Python binary is located.
which python
In this case, we are using Python version 3.8.5 which is located in the
/home/udoms/env/md/bin/python directory.
3. Create a Django Project
Now that our Python environment is set up, we can install the Django web framework using the pip package installer.
pip install Django
Next let’s create a Django project with django-admin.py which should be on your path by default. Feel free to choose a project name that suites you.
django-admin.py startproject microdomains cd microdomains
Test out your project by spinning up the built-in Django server with the following command:
python manage.py runserver 0.0.0.0:8000
In a browser, you should be able to visit
micro.domains:8000 and see the default Django landing page. If not, you might you see a Django error message like this:
If you see this error message, add your domain name to the
microdomains/settings.py file.
... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['micro.domains', ''] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', ...
Try to visit
micro.domains:8000 again and this time you will see the default Django landing page.
4. Get Started With uWSGI
First we need to install the web server gateway interface (WSGI). In this case, we will be using uWSGI. You will also need the development packages for your version of Python to be installed.
sudo apt-get install python3.8-dev sudo apt-get install gcc pip install uwsgi
The ultimate goal in this tutorial is to send requests from the client to Nginx which will pass them to a socket that will hand them off to uWSGI before finally being given to Django.
That’s a lot to configure right off the bat, so we will start with a much simpler test just to make sure all the individual puzzle pieces are in place.
Create a file called
test.py with the following content:
def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World!"]
Let’s test out uWSGI directly talking to Python with the following command:
uwsgi --http :8000 --wsgi-file test.py
In a browser, you should be able to visit
micro.domains:8000 and see the text “Hello World!”
If this works for you, we have demonstrated that uWSGI is able to pass requests to Python.
Now we can similarly serve the Django project with uWSGI with the following command:
uwsgi --http :8000 --module microdomains.wsgi
Note that this works because the path
microdomains/wsgi.py exists. Test it out in a browser and you should see the default Django landing page again.
5. Configure the Nginx Web Server
Install Nginx with
apt-get as follows:
sudo apt-get install nginx
Now with Nginx installed, you will be able to visit the default “Welcome to nginx!” page in your browser at.
Let’s tell Nginx about our Django project by creating a configuration file at
/etc/nginx/sites-available/microdomains.conf. Change the highlighted lines to suite your needs.
# the upstream component nginx needs to connect to upstream django { server unix:///home/udoms/microdomains/microdomains.sock; } # configuration of the server server { listen 80; server_name micro.domains; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/udoms/microdomains/media; } location /static { alias /home/udoms/microdomains/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/udoms/microdomains/uwsgi_params; } }
We need to create the
/home/udoms/microdomains/uwsgi_params file highlighted above on line 26 as well. REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name;
Next we can publish our changes by creating a symbolic link from sites-available to sites-enabled like so:
sudo ln -s /etc/nginx/sites-available/microdomains.conf /etc/nginx/sites-enabled/
We must edit the
microdomains/settings.py file to explicitly tell Nginx where our static files reside.
First add
import os at the very beginning:
""" Django settings for microdomains project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see For the full list of settings and their values, see """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ...
and
STATIC_ROOT = os.path.join(BASE_DIR, "static/") at the very end:
... # Static files (CSS, JavaScript, Images) # STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/")
With these changes in place, we can now tell Django to put all static files in the static folder.
python manage.py collectstatic
Restart the Nginx server to apply changes.
sudo /etc/init.d/nginx restart
At this point if you visit a browser, you will probably see an Nginx 502 Bad Gateway error, but at this point we just want to test if media files are being properly served. So to test this out, let’s put an image in our media directory.
mkdir media wget -O media/media.gif
Finally visit in a browser and you should see Google’s first logo from back in 1998.
6. Get Nginx, uWSGI, and Django to Work Together
Let’s take this one step further and have Nginx, uWSGI, and Django work together with the help of the UNIX socket.
uwsgi --socket microdomains.sock --module microdomains.wsgi --chmod-socket=666
You can actually try the above command without the
--chmod-socket=666 argument and/or with a
--chmod-socket=664 argument instead. If either of those work for you, just keep that in mind going forward.
Once again, visit a browser, and this time you should see the default Django landing page!
7. Configure uWSGI for Production
Rather than passing arguments to uWSGI like we did above, we can put these options in a configuration file at the root of you Django project called
microdomains_uwsgi.ini.
[uwsgi] # full path to Django project's root directory chdir = /home/udoms/microdomains/ # Django's wsgi file module = microdomains.wsgi # full path to python virtual env home = /home/udoms/env/md # enable uwsgi master process master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/udoms/microdomains/microdomains.sock # socket permissions chmod-socket = 666 # clear environment on exit vacuum = true # daemonize uwsgi and write messages into given log daemonize = /home/udoms/uwsgi-emperor.log
You can then proceed to start up uwsgi and specify the ini file:
uwsgi --ini microdomains_uwsgi.ini
Visit a browser and you will see the default Django landing page if everything works correctly.
As one last configuration option for uWSGI, let’s run uWSGI in emperor mode. This will monitor the uWSGI config file directory for changes and will spawn vassals (i.e. instances) for each one it finds.
cd /home/udoms/env/md/ mkdir vassals sudo ln -s /home/udoms/microdomains/microdomains_uwsgi.ini /home/udoms/env/md/vassals/
Now you can run uWSGI in emperor mode as a test.
uwsgi --emperor /home/udoms/env/md/vassals --uid www-data --gid www-data
Visit a browser and you will see the default Django landing page if everything works correctly.
Finally, we want to start up uWSGI when the system boots. Create a systemd service file at /
etc/systemd/system/emperor.uwsgi.service with the following content:
[Unit] Description=uwsgi emperor for micro domains website After=network.target [Service] User=udoms Restart=always ExecStart=/home/udoms/env/md/bin/uwsgi --emperor /home/udoms/env/md/vassals --uid www-data --gid www-data [Install] WantedBy=multi-user.target
Enable the service to allow it to execute on system boot and start it so you can test it without a reboot.
systemctl enable emperor.uwsgi.service systemctl start emperor.uwsgi.service
Visit a browser and you will see the default Django landing page if everything works correctly.
Check the status of the service and stop it as follows:
systemctl status emperor.uwsgi.service systemctl stop emperor.uwsgi.service
For good measure, reboot your system to make sure that your website is accessible at startup.
Before going public with your website, it is highly recommended that you configure a few additional Django settings.
Please let me know if you have any questions about setting up Django with Nginx and uWSGI.
30 thoughts on “How to Set Up Django on Nginx with uWSGI”
hey man, my url just apear nginx page i dont know whats whrong, can you helpe me?
Seems like the default Nginx landing page is still being served. This tells me that one of the following is true:
1.) You have multiple Nginx config files and the default is overriding your new one
2.) You need to reload Nginx for your config changes to take effect
3.) You haven’t symlinked your config in sites-available to sites-enabled
hello i’ve gone through all the steps though im encountring an error when i start the nginx server :
pam_unix(sudo:auth): Couldn’t open /etc/securetty: No such file or directory
please help
I’m not familiar with securetty. Are you? Is this a typo for security?
what must to write in /etc/nginx/nginx.conf file. first it listens :80 in nginx.conf, not in sites-available/microdomains.conf. is cause of linux server?
I’m sorry, can you rephrase your question?
I don’t have a setting I skipped, but I see the nginx page. django is not shown. Which part should I check again?
Is your Django server running on port 80 and/or is your Nginx config file set up to listen on port 80?
/etc/nginx/sites-available/microdomains.conf
the problem starts after this step
Your Nginx configuration file will be named something other than microdomains.conf
If you are using CentOS system, make *.conf files inside /etc/nginx/conf.d/ directory.
Refer this if needed :
For ubuntu based systems mentions steps in the video works flawless.
Thanks for sharing this info Tony, helped a lot in server config.
Great post, everything is working, thank you very much for this!
Good morning!
This was a great post. It helped me a lot and I thank you so much.
However, from step 5 onwards the domain name stopped redirecting to my website and I could only access it from the VPS’s IP address. Do you know why this problem might be happening? I have checked my spelling of the domain inside the nginx conf files and everything appears to be ok.
Sorry Felipe, I’m not sure why that would be happening
Ok, I kind of have figured out what has happened. It seems I have to clear the cache and flush the DNS configuration of my local machine after I have accessed the site using the IP address.
Tony, once again, thank you for this tutorial.
There is one more error that is coming up to me when I make my Django application open a text file inside Python. I use the Python command ‘open’ inside views.py and, in order to avoid path related issues, I also use os and pathlib. When I run the application through the Django server at port 8000, everything works fine. However, when I run the server with the Nginx and uWSGI server, this error occurs.
I think it might have to do with the server user permissions, but I have tried to chmod and chown the file folder with no success. I would be very glad if you could give me an insight on how to fix this problem.
What is the error message?
I could not find the error message. Which file should I tail in order to get the error messages as I would get running the Django server directly?
I know that the code stops at this part because I used the “print” command several times until I had found the statement that was causing the error.
Hey Tony. This lesson has been a life saver. Thankyou very much! I was wondering if you have some advice for using multiple domain names, and pointing them to specific apps in my Django project. I am missing something.
hey tony thanks for the great and simplified tutorial I’ve followed your tutorial on ubuntu server 20.04 and everything worked fine, I created the service and it worked and the status was running after i rebooted the machine I received “502 Bad Gateway nginx/1.18.0 (Ubuntu)” I checked the status of the service it’s running, am I missing something
Hi Fady, please see if the suggestions in this video help you fix the 502 error
When I run sudo nginx -t -c /etc/nginx/sites-available/na_backend.conf it says upstream is not allowed here
Hey, any idea how to enable –enable-threads
I had the same doubt. I was trying to shedule function using APSheduler. But it fails because django unable to create multiple thread because of uwsgi. Any Suggestions?
Hello Tony,
I used you tutorial to deploy Odoo ERP System, and I succeeded to load the project under uWSGI. But I have a problem with “uwsgi request is too big:XXX”.
My Deployment stack for Odoo ERP 12 :
#Python 3.7.10 and Werkzeug 0.16.1
#Nginx 1.20.0 #uWSGI 2.0.19.1 #FreeBSD 13.0-REL
Nginx throw an alert : “uwsgi request is too big: 81492 GET /……..”
I increased the “uwsgi_buffer_size ” in both uwsgi and nginx, but without any success
How to do a large buffer size (> 64k) uWSGI requests with Nginx proxy.
This is the issue that I openned on uWSGI github
Can you please take a look and help me to solve this problem
Thanks.
hello Mr.Tony,
first of all i really appreciate your effort of making this video but i got 502 bad gatway error,
i followed all steps as you mentioned in this blog
i can see my site only if i run this
“uwsgi –socket microdomains.sock –module microdomains.wsgi –chmod-socket=666″
i think nginx service was not running
and i used this command
sudo tail -f /var/log/nginx/error.log
to see the error logs
and i got
”
2021/06/07 18:51:49 [error] 9612#9612: *1 connect() to unix:///home/developer/bharathwajan/bharathwajan.sock failed (111: Connection refused) while connecting to upstream, client: 157.49.92.156, server: apothecary-re.com, request: “GET / HTTP/1.1”, upstream: “uwsgi://unix:///home/developer/bharathwajan/bharathwajan
”
i saw your video “”
but that doesn’t work for me
if you are ok to fix this error on teamviewer i can pay you around 10 to 14$ ,i know that was a less amount but mine is not a big budget project it was my personal project , if you are ok then mail me
i forgot to say that i cloned my project from my github repo,and used postgresql with it
Did you get a solution? I have the same error
Hi Tony, i m Fernando from Argentina, i did all steps and all looks good.
The server is running fine with django-nginx-uwsgi in a service (emperor mode working)
I’m having another problem, i want to host a site from home, and when i register mi syte with a dns server, i dont know what ip to put in the A record, the modem of my service has an ip like 126.100.66.xx, but when i search internet for my public ip i find another ip like 186.22.19.xx
I did the port forwarding in the modem for the ports 80 y 22 to the local ip of my webserver…
Sorry about my english, my native language is spanish.
Your channel is the best, so plz still going on it!!!
You will want to use the public IP address that is reported by the website 186.22.19.xx | https://tonyteaches.tech/django-nginx-uwsgi-tutorial/ | CC-MAIN-2021-31 | refinedweb | 2,973 | 64.91 |
Norbert Unterberg <nepo <at> gmx.net> writes:
> There remains an issue with the DIFFs. I have setup a diff.exe from the
> GnuWin32 tools which works with the command line from
> mailer.conf.example. The diffs are added to the commit mails.
> BUT: Each line from the diff contains an extra CRLF pair.
I saw the same extra lines in the emailed diffs. I don't know if this is
the correct fix or not, but changing the popen2/popen4 modes to text
instead of binary worked for me...
regards,
markt
Index: mailer.py
===================================================================
--- mailer.py (revision 12828)
+++ mailer.py (working copy)
@@ -107,9 +107,9 @@
cmd = argv_to_command_string(cmd)
if capturestderr:
self.fromchild, self.tochild, self.childerr \
- = popen2.popen3(cmd, mode='b')
+ = popen2.popen3(cmd, mode='t')
else:
- self.fromchild, self.tochild = popen2.popen2(cmd, mode='b')
+ self.fromchild, self.tochild = popen2.popen2(cmd, mode='t')
self.childerr = None
def wait(self):
@@ -123,7 +123,7 @@
def __init__(self, cmd):
if type(cmd) != types.StringType:
cmd = argv_to_command_string(cmd)
- self.fromchild, self.tochild = popen2.popen4(cmd, mode='b')
+ self.fromchild, self.tochild = popen2.popen4(cmd, mode='t')
def wait(self):
rv = self.fromchild.close()
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Sun Jan 23 22:33:14 2005
This is an archived mail posted to the Subversion Dev
mailing list. | http://svn.haxx.se/dev/archive-2005-01/0908.shtml | CC-MAIN-2014-52 | refinedweb | 233 | 63.66 |
In python3, how do I match exactly whitespace character and not newline \n or tab \t?
I've seen the
\s+[^\n]
a='rasd\nsa sd'
print(re.search(r'\s+[^ \n]',a))
<_sre.SRE_Match object; span=(4, 6),
If you want to match 1 or more whitespace chars except the newline and a tab use
r"[^\S\n\t]+"
The
[^\S] matches any char that is not a non-whitespace = any char that is whitespace. However, since the character class is a negated one, when you add characters to it they are excluded from matching.
import re a='rasd\nsa sd' print(re.findall(r'[^\S\n\t]+',a)) # => [' ']
Some more considerations:
\s matches
[ \t\n\r\f\v] if ASCII flag is used. So, if you plan to only match ASCII, you might as well use
[ \r\f\v] to exclude the chars you want. If you need to work with Unicode strings, the solution above is a viable one. | https://codedump.io/share/6MPp8JJQn1P0/1/python-regex-match-space-only | CC-MAIN-2017-09 | refinedweb | 162 | 73.47 |
QSORT(3P) POSIX Programmer's Manual QSORT(3P)
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
qsort — sort a table of data
#include <stdlib.h> void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));
The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2017. The following sections are informative.-zero: ((char *)p - (char *)base) % width == 0 (char *)p >= (char *)base (char *)p < (char *)base + nel * width
None.
alphas QSORT(3P)
Pages that refer to this page: stdlib.h(0p), alphasort(3p), bsearch(3p) | https://man7.org/linux/man-pages/man3/qsort.3p.html | CC-MAIN-2021-04 | refinedweb | 143 | 58.48 |
Hello,
most of the functionality of the .NET Framework are only wrapper classes around old COM+ components. Is there a chance to get a .NET Framework with mostly managed code inside ? Because COM+ is old and bad designed technology -> and it is not interoperable.
Is there a chance for a better future with .NET ?
Is there a better solution (less COM+) in the .NET Framework 2.0 ?
Hello,
I really can't answer to how much is a wrapper around an existin COM component and how much is not but I would tend to guess that it's probably less then you suspect but I'll let a MS guy (or more knowledgable person) answer that. MS has made a lot of past investments (as many other companies have) in COM so I don't think you're going to see it go away over night but it seems like it eventually will.
For clarification when you're refering to COM+ it seems like you really mean COM. COM is the Component Object Model where COM+ is the distributed transaction/messaging middleware product from MS which translates to a specific portion of the .Net framework call Enterprise services and yes Enterprise services does indeed have a lot of COM interop going on to interact with COM+ but this is only a very small portion of the .NET framework. Enterprise Services and COM+ is only used in very specific circumstances when you need some functionality that only COM+ offers "out of the box" such as distributed transactions but I would tend to wager that you will not find it in a majority of .NET apps out there.
I think the future is very bright for .NET IMO and to answer your question about a better solution in future version of the framework for COM+ (I always get confused if its in .NET framework 2.0 or longhorn) yes there will be services available for tasks that COM+ does today in native .NET, I believe the current "codename" for it is Indigo.
Hope this helps.
Josh
My understanding is that the MFC is the largest amount of unmanaged code that goes in. From memory that's, what, 5000 classes? That might be a touch high, but that still leaves 10-15K that are managed. Far from most.
Still, you're right, the MFC is a pig to work with (no offence, I'm glad it's there though!). I'm relatively sure the MFC will stay there for a while. It's not like you have to use the MFC components for all but the most ... unique apps.
Again, this is my understanding.
I wouldn't say "most" of the framework is a COM+ wrapper.
99% of the framework classes that wrap COM+ functionality reside in the System.EnterpriseServices namespace, which is just a small fraction of the overall framework.
That´s wrong ! For example see System.Web.Mail -> it uses the COm component called CDO coming from Windows 2000 or so.
You can see that VERY much functionality is encapsulated in OLD COM objects - NOT on the new .NET technology ! Not interoperable ! It´s the M$ lie.
The story I've been told is not that COM has gone away. Just that in a best case scenario you won't have to worry if, when, and how COM does go away.
But how can M$ make a comparision with a programming language like Java if they are using COMs?
It is not platform independent, ... -> do not think about the projects Mono and DotGNU -> these framework are different implementations.
I think M$ had time trouble and therefore a "quick-and-dirty" solution has been made to have a new technology "like Java".
But they earn their money with this ! -> alot of money for servers, VS, ...
Why pay alot for a bad product ? And you say I don´t have to worry about ?
My personal guess is that the platform independency is mostly a marketing thing. I don't expect it to fly. I've been very sceptical about all platform independency claims since I got burned by the Java Applets write-once-debug-everywhere problem. I view the Framework as an improved environment for me to write windows applications and webapps running on Microsoft Servers. Everything else is just frosting on the cake. But that's just my very personal view of things.
And remember: Emulation Is The Sincerest Form Of Flattery.
I'm not a java programmer and I know very little about Java so I'm not going to claim to know much about it by it seems that MS (and other vendors including Sun, IBM,etc) are speaking in terms of web services for interopability now days and not Java's "write once run everywhere" or whatever it's slogan is. You want MS to talk to IBM that talks to Sun that talks to a commodore 64 it seems the current "trend" is to think web services and not <insert platform independant language here> and all the major players are making heavy investments in this technology.
Now depending on your OS and your companies developers you can choose Java or .NET or whatever you want to get you there and they're all going to offer you good solutions (well maybe not the commodore but you got the point). In short who gives a crap about platform independance as long as long as they can speak to each other (web services). Now I know that there are issues that you need to consider when having afor example a java application consume a .Net Web service and it's not a perfect utopian solution but they are well documented and easily workable and with all the work now being done between MS, IBM, and sun I think you'll see even this get smoother. To say that .NET can't compete with Java because it's not platform independant is implying that the most important factor of both languages is the platform independance and that isn't the case and is not a valid comparison for either language.
Going back to the how much of .NET is COM wrapped up I don't think you can go look enterprise services and webmail and say "hey look it's all just COM with a face lift" because that's just not the case. Yes you will find area's that interact or wrap COM components but even so does that neccesarily make it a bad thing? I don't think so. I heard from an MS guy somewhere (Don Box maybe?) that COM isn't dead it's just done. MS isn't going to invest any more in COM they're going to push forward with .NET so you will see less and less "COM" behind the scenes and more native .NET and whatever your doing behind the scenes if you need to talk to another system your going to use web services.
With the massive amounts of dollars, developers, and time that MS is put into .NET I think the last thing it could be considered is "a down and dirty" solution lol. But yes in the end they do earn money from it, and I'll earn money from it, and lots of companies and people will earn money from it... its what makes the world go around.
But to be honest it sounds like you know about as much about .NET and COM as I know about java
Regards,
Josh
A look at rotor may be enlightening...
It would be really nice if the license of rotor would allow for commercial use. I believe that not only would that open up developers to BSD but I believe apple's OSX too? maybe someday.
Josh
I´m programming .NET since the 1.0 Beta 2. And I want to say that I found alot of COM components used in the complete framework. I´ve given only an example with the System.Web.Mail CDO component. Or do you want a complete list ?
I think you are only programming with .NET and you doesn´t look behind the scenes. Please take a look at the "Reflector" (Lutz Roeder) program to see the implementation of the Framework classes. Or the Rotor source.
For example: I´ve developed a universal Data Access component. Because I think it is bad to use the SqlClient, OracleClient, ... If you change the DBMS system you have to change the whole program code. I´ve seen that in java it is a better solution and implemented it. In the 2.0 Framework it is implemented by default. But you say today that the 1.1 Framework is good designed. I think it is the first (1.x) version and it can be improved.
First: Each successive version of the framework uses less and less COM. But re-writing everything from the start would have been project suicide. It would simply have taken too long to build it all in managed code from the start.
Second: Who gives a damn? C# is giving me the productivity gains of VB (well, almost. Edit-and-continue please, edit-and-frigging-continue) with a language I'm more comfortable in.
It can be a wrapper around DDE for all I care. Hell, go ahead and make it a collection of TSRs if that is what works.
What I want is a layer of abstraction that helps me be more productive. What that layer consists of is for people with offices and pay-scales far above mine to determine.
I agree with unix (the channel9 member) to an extent, the wrapping of COM functionality was one of the things that turned me away from .Net in the first release. It's not simply that COM is wrapped, but that this is a "Revolution"! You've got to be kidding me... is there an "Idiot" label on my forhead? Now... (whew, I've been waiting a while to get that out... NICE) I do realize that much of the functionality that is dependant on old COM stuff is going away with each new revision (or service pack or whatever). But the fact is that, you stand and tell me about a revolution, then hand me the same thing I already have with a new coat of paint. This obvviously onle applies to the Foundation Classes, not C#, the CLR or any of that... but its the principle of the matter. You want me to stand in the trenches and argue J2EE vs. .Net with my colleagues (and to my managers), give me the truth, not the hype.
Unix? I would like to hear more about your universal data access component, and comparative performance with SqlClient and perhaps OracleClient. You can be completely platform agnostic if you want, but IMO that is one reason Java has failed to produce GUI applications of any magnitude that perform well.
As far as Java GUI applications that perform well... I think you may want to look again. This has imporved greatly in Java2... check out IntelliJ at , its fully swing and works marvelously. The intellisense popups are quick. At least on my sluggish Mac
Granted, you need some RAM, but run VS.Net with only 256 of RAM and you get a very similar result.
How would you say it performs to say, Eclipse? I think IBM got it right with SWT.. but truthfully I haven't run a pure swing app in a while. The IDE looked pretty good, do you have any other examples?
JParrish, Well, I think it performs better than Eclipse, but unfortunately, I can't quantify it, so you'll have to take that with as (with?) grain of salt. I don't think eclipse is all Swing based though. But I am by no means an *informed* Eclipse user. Let me see what else I've got running here regards other examples.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know. | https://channel9.msdn.com/Forums/Coffeehouse/981-NET-Framework-Future- | CC-MAIN-2015-27 | refinedweb | 2,028 | 74.39 |
.
Amazon Web Services (AWS) for example—but in fact, almost any cloud provider—demonstrates these principles very effectively. When an application needs a feature or mechanism that AWS doesn’t offer, the choices are:.
As somebody not lucky enough to have a nice clicky interface with which to manage and automate all my equipment, I have to develop my own tools to do so. One aspect of developing those tools that drives me up the wall is the variety of mechanisms I have to support to communicate with the various devices deployed in the network. Why can’t we have one, consistent way to manage the devices?
I can already hear voices saying “But we have SSH. SSH is available on almost all devices. Is that not the consistency you desire?” No, it isn’t. In terms of configuring network devices, SSH is just a(n encrypted) transport mechanism and provides no help whatsoever with configuring the devices. Once I’ve connected using SSH, I have to develop the appropriate customized code to screen-scrape the particular operating system I connect to. Anybody who has done this will testify that this is not particularly straightforward and, worse, the reward for doing so is to be able to issue commands and receive, in return, wads of unstructured data (i.e., command output) which can change between code versions, making parsing a nightmare.
So here’s my first requirement: structured data.
Typical command line output blurts out the requested information in such a way that the surrounding label text and the position of a piece of text impart the information necessary to infer what the text itself represents. Decoding data in this format usually means developing regular expressions to identify and pull apart the text so that the constituent data can be processed. Identification of data is implicit, based on contextual clues. Unstructured data is nice (or a least tolerable) for a human to look at and make sense of, but is frequently very difficult to interpret in code.
Structured data, on the other hand, follows a specific set of rules to present the data points such that they are explicitly and unambiguously identified and labeled for consumption by code. Structured data usually presents data in a way that mimics programmatic hierarchical data structures, which lends itself to easy integration into code.
Junos has historically favored XML for structured data, but — subjectively — I would argue that XML is ugly and can get complex very quickly, especially where multiple namespaces are being used. Personally I have a soft spot for JSON, and I know other people like YAML, but ultimately I’m at the point where I’d say “I don’t care, just pick one and stick with it,” so that I can focus my time and effort on handling the one format.
So here’s my second requirement: consistent encoding.
Once we have a way to encode the data in structured format, we then need to be more consistent about what’s being encoded. Again, this may point at a project like OpenConfig, but failing that, perhaps it might be worth it if everything could be described using YANG. By default, YANG maps to XML, but RFC7951 (JSON Encoding of Data Modeled With YANG) helpfully shows how my pet preference JSON can be used instead.
The point here is that if YANG is used, the mapping to JSON or XML is almost a side issue, so long as the data is modeled in YANG to start with; both XML and JSON fans can translate from YANG to their favorite encoding and—and this is the key part—so can the devices, so clients can request the encoding of their choice.
So now that I’ve determined that we need YANG models with support for both JSON and XML encoding, optionally following a common OpenConfig data model, let’s address how we communicate with the devices.
I don’t want to have to figure out what kind of device I’m connecting to, then based on that information, decide what connection transport I should be using (e.g., HTTP, HTTPS, SSH possibly on a non-standard TCP port). What I want to be able to do is to connect to the device in a standard way on a standard port. I don’t mind reconnecting to a non-standard port, but I want to be told about that port after I connect to the standard port.
That’s my third requirement: one transport for all.
OpenConfig takes this approach, by having a “well-known” URL on the device to report back information about the device and connection details in a standard format. I’d like to take it a step further, though.
Let’s use a REST API for all this communication. REST APIs are ubiquitous now; every programming language has the ability to send and receive requests over HTTP(S) and to decode the XML/JSON responses. It makes things easy!
My last requirement: access via REST API.
Wait a moment, let me check again:
I believe I’ve accidentally just defined RESTCONF (RFC8040), whose introductory paragraph reads:
“[...] an HTTP-based protocol that provides a programmatic interface for accessing data defined in YANG, using the datastore concepts defined in the Network Configuration Protocol (NETCONF).”
I am not a huge fan of NETCONF/XML over SSH, but NETCONF/JSON over HTTP? Count me in!
Automating the infrastructure is hard enough without battling against multiple protocols. How about we just all agreed that RESTCONF is a good compromise and start supporting it across all devices?
For what it’s worth, there is some level of RESTCONF support in more recent software releases, including:
But here’s the problem: when did you last hear of anybody trying to automate with RESTCONF?
That’s what I’d like to see. What about you?
I’ve heard repeatedly from people in this industry that what we need is a single interface to our infrastructure. For status monitoring, perhaps that’s best represented by the ubiquitous “Single Pane of Glass” (Drink!); for general network management, perhaps it’s a Manager of Managers (MoM); and for infrastructure configuration it’s, well, that’s where it gets tricky.
I was once hopeful of a future where I could configure and monitor any network device I wanted using a standardized operational interface, courtesy of the efforts of OpenConfig. If you’ve not heard of this before, you can check out an introduction to OpenConfig I wrote in early 2016. However, after a really promising start with lots of activity, OpenConfig appears to have gone dark; there are no updates on the site, the copyright notice still says 2016, the latest “News” was a 2015 year-end round-up, and there’s really little to learn about any progress that might have been made. OpenConfig is a mysterious and powerful project, and its mystery is only exceeded by its power.
I mention OpenConfig because one of the biggest battles that project faced was to to reconcile the desire for consistency across multiple vendors’ equipment while still permitting each vendor to have their own proprietary features. Looking back, SNMP started off the right way too by having a standard MIB where everybody would store, say, network information, but it became clear quite quickly that this standard didn’t support the vendors’ needs sufficiently. Instead, they started putting all the useful information in their own data structures within an Enterprise MIB specific to the vendor’s implementation. Consequently, with SNMP, the idea of commonality has almost been reduced to being able to query the hostname and some very basic information. If OpenConfig goes the same way, then it will have solved very little of the original problem.
Puppet faces a similar problem in that its whole architecture is based on the idea that you can tell any device to do something, and not need to worry about how it’s actually accomplished by the agent. This works well with the basic, common commands that apply to all infrastructure devices (say, configuring an access VLAN on a switchport), but the moment things get vendor-specific, it gets more difficult.
It should therefore be fairly obvious that to write a tool that can fully automate a typical homogeneous infrastructure (that is, containing a mix of device types from multiple vendors) is potentially an incredibly steep task. Presenting a heterogeneous-style front end to configure a homogeneous infrastructure is tricky at best, and to create a single, bespoke tool to accomplish this would require skills in every platform and configuration type in use. The fact that there isn’t even a common transport and protocol that can be used to configure all the devices is a huge pain, and the subject of another post coming soon. But what choice do we have?
One of solutions I proposed to the silo problem is for each team to provide documented APIs to their tools so that other teams can include those elements within their own workflows. Most likely, within a technical area, things may work best if a similar approach is used:
Arguably the Translation API could itself contain the device-specific code, but there’s no getting around the fact that each vendor’s equipment will require a different syntax, protocol, and transport. As such, that complexity should not be in the orchestration tools themselves but should be hidden behind a layer of abstraction (in this case, the translation API). In this example, the translation API changes the Cisco spanning-tree “portfast” into a more generic “edge” type:
There’s also no way to avoid the exact problem faced by OpenConfig, that some vendors, models, features, or licenses, will offer capabilities not offered by others. OpenConfig aimed to make this even simpler, by pushing that Translation API right down to the device itself, creating a lingua franca for all requests to the device. However, until that glorious day arrives, and all devices have been upgraded to code supporting such awesomeness, there’s a stark fact that should be considered:
Most automation in homogeneous environments will, by necessity, cater to the lowest common denominator.
Let’s think about that for a moment. If we want automation to function across our varied inventory, then the fact that it ends up catering to the lowest common denominator means that it should be possible to deploy almost any equipment into the network, because the fancy proprietary features aren’t going to be used by automation. While that sounds dangerously like ad-copy for white box switching, the fact remains that if any port on the network can be configured the same way (using an API) then the reality of which hardware is deployed in the field is only a matter of whether or not a device-specific API can be created to act as middleware between the scripts and the device. That could almost open up a whole new way of thinking about our networks...
Will we end up dumbing down our networks to allow this kind of heterogeneous operation of homogeneous networks? I don’t know, but it seems to me that as soon as there’s a feature disparity between two devices with a similar role in the network, we end up looking right back at the LCD.
I’m a fan of creating abstractions to abstractions, so that—as much as possible—the dirty details are hidden well out of sight. And while it would be lovely to think that all vendors will eventually deploy a single interface that our tools can talk to, until that point, we’re on the hook to provide those translations, and to build that common language for our configuration and monitoring needs.
Qu'est-ce qui pourrait mal se passer? configuration backups every day!
Why is it that the server team seems to have gotten their act together while the network team is still working the same way they were twenty years ago?
To clarify the issue described, for many companies, the instantiation of the company's
network policy is the configuration currently active on the network devices. To understand a full security policy, it's necessary to look at the configuration configuration configuration configurations.
How do you manage the expectations that devices are implementing the policies they were intended to, and do not become an ever-changing source of truth for the intended policy? How do you push configurations to your devices, or does that idea scare you or seem impossible to do? If automation means swapping the CLI for a GUI, are on on board?
Please let me know; I hope to see a light at the end of the tunnel (and I hope it's not an oncoming train).
I am fascinated by the fact that in over twenty years, the networking industry still deploys firewalls in most of our networks exactly the way it did back in the day. And for many networks, that's it. The reality is that the attack vectors today are different from what they were twenty years ago, and we now need something more than just edge security.
Listeners to the Packet Pushers podcast may have heard the inimitable Greg Ferro expound on the concept that firewalls are worthless at this point because the cost of purchasing, supporting, and maintaining them exceeds the cost to the business of any data breach that may occur as a result. To some extent, Greg has a point. After the breach has been cleared up and the costs of investigation, fines, and compensatory actions have been taken into account, the numbers in many cases do seem to be quite close. With that in mind, if you're willing to bet on not being breached for a period of time, it might actually be a money-saving strategy to just wait and hope. There's a little more to this than meets the eye, however.
It's all very well to argue that a firewall would not have prevented a breach (or delayed it any longer than it already took for a company to be breached), but I'd hate to be the person trying to make that argument to my shareholders, or (in the U.S.) the Securities Exchange Commission or the Department of Health and Human Services, to pick a couple of random examples. At least if you have a firewall, you get to claim "Well, at least we tried." As a parallel, imagine that two friends have their bicycles stolen from the local railway station where they had left them. One friend used a chain and padlock to secure their bicycle, but the other just left their bicycle there because the thieves can cut through the chain easily anyway. Which friend would you feel more sympathy for? The chain and padlock at least raised the barrier of entry to only include thieves with bolt cutters.
Greg's assertion that firewalls are not needed does have a subtle truth to it -- if it's coupled with the idea that some kind of port-based filtering at the edge is still necessary. But perhaps it doesn't need to be stateful and, typically, expensive. What if edge security was implemented on the existing routers using (by definition, stateless) access control lists instead? The obvious initial reaction might be to think, "Ah, but we must have session state!" Why? When's the last TCP sequence prediction attack you heard of? Maybe it's a long time ago, because we have stateful firewalls, but maybe it's also because the attack surface has changed.
Once upon a time, firewalls protected devices from attacks on open ports, but I would posit that the majority of attacks today are focused on applications accessed via a legitimate port (e.g. tcp/80 or tcp/443), and thus a firewall does little more than increment a few byte and sequence counters as an application-layer attack is taking place. A quick glance at the OWASP 2017 Top 10 List release candidate shows the wide range of ways in which applications are being assaulted. (I should note that this release candidate, RC1, was rejected, but it's a good example of what's at stake even if some specifics change when it's finally approved.)
If an attack takes place using a port which the firewall will permit, how is the firewall protecting the business assets? Some web application security might help here too, of course.
Another change which has become especially prevalent in the last five years is the idea of using distributed security (usually firewalls!) to move the enforcement point down toward the servers. Once upon a time, it was sometimes necessary to do this simply because centralized firewalls simply did not scale well enough to cope with the traffic they were expected to handle. The obvious solution is to have more firewalls and place them closer to the assets they are being asked to protect.
Host-based firewalls are perhaps the ultimate in distributed firewalls, and whether implemented within the host or at the host edge (e.g. within a vSwitch or equivalent within a hypervisor), flows within a data center environment can now be controlled, preventing the spread of attacks between hosts. VMWare's NSX is probably the most commonly seen implementation of a microsegmentation solution, but whether using NSX or another solution, the key to managing so many firewalls is to have a front end where policy is defined, then let the system figure out where to deploy which rules. It's all very well spinning up a Juniper cSRX (an SRX firewall implemented as a container) for example, on every virtualization host, but somebody has to configure the firewalls, and that's a task, if performed manually, that would rapidly spiral out of control.
Containers bring another level of security angst too since they can communicate with each other within a host. This has led to the creation of nanosegmentation security, which controls traffic within a host, at the container level.
Distributed firewalls are incredibly scalable because every new virtualization host can have a new firewall, which means that security capacity expands at the same rate as the compute capacity. Sure, licensing costs likely grow at the same rate as well, but it's the principal that's important.
Extending the distributed firewall idea to end-user devices isn't a bad idea either. Imagine how the spread of a worm like wannacry could have been limited if the user host firewalls could have been configured to block SMB while the worm was rampant within a network.
In God we trust; all others must pay cash. For all the efforts we make to secure our networks and applications, we are usually also making the assumption that the hardware on which our network and computer runs is secure in the first place. After the many releases of NSA data, I think many have come to question whether this is actually the case. To that end,
trusted platforms have become available, where components and software are monitored all the way from the original manufacturer through to assembly, and the hardware/firmware is designed to identify and warn about any kind of tampering that may have been attempted. There's a catch here, which is that the customer always has to decide to trust someone, but I get the feeling that many people would believe a third-party company's claims of non-interference over a government's. If this is important to you, there are trusted compute platforms available, and now even some trusted network platforms with a similar chain of custody-type procedures in place to help ensure legitimacy.
The good news is that security continues to be such a hot topic that there is no shortage of options when it comes to adding tools to your network (and there are many I have chosen not to mention here for the sake of brevity). There's no perfect security architecture, and whatever tools are currently running, there's usually another that could be added to fill a hole in the security stance. Many tools, at least the inline ones, add latency to the packet flows; it's unavoidable. In an environment where transaction speed is critical (e.g. high-speed trading), what's the trade off between security and latency?
Does this mean that we should give up on in-depth security and go back to ACLs? I don't think so. However, a security posture isn't something that can be created once then never updated. It has to be a dynamic strategy that is updated based on new technologies, new threats, and budgetary concerns. Maybe at some point, ACLs will become the right answer in a given situation. It's also not usually possible to protect against every known threat, so every decision is going to be a balance between cost, staffing, risk, and exposure. Security will always be a best effort given the known constraints.
We've come so far since the early firewall days, and it looks like things will continue changing, refreshing, and improving going forward as well. Today's security is not your mama's security architecture, indeed.!.
As a network engineer, I don't think I've ever had the pleasure of having every device configured consistently in a network. But what does that even mean? What is consistency when we're potentially talking about multiple vendors and models of equipment?
Claim: For any given model of hardware there should be one approved version of code deployed on that hardware everywhere across an organization.
Response: And if that version has a bug, then all your devices have that bug. This is the same basic security paradigm that leads us to have multiple firewall tiers comprising different vendors for extra protection against bugs in one vendor's code. I get it, but it just isn't practical. The reality is that it's hard enough upgrading device software to keep up with critical security patches, let alone doing so while maintaining multiple versions of code.
Why do we care? Because different versions of code can behave differently. Default command options can change between versions; previously unavailable options and features are added in new versions. Basically, having a consistent revision of code running means that you have a consistent platform on which to make changes. In most cases, that is probably worth the relatively rare occasions on which a serious enough bug forces an emergency code upgrade.
Corollary: The approved code version should be changing over time, as necessitated by feature requirements, stability improvements, and critical bugs. To that end, developing a repeatable method by which to upgrade code is kind of important.
Claim: Every device type should have a baseline template that implements a consistent management and administration configuration, with specific localized changes as necessary. For example, a template might include:
(*) There are those who would argue, quite successfully, that such a local account should have a password unique to each device. The password would be extracted from a secure location (a
break glass type of repository) on demand when needed and changed immediately afterward to prevent reuse of the local account. The argument is that if the password is compromised, it will leave all devices susceptible to accessibility. I agree, and I tip my hat to anybody who successfully implements this.
Response: Local accounts are for emergency access only because we all use a centralized authentication service, right? If not, why not? Local accounts for users are a terrible idea, and have a habit of being left in place for years after a user has left the organization.
NTP is a must for all devices so that syslog/SNMP timestamps are synced up. Choose one timezone (I suggest UTC) and implement it on your devices worldwide. Using a local time zone is a guaranteed way to mess up log analysis the first time a problem spans time zones; whatever time zone makes the most sense, use it, and use it everywhere. The same time zone should be configured in all network management and alerting software.
Other elements of the template are there to make sure that the same access is available to every device. Why wouldn't you want to do that?
Corollary: Each device and software version could have its own limitations, so multiple templates will be needed, adapted to the capabilities of each device.
Claim: Pick a device naming standard and stick with it. If it's necessary to change it, go back and change all the existing devices as well.
Response: I feel my hat tipping again, but in principle this is a really good idea. I did work for one company where all servers were given six-letter dictionary words as their names, a policy driven by the security group who worried that any kind of semantically meaningful naming policy would reveal too much to an attacker. Fair play, but having to remember that the syslog servers are called WINDOW, BELFRY, CUPPED, and ORANGE is not exactly friendly. Particularly in office space, it can really help to be able to identify which floor or closet a device is in. I personally lean toward naming devices by role (e.g. leaf, access, core, etc.) and never by device model. How many places have switches called
Chicago-6500-01 or similar? And when you upgrade that switch, what happens? And is that 6500 a core, distribution, access, or maybe a service-module switch?
Corollary: Think the naming standard through carefully, including giving thought to future changes.
There are more areas that could and should be consistent. Maybe consider things like:
But why bother? Consistency brings a number of obvious operational benefits.
The only way to know if the configurations are consistent is to define a standard and then audit against it. If things are set up well, such an audit could even be automated. After a software upgrade, run the audit tool again to help ensure that nothing was lost or altered during the process.
What does your network look like? Is it consistent, or is it, shall we say, a product of organic growth? What are the upsides -- or downsides -- to consistency like this?
You!
In this post, part of a miniseries on coding for non-coders, I thought it might be interesting to look at a real-world example of breaking a task down for automation. I won't be digging hard into the actual code but instead looking at how the task could be approached and turned into a sequence of events that will take a sad task and transform it into a happy one.
Deploying a new VLAN is simple enough, but in my environment it means connecting to around 20 fabric switches to build the VLAN. I suppose one solution would be to use an Ethernet fabric that had its own unified control plane, but ripping out my Cisco FabricPath™ switches would take a while, so let's just put that aside for the moment.
When a new VLAN is deployed, it almost always also requires that a layer 3 (IP) gateway with HSRP is created on the routers and that VLAN needs to be trunked from the fabric edge to the routers. If I can automate this process, for every VLAN I deploy, I can avoid logging in to 22 devices by hand, and I can also hopefully complete the task significantly faster.
Putting this together, I now have a list of three main steps I need to accomplish:
Much in the same way that one uses modules when coding to avoid rewriting something that has been created already, I believe that the same logic applies to automation. For example, I run Cisco Data Center Network Manager (DCNM) to manage my Ethernet fabric. DCNM has the capability to deploy changes (it calls them Templates) to the fabric on demand. The implementation of this feature involves DCNM creating an SSH session to the device and configuring it just like a real user would. I could, of course, implement the same functionality for myself in my language of choice, but why would I? Cisco has spent time making the deployment process as bulletproof as possible; DCNM recognizes error messages and can deal with them. DCNM also has the logic built in to configure all the switches in parallel, and in the event of an error on one switch, to either roll back that switch alone or all switches in the change. I don't want to have to figure all that out for myself when DCNM already does it.
For the moment, therefore, I will use DCNM to deploy the VLAN configurations to my 20 switches. Ultimately it might be better if I had full control and no dependency on a third-party product, but in terms of achieving the goal rapidly, this works for me. To assist with trunking VLANs toward the routers, in my environment the edge switches facing the routers have a unique name structure, so I was also able to tweak the DCNM template so that if it detects that it is configuring one of those switches, it also adds the VLANs to the trunked list on the relevant router uplinks. Again, that's one less task I'll have to do in my code.
Similarly, to configure the routers (IOS XR-based), I could write a Python script based on the Paramiko SSH library, or use the Pexpect library to launch ssh and control the program's actions based on what it sees in the session. Alternatively, I could use NetMiko which already understands how to connect to an IOS XR router and interact with it. The latter choice seems like it's preferable, if for no other reason than to speed up development.
DCNM has a REST API through which I can trigger a template deployment. All I need is a VLAN number and an optional description, and I can feed that information to DCNM and let it run. First, though, I need the list of devices on which to apply the configuration template. This information can be retrieved using another REST API call. I can then process the list, apply the VLAN/Description to each item and submit the configuration "job." After submitting the request, assuming success, DCNM will return the JobID that was created. That's handy because it will be necessary to keep checking the status of that JobID afterward to see if it succeeded. So here are the steps so far:
Sound good? Wait; the script needs to login as well. In the DCNM REST API that means authenticating to a particular URL, receiving a token (a string of characters), then using that token as a cookie in all future requests within that session. Also, as a good citizen, the script should logout after completing its requests too, so the list now reads:
That should work for the VLAN creation but I'm also missing a crucial step which is to sanitize and validate the inputs provided to the script. I need to ensure, for example, that:
Maybe the final list looks like this then:
In this example, I'll use Python+NetMiko to do the hard work for me. My inputs are going to be:
As before, I will sanity check the data provided to ensure that the IPs are valid. I have found that IOS XR's configuration for HSRP, while totally logical and elegantly hierarchical, is a bit of a mouthful to type out, so to speak, and as such it is great to have a script take the basic information like a subnet, and apply some standard rules to it (e.g. the 2nd IP is the HSRP gateway, e.g. .1 on a /24 subnet), the next address up (e.g. .2) would be on the A router, and .3 would be on the B router. For my HSRP group number, I use the VLAN ID. The subinterface number where I'll be configuring layer 3 will match the VLAN ID also, and with that information I can also configure the HSRP BFD peer between the routers too. By applying some simple standardized templating of the configuration, I can take a bare minimum of information from the user and create configurations which would take much longer to create manually and quite often (based on my own experience) would have mistakes in it.
The process then might look like this:
Note that the sequences of actions above have been created without requiring any coding. Implementation can come next, in the preferred language, but if we don't have an idea of where we're going, especially as a new coder, it's likely that the project will go wrong very quickly.
For implementation, I now have a list of tasks which I can attack, to some degree, separately from one another; each one is a kind of milestone. Looking at the DCNM process again:
Perhaps this data comes from a web page but for the purposes of my script, I will assume that these values are provided as arguments to the script. For reference, an
argument is anything that comes after the name of the script when you type it on the command line, e.g. in the command,
sayhello.py John the program
sayhello.py would see one argument, with a value of
John.
This sounds like a perfect opportunity to write a function/subroutine which can take a VLAN ID as its own argument, and will return a boolean (true/false) value indicating whether or not the VLAN ID is valid. Similarly, a function could be written for the description, either to enforce the allowed characters by removing anything that doesn't match, or by simply validating whether what's provided meets the criteria or not. These may be useful in other scripts later too, so writing a simple function now may save time later on.
These five actions are all really the same kind of thing. For each one, some data will be sent to a REST API, and something will be returned to the script by the REST API. The process of submitting to the REST API only requires a few pieces of information:
It should be possible to write some functions to handle GET and POST requests so that it's not necessary to repeat the HTTP request code every time it's needed. The idea is not to repeat code multiple times if it can be more simply put in a single function and called from many places. This also means that fixing a bug in that code only requires it to be fixed in one place.
For the IOS XR configuration, each step can be processed in a similar fashion, creating what are hopefully more manageable chunks of code to create and test.
I really do believe that sometimes coders want to jump right into the coding itself before taking the time to think through how the code might actually work, and what the needs will be. In the example above, I've run through taking a single large task (
Create a VLAN on 20 devices and configure two attached routers with an L3 interface and HSRP) which might seem rather daunting at first, and breaking it down into smaller functional pieces so that a) it's clearer how the code will work, and in what order; and b) each small piece of code is now a more achievable task. I'd be interested to know if you as a reader feel that the task lists, while daunting in terms of length, perhaps, seemed more accomplishable from a coding perspective than just the project headline. To me, at least, they absolutely are.
I said I wouldn't dig into the actual code, and I'll keep that promise. Before I end, though, here's a thought to consider: when is it right to code a solution, and when is it not? I'll be taking a look at that in the next, and final, article in this miniseries..
SolarWinds uses cookies on its websites to make your online experience easier and better. By using our website, you consent to our use of cookies. For more information on cookies, see our cookie policy. | https://thwack.solarwinds.com/community/solarwinds-community/geek-speak/blog/authors/jgherbert | CC-MAIN-2019-26 | refinedweb | 6,067 | 57.91 |
Hi
Are there any Demo template for EPiCommunity for download ?
Thanks
Arik
Hi,
We are working on new demo templates for EPiServer Community which should be finished sometime this fall.
In the mean time there are some examples available if you register on this site,
-- Per
Any movement on this?.. We're EPiserver partners and the source of the working site u mentioned above will do.No need for an auto installer like with the CMS 5 templates Demo packages.. Will that be possible?
Steven
We're on the finishing line.
The Community demo templates will be shipped for Tests next week, Meanwhile everyone is bizzy updating the installation manager and the community core code. As well as fixing up last bits of the demo templates and write documentations/instructions/demo content etc. to create the whole package for a release.
For example for our swedish customers we have an User event next thursday/friday here in Stockholm with community sessions where we demo the new templates. If you're interested about the community demo templates contact your partner manager for further info.
Hi Per
Thanks for the reply.
Is there anyway I can get hold of the beta database and the site source as per?
The installation is a nice to have but not imperative. I could add areas of the site that I need. as long as we have the sln/source and db.
On another note, Please advise if community (Relate+) uses the default episerver db/structure? i.e no 2nd db?
I'm running EPiserver R1 SP3 5.1.422.267
Also on the user profiles. What is the connection between Relate + users(comminuty admin access) vs the episerver users(editmode,admin mode). I have tried to look for material on that. some clarification please..
Hi,
do you want the solution/source of the link sc3demo.nestar.se? or the new templates for relateplus - which are not yet finished for relase?Either way its best to contact one of episerver partners managers and they can arrange something.
About if second db - so no. EPiServer CMS and community share the same database for Relate+.
About User profiles - Episerver Community is using .net 2.0 membership provider for authentication. In documents section and developers guide - look at the first tutorial about user management for some examples. In Relate+ demo templates we tried to minimize the use of episerver community security handling due to major refactoring of thoose classes as of now. E.g. They are moving to a new namespace episerver.common - to be shared between cms and community core. But that is not finish for release yet.
But you will see many news in Episver Community namespaces and functionallity in near future when they get ready for relase.
hope this helps/clarifies.
/Per
also,
EPiServers community "admin" mode is built in as a plugin to EPiServer CMS Edit mode, as of now. Of course future relase will change this. Community admin is accessing the community database tables as episerver cms admin mode access episerver cms database tables.
However, the same user "john doe" will exists in both places - or in fact in several tables. But there is no direct link today between the two except for .net membership provider.
Thanks for your responses. It sheds light on the subject.
the sc3demo.nestar.se solution/source and database will do perfect.
© Episerver 2017 |
About Episerver World | http://world.episerver.com/Modules/Forum/Pages/thread.aspx?id=22962 | CC-MAIN-2017-09 | refinedweb | 568 | 60.01 |
Simple animation not working
Vincent Blake
Greenhorn
Joined: Mar 11, 2013
Posts: 1
posted
Mar 11, 2013 23:25:06
0
Hello, I'm fairly new to
Java
and I've encountered my first problem I can't seem to fix. I've been learning Java from a series of online tutorials and a book, I completed the basic tutorials with a decent to good grasp of what was covered in my opinion. I moved on to some game development tutorials and now I am on animation.
Below is the code I have, everything seems to work properly except the animation I want. I have a couple robot png files that were imported. Using the array in the Animation class, I hoped to flip through the sceneIndex to make it appear that the robots eye color was changing back and fourth. As mentioned, its not working, it only stays at the first sceneIndex and does not switch. Any help would be much appreciated.
I apologize if my code is not easy to read. I also have a class called Screen but I wouldn't think that's needed.
import java.awt.*; import javax.swing.ImageIcon; import javax.swing.JFrame; public class Main { public static void main(String[] args){ DisplayMode dm = new DisplayMode(1366,768,16, DisplayMode.REFRESH_RATE_UNKNOWN); Main m = new Main(); m.run(dm); } private Screen screen; private Image bg; private Animation a; //Load pictures from computer to java and adds scene void loadPics(){ bg = new ImageIcon("C:\\Users\\Fearthreat\\Documents\\NetBeansProjects\\Java24\\res\\bg1.jpg").getImage(); Image eyelander1 = new ImageIcon("C:\\Users\\Fearthreat\\Documents\\NetBeansProjects\\Java24\\res\\eyelander1.png").getImage(); Image eyelander2 = new ImageIcon("C:\\Users\\Fearthreat\\Documents\\NetBeansProjects\\Java24\\res\\eyelander2.png").getImage(); a = new Animation(); a.addScene(eyelander1, 250); a.addScene(eyelander2, 250); } //MAIN ENGINE TO RUN public void run(DisplayMode dm){ screen = new Screen(); try{ screen.setFullScreen(dm, new JFrame()); loadPics(); movieLoop(); }finally{ screen.restoreScreen(); } } //Main movieLoop public void movieLoop(){ long startingTime = System.currentTimeMillis(); long cumTime = startingTime; while(cumTime - startingTime < 5000){ long timePassed = System.currentTimeMillis() - cumTime; cumTime += timePassed; a.update(timePassed); Graphics g = screen.getFullScreenWindow().getGraphics(); draw(g); g.dispose(); try{ Thread.sleep(20); }catch(Exception ex){} } } //draw method public void draw(Graphics g){ Image bots = a.getImage(); try{ Thread.sleep(200); }catch (Exception e){} g.drawImage(bg, 0, 0, null); g.drawImage(bots, 400, 450, null); } }
import java.awt.Image; import java.util.ArrayList; public class Animation { private ArrayList scenes; private int sceneIndex; private long movieTime; private long totalTime; //CONSTRUCTOR public Animation(){ scenes = new ArrayList(); //sets to zero totalTime = 0; start(); //starts animation } //Add scene to ArrayList and set time for each scene public synchronized void addScene(Image i, long t){ totalTime += t; scenes.add(new OneScene(i, totalTime)); } //Start animation from begining public synchronized void start(){ movieTime = 0; sceneIndex = 0; } //Change scenes public synchronized void update(long timePassed){ if(scenes.size()>1){ movieTime += timePassed; if(movieTime >= timePassed){ movieTime = 0; sceneIndex = 0; } while(movieTime > getScene(sceneIndex).endTime){ sceneIndex++; } } } //get animations current scene(aka image) public synchronized Image getImage(){ if(scenes.isEmpty()){ return null; }else{ return getScene(sceneIndex).pic; } } //Get scene private OneScene getScene(int x){ return (OneScene)scenes.get(x); } ///////// PRIVATE INNER CLASS /////////// private class OneScene { Image pic; long endTime; public OneScene(Image pic, long endTime){ this.pic = pic; this.endTime = endTime; } } }
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Simple animation not working
Similar Threads
Images don't painting
problem with animation
Beginner painting troubles
Drawing An Image In Full-Screen
Having problems with Window and Frame
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/607032/java/java/Simple-animation-working | CC-MAIN-2015-32 | refinedweb | 617 | 50.84 |
iofunc_check_access()
Check access permissions
Synopsis:
#include <sys/iofunc.h> int iofunc_check_access( resmgr_context_t *ctp, const iofunc_attr_t *attr, mode_t checkmode, const struct _client_info *info );
Since:
BlackBerry 10.0.0
Arguments:
- ctp
- A pointer to a resmgr_context_t structure that the resource-manager library uses to pass context information between functions.
- attr
- A pointer to the iofunc_attr_t structure that defines the characteristics of the device that's associated with the resource manager.
- checkmode
- The type and access permissions that you want to check for the resource. For more information, see below.
- info
- A pointer to a _client_info structure that contains the information about a client connection. For information about this structure, see ConnectClientInfo(). You can get this structure by calling iofunc_client_info_ext().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The iofunc_check_access() function verifies that the client is allowed access to the resource, as specified by a combination of who the client is (info), and the resource attributes attr->mode, attr->uid and attr->gid. Access is tested based upon the checkmode parameter.
The checkmode parameter determines which checks are done. It's a bitwise OR of the following constants:
- S_ISUID
- Verifies that the effective user ID of the client is equal to the user ID specified by the attr->uid member.
- S_ISGID
- Verifies that the effective group ID or one of the supplementary group IDs of the client is equal to the group ID specified by the attr->gid member.
- S_IREAD
- Verifies that the client has READ access to the resource as specified by attr->mode.
If the client's effective user ID matches that of attr->uid, then the permission check is made against the owner permission field of attr->mode (mask 0700 octal).
If the client's effective user ID doesn't match that of attr->uid, then if the client's effective group ID matches that of attr->gid, or one of the client's supplementary group IDs matches attr->gid, the check is made against the group permission field of attr->mode (mask 0070 octal).
If none of the group fields match, the check is made against the other permission field of attr->mode (mask 0007 octal).
- S_IWRITE
- Same as S_IREAD, except WRITE access is tested.
- S_IEXEC
- Same as S_IREAD, except EXECUTE access is tested. Note that since most resource managers don't actually execute code, the execute access is typically used in its directory sense, i.e. to test for directory accessibility, rather than execute access.
The S_ISUID and S_ISGID flags are mutually exclusive, that is, you may specify at most one of them. In conjunction with the S_ISUID and S_ISGID flags, you may specify zero or more of the S_IREAD, S_IWRITE, and S_IEXEC flags. If no flags are specified, the permission checks are performed for privileged (root) access.
Here's some pseudo-code to try to explain this:
if superuser: return EOK if S_ISUID and effective user ID == file user ID: return EOK if S_ISGID and effective group ID == file group ID: return EOK if S_IREAD or S_IWRITE or S_IEXEC: if caller's user ID == effective user ID: if all permissions are set in file's owner mode bits: return EOK else: return EACCES if ( caller's group ID or supplementary group IDs ) == effective group ID: if all permissions are set in file's group mode bits: return EOK else: return EACCES if all permissions are set in file's other mode bits: return EOK else: return EACCES return EPERM
Returns:
- EACCES
- The client doesn't have permissions to do the operation.
- ENOSYS
- NULL was passed for info structure.
- EOK
- Successful completion.
- EPERM
- The group ID or owner ID didn't match.
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/i/iofunc_check_access.html | CC-MAIN-2017-34 | refinedweb | 639 | 53.61 |
Thanks for your feedback.
We are rerouting this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.
The following C++ code: namespace NS { struct S { void f (); }; } int main () { NS::S s; s.f(); } namespace NS { void S::f () { extern void g (); g(); } void g () { } } fails at link-time when compiled with Microsoft Visual C++ 2010: error LNK2019: unresolved external symbol "void __cdecl g(void)" (?g@@YAXXZ) referenced in function "public: void __thiscall NS::S::f(void)" (?f@S@NS@@QAEXXZ) If I remove the namespace NS, it works. If f is not a member-function, it works. But in this code, the compiler thinks that the "extern void g ();" is in the global namespace, and not in namespace NS. However, the Standard 3.5/7. says: "When a block scope declaration of an entity with linkage is not found to refer to some other declaration, then that entity is a member of the innermost enclosing namespace." So I think, it is a bug.
Please wait...
Thank you for reporting this bug. This looks like indeed a compiler where we're not injecting the extern decl to the inner-most namespace scope, instead we're injecting it to the global scope. We will consider fixing this bug in a future release. In the meantime, please accept these workarounds, and we apologize for the inconvienence.
namespace NS {
struct S {
void f ();
};
}
int main () {
NS::S s;
s.f();
}
namespace NS {
void S::f () {
extern void g ();
g();
}
}
void g () {
}
Thanks,
Ulzii Luvsanbat
Windows C++ Team | https://connect.microsoft.com/VisualStudio/feedback/details/664619/the-namespace-of-local-function-declarations-in-c | CC-MAIN-2015-48 | refinedweb | 269 | 74.49 |
Improving Rails scalability using modularity with enforced boundaries
I did a talk at LRUG (London Ruby User Group) on this! If you like this post, or prefer video based content, you can check it out here.
Ruby & Rails have a reputation for not scaling well — you’ve probably heard this already.
TLDR for this post
There’s 3 things I’m going to talk about that have been used to improve the scalability of a Rails application.
1. Make the Rails application modular
2. Create a clear dependency graph
3. Enforce the boundaries between those separate modules
Contents
Make the Rails application modular
— Why does it end up like this?
— How should we split the application into modules?
— What have people tried in order to achieve modularity in a monolithic Rails application?
Create a clear dependency graph
Enforce the boundaries between those separate modules
— What do I mean by enforcing boundaries?
— Why doesn’t Rails enforce boundaries?
— Options for enforcing boundaries (tests and Packwerk)
Make the Rails application modular
Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
Many rails applications eventually become an entangled mess of code where a developer can’t easily reason:
1) How the code is organised (the different sections and how they relate to each-other) and what it’s doing
2) What might break when you change one section of the application (what parts of the codebase depend on what other parts of the codebase)
Why does it end up like this?
- The default Rails folder structure encourages you to organize your code in layers rather than modules.
This is the default structure of a Rails application.
This doesn’t tell you much about what the application does — just that it’s implemented in models, views and controllers (the layers). And even then, there’s no guarantee that the boundaries between these sections of the code are enforced.
2. Ruby/Rails doesn’t encourage you to modularise your code in the same way some languages do
If you look at Java (from Java 9) you have ‘modules’ which group ‘packages’ (which are groups of Java classes that relate to each other) and enforce the boundaries between those modules. This is a clear and explicit aspect of the language.
This means that looking at a Java application that uses modules, you could easily see what modules exist (which gives you a pretty good view of how the application code is structured, and what the application does) and what the dependencies between those modules are (so that you’d be confident on what might break if you change a particular module).
We don’t have anything as explicit in Ruby/Rails. People have discovered ways to kind of achieve this (see the ‘what have people tried’ section below) but it feels more like workarounds than a deliberate aspect of the language/framework.
How should we split the application into modules?
This is what I’ll talk about least in this post, but it’s obviously something you’ll need to think a lot about. DDD seems to be a popular approach to decide the bounded contexts within your application and split the code into modules that represent those bounded contexts, I’d recommend this post to see an example within the modular monolith context and this has been touted as the go to book on DDD.
Doing one ‘big bang’ PR to completely re architect an application is one way (this was Shopify’s approach with their humongous Rails application) but breaking out single components over time, or introducing new functionality as components is also a common approach — I like the questions Gousto asked themselves before deciding whether a new feature was a separate enough domain to build outside their normal Rails structure.
What have people tried in order to achieve modularity in a monolithic Rails application?
This isn’t exhaustive (if you know other attempts please comment and I’ll update) but here are some ways people have attempted to modularise a Rails monolith:
- Rails engines.
Rails engines seem to be a very popular approach for achieving modularity and have well documented successes. The idea is that for each component in your application you create a Rails engine, which is like its own stand alone Rails application with its own models, views and controllers. For example Devise is a Rails engine that you include and use in your own application — check out its repo and notice that it has its own
app/ folder with views and controllers!
Aside from the clear separation another massive benefit is that if you load the engines using Bundler you are prevented from having circular dependencies (read the Circular Dependencies section of Modular Monolith). This means that you’ll have a clear dependency graph that can only flow one way, and that’s massive.
Component Based Rails Applications (Cbra) is a popular architecture and you can start your research here if you haven’t heard of it or listen to this talk. Another popular use of Rails engines for this goal is the Modular Monolith which breaks down a real life example of how Root used Rails engines and components to achieve modularity. Airtasker have also broken down their approach to modularization using Rails engines which is well worth a read. Gousto have a great blog on how they used a Rails engine for a new feature that they considered breaking into its own external service but wrote as an engine inside the monolith instead. Lastly, shopify have broken their enormous Rails application into components and heavily utilise Rails engines (although not for everything) — they’ve got many blog posts but here’s one, and another to get you started.
2. Extracting components to the lib directory or a new directory at the root level of the application
This approach is similar to the above in terms of intent, the intention is to group the domain logic of an application into clearly defined components and then namespace those components outside of the standard app folder but without using Rails engines.
By not using Rails engines our components won’t have their own views and controllers, this means that the approach outlined by Dan in the Modular Monolith where he breaks the API and Admin (admin dashboard) into separate components wouldn’t be possible as you’d need Admin to have it’s own views etc. However, you’re not always going to need views and controllers for components — at Simply Business we had a Rails application that was responsible for attributing sales to partners with a lot of domain logic that we’d gone through a long DDD process to clearly define and represent in our code. We architected the code in a similar fashion to Ubers domain-orientated microservices architecture (where we used folders with enforced boundaries— see packwerk below — instead of microservices).
The downside of this approach is that now you have the app folder doing its normal Rails thing but also now these separate components. If it’s impossible to mistake that logic should go in the component and not the app folder (which was the case for us at Simply Business because almost all the logic was in the components folder) or everyone is aware that logic relating to certain functionality should go in these components then you’re golden, but if people start creeping functionality into
app/ then beware you may end up with code spread across the app.
3. Extracting gems
Rails engines are distributed as gems, but it’s also possible to just create standard gems that encapsulate domain logic. For example if you are building an application for an insurance company, you could encapsulate all the logic relating to rating (which will take all the information about a customer and create insurance quotes for them) into a gem.
This approach has similarities to the above 2 — it’s got similar benefits to rails engines (e.g. it creates a very clear place for logic that is within your application but clearly separate, and bundler prevents circular dependencies so if you had multiple gems then you’d only ever have a dependency graph that has arrows pointing in one direction between them) but the gems only encapsulate domain logic, they will work alongside the normal Rails application to utilise views and controllers.
Create a clear dependency graph
A dependency graph is a directed graph that represents the dependencies of several objects towards each other…the main question you need to answer is: if I touch this, what else would be impacted? Source
You can use automated tools like rubrowser to automatically generate this for you.
Ideally your graph would look something like this:
Notice that the arrows only go one way. For example, Subscription points to (i.e. depends on) Billing and Delivery. This means that if we changed either Billing or Delivery then there’s a chance that Subscription has broke BUT if we change Subscription then we shouldn’t need to run the tests for Delivery or Billing. The rule is that when we change the system from the diagram above, we only need to check the component we change or the components that have arrows pointing into it.
There are so many benefits to this but here are my 2 favourite:
1. It’s easy to reason about how your system interacts at a high level. If someone new joined tomorrow you could show them this dependency graph and they’d have a pretty good understanding of what the app is doing and how it’s organised by this graph alone.
2. When you make changes in a component, you feel confident that you’re not breaking unexpected parts of your system. Note this only applies if you have enforced boundaries (i.e. you feel confident because you 100% know that nowhere uses this class/module apart from this defined list).
See Steve Hagemann explain this and even more benefits.
You might find that your Rails application looks absolutely nothing like the above, and has arrows pointing both to other modules and back from them (circular dependencies). This is common for a Rails application and is the trade off for being able to move so quickly initially.
If your application’s dependency graph looks like spaghetti, understanding the impact of changes is difficult.
Enforce the boundaries between those separate modules
Okay so there’s a massive problem with all of the approaches for modularisation, and it’s the main reason I say that Rails/Ruby aren’t set up for modularisation in the same way as a language like Java. The problem is that there’s no way to enforce the boundaries between the components you’ve now created.
What do I mean by enforcing boundaries?
Let’s quickly go back to the Java ‘module’:
a module must provide a module descriptor — metadata that specifies the module’s dependencies, the packages the module makes available to other modules, and more. (from this article)
This means that
Module A cannot use the code from
Module B, unless
Module B explicitly makes that code available in a public interface and
Module A explicitly lists it as a dependency. Beautiful. If you’re a developer working on that application you are forcibly prevented from creating circular dependencies (or any dependencies!) without explicitly defining them and it passing a PR review, and you’re forced to only use the public interface of a module so you can’t dive straight into its domain logic. Your application is now much less likely (but not impossible) to turn into a ball of mud with a dependency graph like a bowl of spaghetti because people are forced to think about and state their dependencies.
Why doesn’t Rails enforce boundaries?
There’s nothing that stops anyone from using code from anywhere else in a Rails application regardless of if it’s in the normal Rails folder structure, in a gem, in an engine or in a new folder structure outside of the app folder. The only difference is that in some instances you may need to require the file that the class you’re calling is in, or add it to the autoload config. In no situation do you need to list a dependency for a component and you’re never forced to use a public interface — you can delve straight into any class/module.
In fact, Rails actually makes it easier for you to unwittingly create these dependencies and spaghetti code because it uses Zeitwerk which auto-loads all files in the standard rails structure (and you can add additional paths to the autoload if you’d like, e.g. if you added a new folder outside of
app/). This has benefits, namely speed and ease, in Zeitwerk’s own words:
You don’t need to write require calls for your own files, rather, you can streamline your programming knowing that your classes and modules are available everywhere
However those benefits come at the cost that after a while your code is less likely to have clear modules with public interfaces, enforced boundaries and clear dependencies.
Options for enforcing boundaries (tests and Packwerk)
There’s been different attempts at enforcing boundaries and here’s a couple of ways that people have had success with:
- Testing. There’s been some creative ways to use test suites to help enforce boundaries when using Rails engines. I’d really recommend reading the enforcing boundaries section of the modular monolith and Airtaskers section on enforcing boundaries for step by steps.
- Packwerk. Packwerk is a Ruby gem from Shopify that’s used to enforce boundaries and modularize Rails applications. It’s not the only linter of this type (check out flexport for using with Rails Engines) but it’s an incredibly lightweight tool that’s usable with any Rails code, not just engines. It’s being used at a massive scale at Shopify (they had 37 components and 48 packages in 2020, source) and other organisation including Simply Business are utilising it.
Packwerk allows you to create ‘packages’ (which can be any folder of any size, and packages can contain other packages inside them). A package has a public interface (which can be 1 or more files) and must explicitly define its own dependencies. Adding a simple command to your CI will check that the boundaries between your packages are enforced, raising a linting error if a violation occurs. You can allow a dependency between packages to occur, but similar to Java ‘modules’ you’re forced to explicitly define them which means that anybody looking at your application will be able to create a clear dependency graph and be confident when changing a package what other packages may be affected.
Lastly, if you’re looking to implement packwerk into an existing application and know that you’re going to have many violations, unlike the Rails engine and other approaches you’re not forced to re architect before implementing — they have a ‘stop the bleeding’ approach that allows you to only enforce the violations from the point you implement (similar to how you can ignore current rubocop errors when implementing a new cop so your build doesn’t suddenly have 5k errors to fix). Even better — when doing this, packwerk will automatically generate a list of the current violations to ignore — and that list can be used both to understand the current dependencies but also act as a starting point and future plan for how to reduce the dependencies of that package.
If you’re interested in trying Packwerk I’d recommend this video and their docs to get you started. | https://robertfaldo.medium.com/improving-rails-scalability-using-the-modular-monolith-approach-with-enforced-boundaries-f8cea89e85b9?source=post_internal_links---------3------------------------------- | CC-MAIN-2022-05 | refinedweb | 2,634 | 52.12 |
Hide Forgot
Description of problem:
minus number could be set in router RELOAD_INTERVAL
Version-Release number of selected component (if applicable):
oc v3.1.1.904
kubernetes v1.2.0-alpha.7-703-gbc4550d
How reproducible:
Always
Steps to Reproduce:
1. Create router in your env
2. Edit router dc to set a reload time to a minus value for router
- name: RELOAD_INTERVAL
value: -100s
3. Check the router log (set loglevel=5 for router)
Actual results:
Got "Template router will coalesce reloads within -100 seconds of each other" info from the log
[root@ip-172-18-0-36 ~]# oc logs router-9-qol1l
I0216 09:40:36.848332 1 router.go:116] Creating a new template router, writing to /var/lib/containers/router
I0216 09:40:36.853388 1 router.go:118] Router will use default/router service to identify peers
I0216 09:40:36.853421 1 router.go:158] Template router will coalesce reloads within -100 seconds of each other
I0216 09:40:36.853427 1 router.go:163] Reading persisted state
I0216 09:40:36.854875 1 router.go:167] Committing state
I0216 09:40:36.855813 1 router.go:224] Writing the router state
I0216 09:40:36.856570 1 router.go:229] Writing the router config
I0216 09:40:36.857066 1 router.go:234] Reloading the router
I0216 09:40:36.997549 1 router.go:161] Router is including routes in all namespaces
I0216 09:40:36.997632 1 controller.go:40] Running router controller
I0216 09:40:36.997644 1 reaper.go:17] Launching reaper
Expected results:
Minus number could not be set for router RELOAD_INTERVAL
Fixed with - completing the paperwork.
Test on latest origin code, bug have been fixed
router will be deployed failed when set minus number in router RELOAD_INTERVAL
[root@ip-172-18-13-133 ~]# oc logs router-5-xnbd8
F0308 08:15:40.370781 1 helpers.go:107] error: invalid reload interval: -100 - must be a positive duration
QE will verify the bug once the PR merge to OSE
Test on latest ose env, issue have been fixed on ose.
oc v3.2.0.6
kubernetes v1.2.0-36-g4a3f9c5
# oc logs router-4-qmcx7
F0322 05:22:10.826550 1 helpers.go:107] error: invalid reload interval: -90 - must be a positive duration
# oc logs router-5-qcy15
W0322 05:24:35.872227 1 template.go:66] Invalid RELOAD_INTERVAL "dbdn", using default value 5 ...
Could you please move the bug to ON_QA, then I could verify it. Thanks!
This has been merged into ose and is in OSE v3.3.0.28 or newer.
Issue have been fixed on
oc v3.3.0.28. | https://bugzilla.redhat.com/show_bug.cgi?id=1311459 | CC-MAIN-2019-51 | refinedweb | 447 | 71.71 |
I very happy at the time with them.) I also had no real way to measure the performance of them.
A few months ago I started to get very suspicious that the old carryover code was causing a lot of the flight headaches I've been experiencing such as aggressive flight leading to a flip. Or slow, wobbly response in descents. Max was complaining that AC2 lacked "wings". That's not a lot to go on, but it is real feedback that something needed done.
I built the SIM specifically to tackle this type of problem and here is how it was used:
In the SIM a parameter was created called g.test. A checkbox toggles the value of this param and the boolean value is used to turn on or off chunks of code. This gives me a side-by-side comparison of the impact.
Suspect code:
Attitude.pde: get_stabilize_roll() and get_stabilize_pitch();
// limit the error we're feeding to the PID
target_angle = constrain(target_angle, -2500, 2500);
This line limits the desired rates sent to the rate loop. A before and after plot shows the performance gain when this line of code is disabled. The Initial state of the copter was roll left at 450° per second. The plot shows the roll angle going to -85°, then recover to 0. Removing that line improve the recovery time from 1.15s to .75s
Suspect code 2:
static int16_t get_angle_boost(int16_t value)
{
float temp = cos_pitch_x * cos_roll_x;
temp = 1.0 - constrain(temp, .5, 1.0);
int16_t output = temp * value;
return constrain(output, 0, 200);
static int16_t get_angle_boost()
{
float temp = cos_pitch_x * cos_roll_x;
temp = constrain(temp, .5, 1.0);
return ((float)g.throttle_cruise / temp) - g.throttle_cruise;
This has the effect of maintaining perfect downward acceleration at all times. The reason this works is the throttle-cruise (say 500 out of 1000) is = to 9.81m/s/s of downward acceleration. We can use a linear mapping of throttle to acceleration to achieve the additional throttle necessary for the combined roll and pitch tilt.
Bonus
The last example not is not a patch but a tuning example:
For a basic setup we've been using Rate_P of .14 and Rate_D of 0. Also a Rate dampener similar to the Wii project of .15 Many folks were OK with these gains, but the performance was meh in Max and Marco's experience.
Here is a copter at 45° returning to 0° with the current gains and no patches:
With Patches:
Notice the overshoot and the bell ringing. The frequency with the above with patches is lower and that's good.
Here is the comparison of the above, but with the optimum gains:
These gains are now the default gains:
rate_P of .18
rate_D of .004
stab_D of 0
Please try these gains in the simulator and raise and lower the rate_D term. I was pretty surprised to see how tied the Rate_P and Rate_D are to each other. They cannot be tuned independently. A rate_P of .18 and Rate_D of 0 will not fly well at all. It will fast wobble in the air quite a bit.
I hope this was interesting. The SIM is currently residing at
Jason
Views: 1098
Comment
Thanks Jason for your great work!
Distributor Comment by Dany Thivierge on June 6, 2012 at 12:16pm
This is great work and will take out some more "real" testing time and damages to our copters!
are you combining this to the other simulator tool used to find bugs? (forgot the name)
I am playing with it and I really enjoy the scripted loops! hahaha I want my switch CH7 to do that!
Superb work Jason (as usual) thanks a lot. Cant wait to see these fixes in action in Firmware 2.6
Dany
Great stuff!
Question to the experts out there:
I remember seeing some amazing control system demos 20 years ago and the term "fuzzy logic" was all the hype. Can fuzzy logic be used to improve PID controllers or is that a complete different approach? Could the APM/AC benefit from some fuzzy logic?
Moderator Comment by John Church on June 6, 2012 at 2:00pm
Jason, the current GIT is flying great! Thanks.
Does this mean that you'll be closer to the "one knob tunes all parameters" functionality that is key to an "easy" setup?
I tell ya'... leaps and bounds, man. Nice work.
Fuzzy logic is a different control method which translates "human intuition" into approximate feedback gains.
It’s more suited when you lack a (accurate) mathematical model of the plant, but you know how to manual control it.
As for controlling a quad, a classic cascaded PID feedback control architecture is more suited
Developer Comment by Andreas M. Antonopoulos on June 6, 2012 at 7:36pm
What is amazing about your innvation Jason, isn't so much the bugs that you discovered, but how you introduced a rigorous methodology for A/B testing with the ability to do test iterations in minutes rather than hours. Your new methodology basically uncovered stuff it would have taken *thousands* of hours of flights, anecdotal stories and tlogs to figure out.
Developer Comment by Andreas M. Antonopoulos on June 6, 2012 at 7:40pm
To Other Andreas:
Now that we can simulate A/B testing, you have the basis for a neural network training scheme (ie. a fitness test). It would be interesting to consider "evolving" control schemes or tuning parameters or both using a neural net.
This is just begging for neural network to find the best values for PID variables.
Nice work Jason.
Great stuff | http://diydrones.com/profiles/blog/show?id=705844%3ABlogPost%3A883293&commentId=705844%3AComment%3A883507&xg_source=activity | CC-MAIN-2013-20 | refinedweb | 936 | 74.19 |
Creating Repeated Sequences With The Modulus (MOD) Operator
This almost doesn't warrant its own post; but, it seems to be one of those small factoids that I can't keep in my head without writing it down. And so, a quick post to demonstrate creating repeated sequences with the modulus operator (MOD or %). To be fair, the modulus operator already creates repeated sequences; but, those sequences end with a zero. This is perfect for when you only care about one number in a particular sequence; but, when you want to deal with a sequence as a set of numbers, typically, you want your sequence to start at 1 and proceed to N.
In order to end your sequence on "N", you have to add some math to your modulus calculation. But, before we look at that, let's take a look at a simple modulus loop:
- <!---
- Loop to 15 using a modulus of 3 to get a result
- at each index.
- --->
- <cfloop
- index="i"
- from="1"
- to="15"
-
- #i# % 3 = #(i % 3)#<br />
- </cfloop>
Here, we are looping from 1 to 15 and outputting the mod-3 for each index. When we run this code, we get the following output:
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
8 % 3 = 2
9 % 3 = 0
10 % 3 = 1
11 % 3 = 2
12 % 3 = 0
13 % 3 = 1
14 % 3 = 2
15 % 3 = 0
As you can see, this creates the repeated sequence, {1,2,0}. Like I said, standard modulus sequences end with zero. This is great if you want to determine which index you are at (1 == first, 0 == last); but, if you wanted to get the index within the repeated sequence, your logic gets a bit more tricky.
To create a repeated sequence that ends in N rather than zero, we have to add some more math to the mix:
- <!---
- Now, loop to 15 using a modulus of 3. However, this time,
- rather than repeating 1,2,0, we want to repeat 1,2,3. To do
- this, we have to use a slightly different formula:
- ((n - 1) % 3) + 1
- --->
- <cfloop
- index="i"
- from="1"
- to="15"
-
- ((#i# - 1) % 3) + 1 = #(((i - 1) % 3) + 1)#<br />
- </cfloop>
This time, we are subtracting one from the index and then adding one to the result. When we run this code, we get the following output:
((1 - 1) % 3) + 1 = 1
((2 - 1) % 3) + 1 = 2
((3 - 1) % 3) + 1 = 3
((4 - 1) % 3) + 1 = 1
((5 - 1) % 3) + 1 = 2
((6 - 1) % 3) + 1 = 3
((7 - 1) % 3) + 1 = 1
((8 - 1) % 3) + 1 = 2
((9 - 1) % 3) + 1 = 3
((10 - 1) % 3) + 1 = 1
((11 - 1) % 3) + 1 = 2
((12 - 1) % 3) + 1 = 3
((13 - 1) % 3) + 1 = 1
((14 - 1) % 3) + 1 = 2
((15 - 1) % 3) + 1 = 3
As you can see, this time, we created the repeated sequence, {1,2,3}. With the extra math, we were able to end on N (3 in our case) rather than zero.
And, of course, we could abstract this concept out into its own function:
- <cffunction
- name="modSequence"
- access="public"
- returntype="numeric"
- output="false"
-
- <!--- Define arguments. --->
- <cfargument
- name="index"
- type="numeric"
- required="true"
- hint="I am the index that we will fit into the given sequence."
- />
- <cfargument
- name="sequence"
- type="numeric"
- required="true"
- hint="I am sequence (max value) into which we will be fitting the given index."
- />
- <cfreturn (((arguments.index - 1) % arguments.sequence) + 1) />
- </cffunction>
- <!--- loop to 15, repeating 1,2,3. --->
- <cfloop
- index="i"
- from="1"
- to="15"
-
- modSequence( #i#, 3 ) = #modSequence( i, 3 )#<br />
- </cfloop>
Here, we're simply encapsulating the details behind a function invocation. When we run the above code we get the following page output:
modSequence( 1, 3 ) = 1
modSequence( 2, 3 ) = 2
modSequence( 3, 3 ) = 3
modSequence( 4, 3 ) = 1
modSequence( 5, 3 ) = 2
modSequence( 6, 3 ) = 3
modSequence( 7, 3 ) = 1
modSequence( 8, 3 ) = 2
modSequence( 9, 3 ) = 3
modSequence( 10, 3 ) = 1
modSequence( 11, 3 ) = 2
modSequence( 12, 3 ) = 3
modSequence( 13, 3 ) = 1
modSequence( 14, 3 ) = 2
modSequence( 15, 3 ) = 3
The modulus operator is pretty awesome, no doubt. Hopefully, I'll now be able to remember how to use it to create a more "standard" repeated sequence. And if I can't, at least I know where to look.
Looking For A New Job?
Ooops, there are no jobs. Post one now for only $29 and own this real estate!
Reader Comments
When I first started programming, I thought the MOD operator was the coolest, most awesome and interesting thing. I still love it to this day. Thanks for writing about it. You get extra brownie points, as well, for adding extra math. :-)
@Anna,
Yeah, the mod operator is totally awesome :) It's one of my favorite operators (which may very well be the geekiest thing I say all day).
@Ben,
haha...you can be geeky, that's ok. I am geeky all day, every day, probably, but it's gotten so bad with me, that I don't even really notice it anymore, and don't recognize it when I am.
@Ben,
If you cfloop from -6 to 6, instead of from 1 to 15, you'll see that % is actually a remainder operator, not a true modulo. In a true modulo, -5 % 3 would 1, not -2.
It can make a difference if you're trying to generate a random number within a range. Say you want to generate a random number in the range of 0 to 59, to represent the number of seconds to wait before doing something. Ordinarily, % 60 does that quite nicely. But if the first operand accidentally goes negative somehow, you instead get a number in the range of -59 to 0.
Just something to watch out for.
This might be a bit more visual. Switching to code for its monofont.
You can take integer quotient times divisor and add in the remainder to get the dividend, on either side of 0.
You can't do that with true modulo.
Aw, shucks. I wish you would allow pre in addition to code.
@Ben, I forgot to mention that I like the other operators, too. It's just that by the time I got to the mod operator, I had used the others so much, I had just grown kind of tired of them. They were kind of like old news at that point. But I still like them. Just think the mod is super-cool. (and can be helpful for a lot of solutions to different problems you can't really solve easily in other ways).
We use MOD to place things in row, three columns wide. Thus, if there are eight items, the output ends up looking like:
1 2 3
4 5 6
7 8
is that what prompted this post, Ben?
@WebManWalking,
It's funny you mention that - I almost never think about numbers in the negative. I know that sounds odd; but, I can't even remember the last time that I really had to work with negative numbers. ... I am sure that is a ridiculous thought - I am sure I use them all the time :)
@Randall,
That's the kind of situation where I really started to use MOD for the first time on a regular basis. When I was using Table tags to lay things out, especially, I remember I used to use the MOD operator to determine where I should add the closing / opening TR tags.
Another particularly useful way to use the MOD operator is to break items up into an arbitrary number of columns. Say you have an unknown number of elements and you want to display them in three reasonably even columns, you would divide the number of elements by the number of columns, round up or down (so you're working with an integer), and start a new column when your MODULUS is zero.
@Paul,
I believe that splitting columns and rows was actually one of the first things I ever used it for in production. I vaguely remember having code like:
... something like that.
could also do this sort of thing with news articles or classified ads based on the number of "inches" for each article or some other arbitrary unit of measuring length, thus simulating the columnar layout of a newspaper.
How about a sequence like this?
How would you go about it?
45678123
Or
891234567 | https://www.bennadel.com/blog/2240-creating-repeated-sequences-with-the-modulus-mod-operator.htm | CC-MAIN-2018-51 | refinedweb | 1,420 | 68.6 |
The basic applet the framework methods
Posted on March 1st, 2001
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
Libraries are often grouped according to their functionality. Some libraries, for example, are used as is, off the shelf. The standard Java library String and Vector classes are examples of these. Other libraries are designed specifically as building blocks to build other classes. A certain class framework’s.
Applets are built using an application framework. You inherit from class Applet and override the appropriate methods. Most of the time you’ll be concerned with only a few important methods that have to do with how the applet is built and used on a Web page. These methods are:
Consider the paint( ) method. This method is called automatically when the Component (in this case, the applet) decides that it needs to update itself – perhaps because it’s being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method (defined in the base class Component), which goes about restoring everything, and as a part of that restoration calls paint( ). You don’t have to override paint( ), but it turns out to be an easy way to make a simple applet, so we’ll start out with paint( ).
When update( ) calls paint( ) it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because you’re limited to the surface of that particular component and thus cannot paint outside that area, which is a good thing or else you’d be painting outside the lines. In the case of an applet, the surface is the area inside the applet.
The Graphics object also has a set of operations you can perform on it. These operations revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc. (Note that you can look all this up in your online Java documentation if you’re curious.) There are some methods that allow you to draw characters, however, and the most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet’s drawing surface. This location is given in pixels, so it will look different on different machines, but at least it’s portable.
With this information you can create a simple applet:
//: Applet1.java // Very simple applet package c13; import java.awt.*; import java.applet.*; public class Applet1 extends Applet { public void paint(Graphics g) { g.drawString("First applet", 10, 10); } } ///:~
Note that applets are not required to have a main( ). That’s all wired in to the application framework; you put any startup code in init( ).
To run this program you must place it inside a Web page and view that page inside your Java-enabled Web browser. To place an applet inside a Web page you put a special tag inside the HTML source for that Web page [54] to tell the page how to load and run the applet. This is the applet tag, and it looks like this for Applet1:
<applet code=Applet1 width=200 height=200> </applet>
and there can be as many as you want.
For simple applets all you need to do is place an applet tag in the above form inside your Web page and that will load and run the applet.
Testing applets
You can perform a simple test without any network connection by starting up your Web browser and opening the HTML file containing the applet tag. (Sun’s JDK also contains a tool called the appletviewer that picks the <APPLET> tags out of the HTML file and runs the applets without displaying the surrounding HTML text. [55]) As the HTML file is loaded, the browser will discover the applet tag and go hunt for the .class file specified by the code value. Of course, it looks at the CLASSPATH to find out where to hunt, and if your .class file isn’t in the CLASSPATH then it will give an error message on the status line of the browser to the effect that it couldn’t find that .class file.
When you want to try this out on your Web site things are a little more complicated. First of all, you must have a Web site, which for most people means a third-party Internet Service Provider (ISP) at a remote location. Then you must have a way to move the HTML files and the .class files from your site to the correct directory (your WWW directory) on the ISP machine. This is typically done with a File Transfer Protocol (FTP) program, of which there are many different types freely available. So it would seem that all you need to do is move the files to the ISP machine with FTP, then connect to the site and HTML file using your browser; if the applet comes up and works, then everything checks out, right?
Here’s where you can get fooled. If the browser cannot locate the .class file on the server, it will hunt through the CLASSPATH on your local machine. Thus, the applet might not be loading properly from the server, but to you it looks fine because the browser finds it on your machine. When someone else logs in, however, his or her browser can’t find it. So when you’re testing, make sure you erase the relevant .class files on your machine to be safe.. It took some time to discover that the package statement was the culprit. In general, you’ll want to leave the package statement out of an applet.
A more graphical example
The example above isn’t too thrilling, so let’s try adding a slightly more interesting graphic component:
//: Applet2.java // Easy graphics import java.awt.*; import java.applet.*; public class Applet2 extends Applet { public void paint(Graphics g) { g.drawString("Second applet", 10, 15); g.draw3DRect(0, 0, 100, 20, true); } } ///:~
This puts a box around the string. Of course, all the numbers are hard-coded and are based on pixels, so on some machines the box will fit nicely around the string and on others it will probably be off, because fonts will be different on different machines.
There are other interesting things you can find in the documentation for the Graphic class. Any sort of graphics activity is usually entertaining, so further experiments of this sort are left to the reader.
Demonstrating
the framework methods
It’s interesting to see some of the framework methods in action. (This example will look only at init( ), start( ), and stop( ) because paint( ) and destroy( ) are self-evident and not so easily traceable.) The following applet keeps track of the number of times these methods are called and displays them using paint( ):
//: Applet3.java // Shows init(), start() and stop() activities import java.awt.*; import java.applet.*; public class Applet3 extends Applet { String s; int inits = 0; int starts = 0; int stops = 0; public void init() { inits++; } public void start() { starts++; } public void stop() { stops++; } public void paint(Graphics g) { s = "inits: " + inits + ", starts: " + starts + ", stops: " + stops; g.drawString(s, 10, 10); } } ///:~
Normally when you override a method you’ll want to look to see whether you need to call the base-class version of that method, in case it does something important. For example, with init( ) you might need to call super.init( ). However, the Applet documentation specifically states that the init( ), start( ), and stop( ) methods in Applet do nothing, so it’s not necessary to call them here.
When you experiment with this applet you’ll discover that if you minimize the Web browser or cover it up with another window you might not get calls to stop( ) and start( ). (This behavior seems to vary among implementations; you might wish to contrast the behavior of Web browsers with that of applet viewers.) The only time the calls will occur is when you move to a different Web page and then come back to the one containing the applet.
[54] It is assumed that the reader is familiar with the basics of HTML. It’s not too hard to figure out, and there are lots of books and resources.
[55] Because the appletviewer ignores everything but APPLET tags, you can put those tags in the Java source file as comments:This way, you can run " appletviewer MyApplet.java " and you don’t need to create tiny HTML files to run tests.
// <applet code=MyApplet.class width=200 height=100></applet>
There are no comments yet. Be the first to comment! | https://www.codeguru.com/java/tij/tij0134.shtml | CC-MAIN-2017-51 | refinedweb | 1,470 | 69.62 |
This follows on from my first article, so if you want to follow along, download and configure that code for your Azure AD instance as a starting point.
Having created an Angular site that requires users to log in with Azure AD, now we want to protect our back end APIs so that they will ignore calls that don't contain a token generated by Azure AD. Until we do this, our site is not really secure, anyone can hit our end points and access sensitive data.
In order to write the code we need, we need to first get a secret from Azure AD. Go to your Application in Azure AD and click on 'Certificates and Secrets' (for now, we're clicking on the 'Preview' item which will eventually replace the main one today).
If you click on 'New client secret', you'll be prompted to give it a name and decide on how long it lasts. You can make it automatically expire in 1 or 2 years, or make it last until you choose to remove it. When you click 'Add', you will see your secret as follows:
alt="Image 2" data-src="/KB/azure/2355904/Secret_2-r-700.PNG" class="lazyload" style="cursor: pointer; border: 0; width: 700px; height: auto" onclick="imageCleanup.showFullImage('/KB/azure/2355904/Secret_2.PNG')" data-sizes="auto" data->
BE CAREFUL!!! If you refresh this screen, there is NO WAY to ever see this secret again. Click on the icon to the right to copy your secret to your clipboard and then store it in a safe place.
The first thing we need to do is configure the settings. Go to your appsettings.json and add this object:
"AzureAd": {
// Coordinates of the Azure AD Tenant
"Instance": "",
"Domain": "<yourdomain>",
"TenantId": "<yourtenantid>",
// Coordinates of the app
"ClientId": "<yourclientid>",
"CallbackPath": "/signin-oidc",
"ClientSecret": "<yourclientsecret>"
},
width="699px" alt="Image 3" data-src="/KB/azure/2355904/tenant.PNG" class="lazyload" data-sizes="auto" data->
The easiest way I found to find your domain is to click 'expose an API' and the scope added by default has your domain URL in it. Just remove the GUID at the end and copy this in.
It's worth mentioning that, at this point, you're configuring your Azure instance twice, once for .NET Core and once for Angular. If you don't configure them both the same, it's not going to work.
Now, if you're following along, you will need to download the sample code for this article and create a folder and add two class files as follows:
This is not code I wrote, it's code I found online, on the Microsoft site. I imagine it will become part of a library at some point.
Once this is done, you can add AzureAD auth to your ConfigureServices in the Startup file as follows:
AzureAD
ConfigureServices
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
Intellisense will help you add the namespace you need and you'll be good to go.
namespace
I have initially forgotten this more than once, but you also need to turn on Authentication in the Configure method:
Configure
app.UseAuthentication();
alt="Image 5" data-src="/KB/azure/2355904/tokens-r-700.PNG" class="lazyload" style="cursor: pointer; border: 0; width: 700px; height: auto" onclick="imageCleanup.showFullImage('/KB/azure/2355904/tokens.PNG')" data-sizes="auto" data->
There's still stuff to do in Azure. If you want to validate with tokens, you need to check "ID tokens" here and save.
alt="Image 6" data-src="/KB/azure/2355904/grant-r-700.PNG" class="lazyload" style="cursor: pointer; border: 0; width: 700px; height: auto" onclick="imageCleanup.showFullImage('/KB/azure/2355904/grant.PNG')" data-sizes="auto" data->
Later, when we use groups for roles, we'll need to give the app some permissions on the Graph API. For now, 'Grant admin consent', this will mean that you have consented on behalf of your users.
Graph
At this point, we have auth configured but we're not using it. The sample app that Visual Studio generates has one controller. Add an [Authorize] attribute at the top level.
[Authorize]
The site won't work anymore. You can get the token from the console and use it with Postman to confirm that authorisation is working, but let's make it work in the code.
First, we'll extend the FetchDataComponent to use an auth token. First, add a property to store the token:
FetchDataComponent
public static token: string;
Now, change the get method to use it:
get
const headerDict = {
'Authorization': 'bearer ' + FetchDataComponent.token
}
const requestOptions = {
headers: new HttpHeaders(headerDict),
};
http.get<WeatherForecast[]>(baseUrl +
'api/SampleData/WeatherForecasts', requestOptions).subscribe(result => {
this.forecasts = result;
}, error => console.error(error));
This is a little rough but it's the basic idea of what you'd want to do in production, store the token somewhere and use it in all your calls.
Now we need to store the token, so return to our app.component.ts.
import {FetchDataComponent} from './fetch-data/fetch-data.component'
and:
constructor(private adalSvc: MsAdalAngular6Service) {
console.log(this.adalSvc.userInfo);
this.adalSvc.acquireToken('').subscribe((token: string) => {
FetchDataComponent.token = token;
console.log(token);
});
}
That's it!!! Your Angular code knows how to store your token and use it as an auth header in your requests. The page will now work again, showing a collection of weather forecasts. We have everything we need to build an Angular application and protect all our APIs and access to our front end page, using Azure AD.
The main things to remember here are, make sure you're registering the front and back end to the same Azure AD application, and that you're calling app.UseAuthorization as well as the service calls.
app.UseAuthorization
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
link to source file does not work
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://codeproject.freetls.fastly.net/Articles/2355904/Azure-AD-and-Angular-Part-2-Securing-the-Back-End?pageflow=FixedWidth | CC-MAIN-2021-43 | refinedweb | 1,018 | 55.54 |
> module5.py: > from package import module6 # absolute import > > module6.py: > from package import module5 > [...] > ImportError: cannot import name module5 > > Is this behavior expected? Or is it a bug? The problem is that importing with from consists of two steps: - load the module - add the imported names to the local namespace Since this addition is by reference to the actual object and not to the symbol's name in the other module, a concept which Python doesn't have (use Perl if you want this...), your recursive import doesn't work. The solution would be: import package.module6 as module6 which should have the same effect. -- Matthias Urlichs | https://mail.python.org/pipermail/python-dev/2002-June/024889.html | CC-MAIN-2019-22 | refinedweb | 107 | 67.15 |
Click event on SWFLoadercarlos_sousa4 Jul 17, 2010 7:04 AM
Hello,
In my FLEX application i have a SWFLoader where i load some wsf files that are located in others places in the web. Some of the swf files loaded contain an hyperlink associated and, when the swf file is clicked, a new web page is opened.
So, i need to count the number of clicks made in the SWFLoader but, in the case when the swf file has an hyperlink associated, the click event is not fired. What can i do to detect if a click was made in the SWFLoader?
Thanks in advance for your help.
1. Re: Click event on SWFLoaderBhaskerChari Jul 18, 2010 10:44 PM (in response to carlos_sousa4)
Hi carlos_sousa4,
Check the below code loading the Flash SWF in to Flex application.. and handling a click event on the Flash SWF Button in the Flex app..
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.controls.Alert;
private var loadedSWFMainTimeline:*;
public function onSWFLoadComplete():void {
Alert.show("onSWFLoadComplete");
//loadedSWFMainTimeline gets you a reference to the Flash SWF MainTimeline
loadedSWFMainTimeline = swfLoader.content;
if(loadedSWFMainTimeline)
{
var _button:SimpleButton = loadedSWFMainTimeline.button_btn as SimpleButton;
_button.addEventListener(MouseEvent.CLICK,onMCButtonClick);
}
}
public function onMCButtonClick(event:MouseEvent):void {
if(loadedSWFMainTimeline)
{
Alert.show("HELLO SWF LINK CLICKED");
}
}
]]>
</mx:Script>
<mx:SWFLoader
</mx:Application>
Note : In the above code button_btn is the Flash button instance of the SWF file and the corresponding type in the Flex will be SimpleButton...In your post you said that you are using a HyperLink so may be you should flash.text.TextField datatype instead of SimpleButton.
Try to debug by putting a break point at onSWFLoadComplete function and watch the loadedSWFMainTimeline varibale you will come to know the exact type and the other parameters in the SWF file.
If this post answers your question or helps, please kindly mark it as such.
Thanks,
Bhasker Chari
2. Re: Click event on SWFLoadercarlos_sousa4 Jul 19, 2010 1:39 PM (in response to BhaskerChari)
Hi Bhasker,
Thanks for your suggestions.
I've tried it and it seems to be in the correct way but i have a problem in the following line:
loadedSWFMainTimeline = swfLoader.content;
The error message is the following:
SecurityDomain '' tried to access incompatible context ' /pub/investir_pacosdeferreira.swf'
SecurityError: Error #2121: Security sandbox violation: Loader.content: cannot access. This may be worked around by calling Security.allowDomain.
The swf file that i include in my application is reference by a url and it seems that i can't access the file to get its content. I have tried the work around suggested without succes with this two lines:
Security.allowDomain(swfLoader.source);
Security.allowDomain(swfLoader.content);
How can i solve this new problem?
Thanks.
3. Re: Click event on SWFLoaderBhaskerChari Jul 19, 2010 10:23 PM (in response to carlos_sousa4)
Hi carlos_sousa4,
Try setting Security.allowDomain("");
Also set trustContent="true" on <mx:SwfLoader /> tag
<mx:SwfLoader
If this post answers your question or helps, please kindly mark it as such.
Thanks,
Bhasker Chari
4. Re: Click event on SWFLoadercarlos_sousa4 Jul 29, 2010 8:15 AM (in response to BhaskerChari)
Hi,
I'm sorry for taking too much time for responding.
I've done a work around for the security question but my problem is still not solved because i get an error in this line suggested by Bhasker:
var _button:SimpleButton= loadedSWFMainTimeline.button_btn as SimpleButton;
The swf that i include in my flex application is somewhere in the web and i haven't access to the source code of the swf file. I just include it in the application, therefore i don't know what kind of component exist in the swf file. In the line above, i get an error because the cast is not valid.
I've done more searchs about this problem and it seems to be very complex.
The swf file that i include in my application has an infinite z-index value and it will catch all the click events. So, i can't handle those events in my application.
What suggestions can you give to me?
Thanks in advance.
Message was edited by: carlos_sousa4
5. Re: Click event on SWFLoadershashank Kulkarni Aug 27, 2010 4:55 AM (in response to BhaskerChari)
Hi Bhaskar,
I do have the same problem, Where in my SWF files are dynamically loaded documents. So how to identify words with the link from same object.
Can we capture the event in such scenario?
Thanks
6. Re: Click event on SWFLoaderBhaskerChari Aug 27, 2010 5:48 AM (in response to shashank Kulkarni)
Hi SRKKing,
You can access the flash Text field placed in Flash SWF file in Flex in the same way as I did for Button where I got a reference to the Flash Button which
is a SimpleButton type in Flex...and registered a eventListener in Flex...
Same way you can get a reference to the TextField placed in flash in flex and register an eventListener in Flex....
If you can send me the sample SWF file you are working I can help you better...
Thanks,
Bhasker Chari
7. Re: Click event on SWFLoadershashank Kulkarni Aug 30, 2010 2:21 AM (in response to BhaskerChari)
HI Bhaskar,
Thanks for Reply,
At my application swf loaded are not customized at our end.
Let me Elaborate,
We have one component to View SWF. The SWF are the word document converted into SWF with the help of Java API.
here in this case i want to capture the link click inside these SWFs from Flex based swf Viewer.
I tried what is been suggested by you,
public function onSWFLoadComplete(ev:Event):void {
Alert.show("onSWFLoadComplete");
//loadedSWFMainTimeline gets you a reference to the Flash SWF MainTimeline
loadedSWFMainTimeline = loader.content as Object;
// This is the Button i am getting from SWF
var simpleButton:SimpleButton = loadedSWFMainTimeline.button1162 as SimpleButton;
//But None of the following works correctly
simpleButton.addEventListener(MouseEvent.CLICK,onMCButtonClick);
simpleButton.addEventListener(MouseEvent.MOUSE_OVER,onMCButtonClick);
(loadedSWFMainTimeline.button1162 as SimpleButton).loaderInfo
var textSnap:TextSnapshot = loadedSWFMainTimeline.textSnapshot;
var str:String = textSnap.getText(0,textSnap.charCount,true);
// To make the things and ID capturing dynamic i had tried following way
/* if(loadedSWFMainTimeline)
{
for each (var obj:String in loadedSWFMainTimeline)
{
if(loadedSWFMainTimeline[obj] is SimpleButton)
{
Alert.show(ObjectUtil.toString(obj));
}
} */
}
public function onMCButtonClick(event:MouseEvent):void {
if(loadedSWFMainTimeline)
{
Alert.show("HELLO SWF LINK CLICKED");
}
But neither of above works, Would appreciate any comment on your part.
Thanks.
8. Re: Click event on SWFLoaderBhaskerChari Aug 30, 2010 3:42 AM (in response to shashank Kulkarni)
Hi SRKKing,
Can you mail me the sample SWF file you are working with....??? So that way I can help you in figuring out your problem..exactly...!!!
Also please mention on which link you want the event to captured...
Thanks,
Bhasker
9. Re: Click event on SWFLoadershashank Kulkarni Aug 30, 2010 10:53 PM (in response to BhaskerChari)
HI Bhaskar,
Thanks for your valuable time and comments. Indeed it definatly worked with inputs.
loader.root.addEventListener(MouseEvent.CLICK, onMCButtonClick);
has started working for me and now i just need to put if condition for my desired target.
Thanks and Regards,
Shashank | https://forums.adobe.com/thread/682102 | CC-MAIN-2017-51 | refinedweb | 1,198 | 56.66 |
On 24 Mar 2006 Peter Juszack <vdr at unterbrecher.de> wrote: > Do I have to lock/unlock the cDevice when switching to a channel? I don't know this specific plugin, but looking at the code sniplet: > void cEggtimerThread::Stop(void) { > #ifdef DEBUG > printf("cEggtimerThread::Stop\n" ); > #endif > running = false; > Cancel(30); > } > > > void cEggtimerThread::Action(void) { [...] > > Stop(); // Stop eggtimer thread I don't think that one should Cancel() (in this case via Stop()) a thread from inside the Action() function. This must lead to the observed dead-lock. I guess you should set running=false and let the loop terminate itself (if needed you can break; out from the loop too). On exit from Action() the child thread is terminated. Regards. -- Stefan Huelswitt s.huelswitt at gmx.de | | https://www.linuxtv.org/pipermail/vdr/2006-March/008503.html | CC-MAIN-2016-30 | refinedweb | 128 | 75.81 |
go to bug id or search bugs for
Description:
------------
When including files in directories that have access only permissions (no read or write), includes fail with a permission denied when trying things like
include ('../include_me.inc');
Directory permissions for the webserver process are access only (--x).
When including an absolute path, or relative path descending into the directory tree, include works ok eg:
include ('access_only/level2/include_me.inc');
The return value of "is_readable('../include_me.inc');" returns true, however include() fails.
Everything works find up to and including PHP 5.1.6, as of PHP 5.2.0 this problem occurs.
Anthony D. has access to our SPARC system and a test area in which this bug is reproduced has been set up. He should contact me at my work email address for further information.
Expected result:
----------------
The files should be included, as they were in versions prior to and in 5.1.6.
Actual result:
--------------
Warning: include(../include_me.inc) [function.include]: failed to open stream: Permission denied in /access_only/level2/index.php on line 15
Add a Patch
Add a Pull Request
Please try using this CVS snapshot:
For Windows (zip):
For Windows (installer):
CVS version still produces the error.
Verified that this is still not working in 5.2.4, nor in the latest CVS version, php5.2-200709121030.
We made a system available on a Sun E3500, partially for the purposes of fixing this bug. The last login from anyone from the PHP team was on 5 July 2007.
Is there any time plan to fix this bug? We are running on Solaris 10
and are stuck on PHP 5.1.6 because of this problem, so the situation for us is critical.
I am having this problem on *ONE* of two load-balanced servers that are setup exactly the same and that share an NFS mounted filesystem in Solaris 9. The permissions on all the subdirs, all the way from the root directory are at least 'r' and 'x' and are the same on both servers. Both machines are running the same PHP/Apache binary and are at the same OS patch level.
The following code properly returns the path on one of the machines, but not the other:
echo getcwd();
Could this have something to do with NFS?
I think I found the culprit that is bubbling up to PHP here. It effects users with:
- At least Solaris 9 to early versions of 10
- NFS mounted directories
- Any setuid application (including apache/php)
From my previous post, I showed how one server was able to getcwd() in PHP and other other wasn't. The root cause is this bug:
I tested the code under Solaris 9 and was able to reproduce it at the OS level. The one machine where include("../file.php") works on was able to successfully execute the solaris bug test code in the NFS mounted directory:
# pwd
/usr/local/www/sites
# ./solaris-nfs-getcwdtest
CWD = /usr/local/www/sites
#
The machine where include("../file.php") gives the "permission denied " error fails the getcwd command in the directory:
# pwd
/usr/local/www/sites
# ./solaris-nfs-getcwdtest
getcwd failed!!!
#
I'm not sure if anything can be done with the PHP source here to solve this since the bug is at the OS level. Unless there is some other way to get the CWD for PHP in the above situation.
NFS has nothing to do with it, this bug is definately *not* at the OS
level. We have all file systems mounted locally, and still have the
problem.
NFS may however cause other problems, particularly userid mapping,
which are more difficult to solve and need to be solved at the OS
level.
All of this stuff worked just fine up until PHP 5.1.6, since PHP
5.2.0 it's broken, and there is apparently no activity to fix this
bug.
Ok, or, these may be the same problem caused by 2 different root issues. In your initial post, you mentioned "Directory permissions for the webserver process are access only (--x).". I just lifted the following out of PHP source for tsrm_virtual_cwd.c:
/* cwd_length can be 0 when getcwd() fails.
* This can happen under solaris when a dir does not have read permissions
* but *does* have execute permissions */
Have you tried adding r-x to every subdir below and including the path?
Previous versions of PHP including 5.0.5 worked for me with a relative include() parameter, but getcwd() still returned nothing even then. This did not really cause a problem until include() broke for me. I believe that PHP now rebuilds a fully qualified path based on getcwd() when it tries to open the file stream and when you are using relative includes. This may have changed since earlier versions. I think this issue is probably related somehow to broken Solaris functions that don't work if suid:
Also, have a look at: #41899 "Can't open files with leading relative path of '..' and '..' is not readable."
They all seem related somehow.
>ab5602> Have you tried adding r-x to every subdir below and
including the path?
This is not an option here. First issue is user data security. All
users have ftp access to the system, and as a reqult of cross
cooperations, users need to be able to go through the users root
directory (note that this is not the system root!), meaning if all
directoriues were r-x, then users could easily see and access data
that is not relevant to them (other access issues that are obvious
here have been taken care of using system groups). Second issue is
we have tens of thousands of directories like this, and changing the
permissions to something else is simply not possible because the
users all have individual requirements, and most have set their own
permission schemes. Third issue is *this used to work!!!*
>ab5602> Also, have a look at: #41899 "Can't open files with leading
relative path of '..' and '..' is not readable."
The bugs are related. I am following both of them as they are both
relevant to us.
>ab5602> ...but getcwd() still returned nothing even then.
Getcwd() needs read permissions on the directory, however in a shell
in a directory with such permissions, pwd still returns the correct
directory even if nothing else can be read, and files with read
permission can also still be read:
root@www:/home/ian/testdir# ls -la
total 10
drwx--x--x 3 root root 512 Oct 1 13:17 .
drwxr-xr-x 6 ian staff 1536 Oct 1 12:56 ..
-rw-r--r-- 1 root root 24 Oct 1 13:15 afile
drwx--x--x 2 root root 512 Oct 1 13:17 testd2
root@www:/home/ian/testdir# cd testd2/
root@www:/home/ian/testdir/testd2# ls -la
total 6
drwx--x--x 2 root root 512 Oct 1 13:17 .
drwx--x--x 3 root root 512 Oct 1 13:17 ..
-rw-r--r-- 1 root root 15 Oct 1 13:17 afile2
root@www:/home/ian/testdir/testd2# cd ../../
root@www:/home/ian# su - ian
Sun Microsystems Inc. SunOS 5.10 Generic January 2005
ian@www: cd testdir
ian@www: pwd
/home/ian/testdir
ian@www: ls -la
.: Permission denied
total 2
ian@www: cat afile
Good bye cruel world!!!
ian@www: cd testd2
ian@www: pwd
/home/ian/testdir/testd2
ian@www: cat afile2
Frodo lives!!!
ian@www: ls -la
.: Permission denied
total 2
ian@www: logout
root@www:/home/ian#
To me, the problem is not something from Sun or Solaris. The
problems are in the way PHP is handling access to the files and
directories. This needs to be fixed so everything works correctly
again.
Hi, the 'pwd' command works just fine for me too on any platform. However, suid'd use of the getcwd() function I think is the issue. The below demonstrates what I think is the going on with how Solaris behaves vs. how PHP expects the getcwd() command to behave.
The following code was compiled and run on both Linux and Solaris platforms under a local filesystem and called cwdtest:
#include <stdio.h>
main()
{
char str[200];
if (getcwd(str, sizeof(str)) == NULL)
printf("getcwd failed!!!\n");
else
printf("CWD = %s\n",str);
}
------ Linux ------
# uname -a
Linux messaging2.wayne.edu 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:27:17 EDT 2006 i686 athlon i386 GNU/Linux
# find ./localfs -ls
32001 8 d--x--x--x 3 nobody nobody 4096 Oct 1 13:05 ./localfs
32002 8 d--x--x--x 2 nobody nobody 4096 Oct 1 13:12 ./localfs/test123
32004 12 -rwsr-xr-x 1 nobody nobody 4878 Oct 1 13:06 ./localfs/test123/cwdtest
# su nobody
# cd /localfs/test123
# ./cwdtest
CWD = /localfs/test123
# pwd
/localfs/test123
#
------ Solaris 10 ------
# uname -a
SunOS opteron 5.10 Generic_118855-14 i86pc i386 i86pc
# find ./localfs -ls
449384 1 d--x--x--x 3 nobody nobody 512 Oct 1 13:13 ./localfs
449386 1 d--x--x--x 2 nobody nobody 512 Oct 1 13:13 ./localfs/test123
449388 7 -rwsr-xr-x 1 nobody nobody 6552 Oct 1 12:57 ./localfs/test123/cwdtest
# su nobody
# cd /localfs/test123
# ./cwdtest
getcwd failed!!!
# pwd
/localfs/test123
#
Wow, this is strange. I'm very much closer to seeing what is going on with PHP+Solaris that is causing the issue here Ian. I've tested pwd/getcwd() with every combination I could think of and this is how Solaris feels about permissions:
If you are not root AND you want to get your current working directory that has parents with exclusively 'x' permissions, you must do one of two things:
a) Execute a getuid() program that is suid-root.
OR: And this is the strange one...
b) Tell Solaris that you already know where you are!!
If it is feasible, I'll see if I can come up with a patch to implement (b) if your architecture is Solaris and send it to the PHP internals list. See below for how this works:
-----
# uname -a
SunOS opteron 5.10 Generic_118855-14 i86pc i386 i86pc
# pwd
/
# find ./dirtest/ -ls
449393 1 d--x--x--x 3 root root 512 Oct 1 19:29 ./dirtest/
449394 1 d--x--x--x 2 root root 512 Oct 1 19:29 ./dirtest/dirtest2
# cd /dirtest/dirtest2
# pwd
/dirtest/dirtest2
# su nobody
# pwd
cannot determine current directory
# cd /dirtest/dirtest2/
# pwd
/dirtest/dirtest2
#
correction: a) Execute a program that implements getcwd() that is suid-root.
I figured out what the issue was with the NFS shares and the "permission denied error" in our Solaris environment. It was related to the same (--x) permission issue that you are having.
As it turns out, if you mount an NFS share in:
/mylocaldir/nfsmount/
The /nfsmount/ directory permissions, *before* you mount the share, need to be (r-x) or better, even though these permissions are hidden after the mount in order to avoid the Solaris+PHP include() bug. Now include() and getcwd() work just fine!
It is very clear that this all goes back to two options:
1) Either make all the subdirs underneath (r-x)
OR
2) If it is possible (which I'm not yet sure of), the PHP binary needs to "tell" Solaris that it already knows the current path by doing a chdir(/absolute/path/) or the like before trying getcwd() in order to make the "include() cause permission denied error" go away.
So this is only an issue with NFS shares? If so, please indicate that in the summary.
No, the above NFS issues is a side-effect of:
1) Solaris getcwd() not functioning properly with (--x) directories
and
2) PHP not properly allowing relative include()'s when #1 is the case
#2 is probably solvable w/ a bug fix, #1 is obviously not.
Could reproduce this bug under Mac OS X 10.4.10 and PHP 5.2.4 (via
MacPorts).
I created the following patch which fixes the problem, however it still needs discussion as to if it is a good way to implement this fix. At least it can serve as a starting point. One concern was if this should be implemented at a lower level (TSRM code).
--- ./plain_wrapper.c.old 2007-10-05 02:50:59.000000000 -0400
+++ ./plain_wrapper.c 2007-10-05 02:55:38.000000000 -0400
@@ -885,9 +885,20 @@
return NULL;
}
- if ((realpath = expand_filepath(filename, NULL TSRMLS_CC)) ==
NULL) {
- return NULL;
- }
+ if ((realpath = expand_filepath(filename, NULL TSRMLS_CC)) == NULL)
+ {
+ if (options & STREAM_OPEN_FOR_INCLUDE) {
+ /* Attempt to open without path expansion anyways.
+ Files in Solaris dirs with --x will
+ not return a realpath, but are accessible */
+ fd = open(filename, open_flags, 0666);
+ if (fd != -1) {
+ ret =
php_stream_fopen_from_fd_int_rel(fd, mode, persistent_id);
+ return ret; }
+ else {
+ return NULL; }
+ }
+ }
if (persistent) {
spprintf(&persistent_id, 0, "streams_stdio_%d_%s",
open_flags, realpath);
This bug has been fixed in CVS.
Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at.
Thank you for the report, and for helping us make PHP better.
This is fixed in CVS. | https://bugs.php.net/bug.php?id=41822 | CC-MAIN-2015-22 | refinedweb | 2,190 | 73.37 |
IRC log of xmlsec on 2009-07-14
Timestamps are in UTC.
13:27:27 [RRSAgent]
RRSAgent has joined #xmlsec
13:27:27 [RRSAgent]
logging to
13:27:29 [trackbot]
RRSAgent, make logs member
13:27:29 [Zakim]
Zakim has joined #xmlsec
13:27:31 [trackbot]
Zakim, this will be XMLSEC
13:27:31 [Zakim]
ok, trackbot; I see T&S_XMLSEC()10:00AM scheduled to start in 33 minutes
13:27:32 [trackbot]
Meeting: XML Security Working Group Teleconference
13:27:32 [trackbot]
Date: 14 July 2009
13:41:20 [Cynthia]
Cynthia has joined #xmlsec
13:42:05 [Cynthia]
Zakim, who is here?
13:42:05 [Zakim]
T&S_XMLSEC()10:00AM has not yet started, Cynthia
13:42:07 [Zakim]
On IRC I see Cynthia, Zakim, RRSAgent, klanz, tlr, trackbot
13:50:05 [Zakim]
T&S_XMLSEC()10:00AM has now started
13:50:12 [Zakim]
+ +1.443.370.aaaa
13:50:45 [fjh]
fjh has joined #xmlsec
13:51:38 [fjh]
Chair: Frederick Hirsch
13:52:09 [fjh]
Agenda:
13:53:35 [Cynthia]
ok
13:57:50 [Zakim]
+Frederick_Hirsch
13:58:20 [fjh]
zakim, aaaa is Cynthia
13:58:20 [Zakim]
+Cynthia; got it
13:58:45 [fjh]
Present: Frederick_Hirsch, Cynthia_Martin
13:59:38 [bhill]
bhill has joined #xmlsec
13:59:49 [Zakim]
+ +1.617.876.aabb
13:59:56 [bhill]
thanks
14:00:27 [fjh]
zakim, aabb is sean
14:00:29 [bhill]
ScribeNick: bhill
14:00:29 [Zakim]
+ +5aacc
14:00:29 [Zakim]
+sean; got it
14:00:32 [csolc]
csolc has joined #xmlsec
14:00:41 [mullan]
mullan has joined #xmlsec
14:00:41 [Zakim]
+ +1.303.229.aadd
14:00:50 [bhill]
zakim, aadd is bhill
14:00:50 [Zakim]
+bhill; got it
14:01:03 [csolc]
zakim, who is here
14:01:04 [Zakim]
csolc, you need to end that query with '?'
14:01:11 [tlr]
zakim, call thomas-781
14:01:11 [csolc]
zakim, who is here?
14:01:12 [Zakim]
ok, tlr; the call is being made
14:01:12 [fjh]
Present+ Brad_Hill, Sean_Martin, Chris_Solc
14:01:13 [Zakim]
On the phone I see Cynthia, Frederick_Hirsch, sean, +5aacc, bhill
14:01:15 [Zakim]
On IRC I see mullan, csolc, bhill, fjh, Cynthia, Zakim, RRSAgent, klanz, tlr, trackbot
14:01:16 [Zakim]
+Thomas
14:01:24 [fjh]
Present+ Thomas_Roessler
14:01:27 [tlr]
zakim, I am thomas
14:01:30 [Zakim]
ok, tlr, I now associate you with Thomas
14:01:30 [scantor]
scantor has joined #xmlsec
14:01:31 [tlr]
zakim, mute me
14:01:32 [csolc]
zakim, aacc is csolc
14:01:34 [Zakim]
Thomas should now be muted
14:01:38 [Zakim]
+csolc; got it
14:01:58 [Zakim]
+ +0468725aaee
14:02:03 [magnus]
magnus has joined #xmlsec
14:02:07 [pdatta]
pdatta has joined #xmlsec
14:02:10 [tlr]
ack t
14:02:15 [tlr]
zakim, mute aaee
14:02:16 [Zakim]
+ +1.206.992.aaff
14:02:24 [tlr]
zakim, unmute thomas
14:02:39 [Zakim]
+ +1.614.247.aagg
14:02:43 [Zakim]
+0468725aaee should now be muted
14:02:48 [fjh]
zakim, aaff is kyiu
14:02:48 [tlr]
zakim, mute csolc
14:02:52 [tlr]
zakim, who is making noise?
14:02:53 [Zakim]
Thomas was not muted, tlr
14:02:53 [scantor]
zakim, aagg is scantor
14:03:03 [Zakim]
+kyiu; got it
14:03:05 [Zakim]
csolc should now be muted
14:03:07 [Zakim]
+scantor; got it
14:03:15 [Zakim]
+[Oracle]
14:03:17 [Zakim]
tlr, listening for 10 seconds I heard sound from the following: Frederick_Hirsch (96%), kyiu (43%)
14:03:19 [fjh]
zakim, who is here?
14:03:21 [Zakim]
On the phone I see Cynthia, Frederick_Hirsch, sean, csolc (muted), bhill, Thomas, +0468725aaee (muted), kyiu, scantor, [Oracle]
14:03:29 [Zakim]
On IRC I see pdatta, magnus, scantor, mullan, csolc, bhill, fjh, Cynthia, Zakim, RRSAgent, klanz, tlr, trackbot
14:03:39 [fjh]
zakim, [Oracle] is pdatta
14:03:40 [bhill]
TOPIC: Administrivia
14:03:50 [Zakim]
+pdatta; got it
14:03:58 [fjh]
zakim, aaee is magnus
14:04:05 [Zakim]
+magnus; got it
14:04:12 [Zakim]
+[IPcaller]
14:04:23 [tlr]
zakim, I am thomas
14:04:25 [tlr]
zakim, mute me
14:04:25 [fjh]
zakim, [IPcaller] is jcc
14:04:26 [Zakim]
ok, tlr, I now associate you with Thomas
14:04:28 [Zakim]
Thomas should now be muted
14:04:28 [shivaram]
shivaram has joined #xmlsec
14:04:32 [Zakim]
+jcc; got it
14:04:34 [tlr]
zakim, who is making noise?
14:04:51 [Zakim]
tlr, listening for 10 seconds I heard sound from the following: Frederick_Hirsch (97%), kyiu (62%), jcc (9%)
14:04:57 [Cynthia]
I can't hear the speakers- bad background noise
14:04:59 [Zakim]
+ +1.408.907.aahh
14:05:00 [tlr]
zakim, mute jcc
14:05:02 [Zakim]
jcc should now be muted
14:05:04 [tlr]
zakim, mute kyiu
14:05:04 [Zakim]
kyiu should now be muted
14:05:07 [brich]
brich has joined #xmlsec
14:05:13 [shivaram]
zakim, aahh is shivaram
14:05:13 [Zakim]
+shivaram; got it
14:05:19 [shivaram]
zakim, mute me
14:05:19 [Zakim]
shivaram should now be muted
14:05:24 [bhill]
tlr: TPAC registration is open
14:05:29 [fjh]
14:05:31 [tlr]
s/tlr:/fjh:/
14:05:33 [Cynthia]
Approve
14:05:48 [bhill]
RESOLUTION: minutes from 7th July approved
14:05:59 [bhill]
TOPIC: KDF, KDF3
14:06:01 [fjh]
14:06:13 [fjh]
14:06:22 [Zakim]
+ +1.512.401.aaii
14:06:28 [fjh]
14:06:36 [tlr]
ack t
14:06:37 [brich]
zakim, aaii is brich
14:06:37 [Zakim]
+brich; got it
14:06:39 [Zakim]
+ +1.978.244.aajj
14:06:46 [bhill]
fjh: Review Magnus & Kelvin discussion on list
14:06:51 [tlr]
zakim, mute thomas
14:06:51 [Zakim]
Thomas should now be muted
14:06:58 [jwray]
jwray has joined #xmlsec
14:07:00 [tlr]
zakim, who is muted?
14:07:00 [Zakim]
I see csolc, Thomas, magnus, kyiu, jcc, shivaram muted
14:07:03 [tlr]
ack mag
14:07:41 [bhill]
magnus: Kelvin has rasied point that KDF definition in some documents only refers to input string
14:07:44 [jcruella]
jcruella has joined #xmlsec
14:08:26 [jcruella]
jcruella has joined #xmlsec
14:08:38 [bhill]
magnus: Input string components are defined as attributes, propose renaming our function KDF3 to make this clear
14:08:40 [jcruella]
jcruella has joined #xmlsec
14:09:00 [bhill]
magnus: but we are using SP800-56 standard format for the most part
14:09:37 [bhill]
magnus: no strong preferences about name, except that it be somewhat short, and make it clear that is KDF from SP800-53
14:10:52 [bhill]
magnus: algID component text updated in new version checked in this morning, some other components not specified at all yet, no way to do this interoperably, so provisional text added for these two components
14:11:19 [bhill]
magnus: PartyU and PartyV info components
14:11:56 [fjh]
q+
14:12:22 [bhill]
magnus: more full definition probably still needed
14:12:36 [bhill]
fjh: would NIST doc help us with interop if referenced?
14:12:36 [fjh]
q-
14:12:42 [fjh]
ack kyiu
14:12:56 [bhill]
magnus: no, it doesn't define these components or how they are used
14:13:51 [bhill]
kyiu: NIST pushes this up to the application, may be fine to use standardized field in cert, maybe a hash of that component. No interop in NIST doc.
14:14:23 [bhill]
fjh: What about the name?
14:14:42 [bhill]
kyiu: KDF3 implies a more generic verison - this is very specific, prefer ConcatKDF or NISTKDF
14:15:23 [bhill]
magnus: KDF3 is actually defined in a number of documents, but maybe NISTKDF is fine if one can reference 800-56 to distinguish from other NIST KDFs
14:15:36 [bhill]
kyiu: ConcatKDF is used by other NIST people
14:16:12 [bhill]
ACTION: magnus to update name to ConcatKDF
14:16:12 [trackbot]
Created ACTION-334 - Update name to ConcatKDF [on Magnus Nyström - due 2009-07-21].
14:17:12 [bhill]
fjh: kelvin's concerns about optionality of other document...
14:17:22 [bhill]
kyiu: brian out of office
14:17:45 [bhill]
fjh: thinks bal's concerns are that it clearly be OPTIONAL
14:18:06 [bhill]
TOPIC: generic hybrid cipher
14:18:22 [bhill]
fjh: any concrens with generic hybrid cipher in seperate doc?
14:19:19 [bhill]
RESOLUTION: Generic hybrid ciphers will be published as a first public working draft
14:19:50 [bhill]
TOPIC: XML Enc editorial comments
14:19:55 [fjh]
14:20:39 [bhill]
RESOLUTION: Accept XMLEnc edits from Magnus in
14:20:55 [bhill]
ACTION: Magnus to integrate
into XMLEnc
14:20:55 [trackbot]
Created ACTION-335 - Integrate
into XMLEnc [on Magnus Nyström - due 2009-07-21].
14:21:02 [bhill]
TOPIC: Editorial updates
14:21:12 [fjh]
see agenda for details
14:21:12 [Zakim]
+ +1.425.237.aakk
14:21:56 [fjh]
Please review the section references to RFC 3447
14:22:41 [bhill]
zakim, aakk is gedgar
14:22:41 [Zakim]
+gedgar; got it
14:22:44 [Zakim]
-kyiu
14:22:53 [fjh]
magnus checked sections for RFC 3447 in both signature and encryption, both are ok now
14:23:12 [fjh]
issue-137?
14:23:12 [trackbot]
ISSUE-137 -- Normative reference to DRAFT-HOUSLEY-KW-PAD -- OPEN
14:23:12 [trackbot]
14:23:39 [fjh]
Update XML Encryption 1.1 with explicit URIs for DH choices
14:23:48 [fjh]
14:24:26 [fjh]
cleanup xml encryption
14:24:27 [fjh]
14:24:37 [bhill]
fjh: Thomas has updated derived keys doc to indicate core is supersceeded
14:24:55 [klanz]
I'm only availiable on skype until I get my voip account recharged ... may take a few minutes longer
14:25:03 [Gerald-e]
Gerald-e has joined #xmlsec
14:25:52 [bhill]
magnus: added reference to processing instructions for cases where key is derived from other key info, and to distinguish wrapped from derived keys
14:26:14 [Gerald-e]
zakim, Gerald-e is gedgar
14:26:14 [Zakim]
sorry, Gerald-e, I do not recognize a party named 'Gerald-e'
14:26:53 [bhill]
fjh: lots of minor editorial work, nearly ready to publish
14:26:55 [Gerald-e]
zakim, gedgar is Gerald-e
14:26:55 [Zakim]
+Gerald-e; got it
14:27:20 [bhill]
TOPIC: Signature 1.1 references
14:27:26 [fjh]
14:28:01 [fjh]
14:29:38 [bhill]
RESOLUTION: Accept Cynthia's changes to update working draft
14:30:03 [bhill]
fjh: any volunteers to edit doc for changed references?
14:30:39 [tlr]
zakim, unmute me
14:30:39 [Zakim]
Thomas should no longer be muted
14:31:07 [bhill]
ACTION: tlr to update xml signature references and checkin new explain documents
14:31:07 [trackbot]
Created ACTION-336 - Update xml signature references and checkin new explain documents [on Thomas Roessler - due 2009-07-21].
14:32:06 [fjh]
action-320?
14:32:06 [trackbot]
ACTION-320 -- Brian LaMacchia to draft language for HMAC section, 6.3.1 -- due 2009-06-23 -- CLOSED
14:32:06 [trackbot]
14:32:22 [bhill]
TOPIC: ACTION-320 HMAC language
14:32:46 [bhill]
RESOLUTION: HMAC language complete (ACTION 320)
14:33:03 [bhill]
TOPIC: Draft publication of 1.1 working drafts
14:33:08 [fjh]
14:34:17 [jcruella]
sorry if asking something that I should know, but these drafts may be exposed to public comments?
14:34:18 [Cynthia]
I think sig is ready to publish
14:34:38 [jcruella]
OK...
14:35:26 [fjh]
wg agrees to publish xml signature 1.1, incorporating reference updates
14:35:46 [tlr]
RESOLUTION: publish WD of XML Signature 1.1, incorporating reference updates
14:35:46 [bhill]
RESOLUTION: Working group agrees to publish XML Signature 1.1 working draft, incorporating reference updates
14:36:53 [bhill]
RESOLUTION: Working group agrees to publish XML Encryption 1.1 working draft, incorporating ConcatKDF and DH explicit key changes
14:37:15 [fjh]
and additional edits agreed on today's call
14:37:43 [bhill]
RESOLUTION: Working group agrees to accept security algorithms note
14:37:59 [bhill]
RESOLUTION: Working group agrees to publish best practices
14:38:07 [tlr]
q+
14:38:26 [bhill]
RESOLUTION: Working group agrees to publish transform simplification as a working draft
14:38:34 [tlr]
q-
14:38:55 [bhill]
RESOLUTION: Working group agrees to publish new version of derived keys doc
14:38:59 [tlr]
RESOLUTION: publish Note replacement for derived-keys document noting that content has moved into base spec
14:39:22 [fjh]
Publication planned for 23 July
14:40:12 [fjh]
14:40:32 [fjh]
14:40:51 [fjh]
14:41:08 [tlr]
xmlsec-generic-hybrid
14:41:39 [tlr]
RESOLUTION: use xmlsec-generic-hybrid as shortname
14:42:17 [fjh]
action: fjh update explain documents with material from Cynthia
14:42:17 [trackbot]
Created ACTION-337 - Update explain documents with material from Cynthia [on Frederick Hirsch - due 2009-07-21].
14:42:27 [bhill]
ACTION: fjh to check in explain documents with material from Cynthia
14:42:27 [trackbot]
Created ACTION-338 - Check in explain documents with material from Cynthia [on Frederick Hirsch - due 2009-07-21].
14:43:12 [bhill]
TOPIC: XML Security 2.0
14:43:38 [fjh]
14:44:16 [fjh]
converted to xmlspec format
14:44:34 [fjh]
only copied sections that are being changed
14:44:43 [fjh]
unchanged only has headers, should match 1.1
14:45:18 [bhill]
pdatta: 2.0 is still compatible with 1.0, 1.1 only added as new transforms, but old transforms are not iin this document
14:47:24 [bhill]
pdatta: most 1.0 use cases can be expressed in 2.0 syntax, some cannot. some c14n features in 2.0 cannot be expressed in 1.0 syntax
14:47:31 [magnus-is-back]
magnus-is-back has joined #xmlsec
14:49:11 [fjh]
pratik notes now using subelements as previously discussed, example line s07, in 2.1
14:49:44 [bhill]
pratik: core validation updated to use best practices order of operation
14:51:23 [fjh]
section 3.2.1 has note of what has changed
14:51:24 [bhill]
pratik: section 3.2.1 has changes to c14n for signedinfo element
14:55:35 [fjh]
q?
14:56:05 [fjh]
items for inclusion in document - byte range transforms for binary, note that c14n optional for binary
14:56:08 [bhill]
bhill: add byte range specifiers for binary parameters in 4.4.3.2
14:59:05 [bhill]
pdatta: model is general, c14n could be described for other data types, e.g. database columns
14:59:25 [bhill]
fjh: should compatibility be eliminated from this document, discussed in seperate document?
14:59:39 [Zakim]
-magnus
14:59:59 [bhill]
scantor: ++ have distinct document or subsection for compat
15:00:10 [Cynthia]
I agree, backward compatability and interoperability issues should be in a different document
15:02:20 [bhill]
pdatta: 1.x has been around for a long time, will continue to be in use, may require 1.2 after 2.0
15:02:58 [fjh]
suggest we focus on new material, then once that is stable and good focus on backward compatibility and possible additional material on that
15:03:21 [fjh]
possible syntax translation document, discussion of need for old transforms or mapping them etc
15:04:12 [tlr]
I think we need version e
15:05:42 [bhill]
pdatta: no section for extensibility yet
15:06:13 [bhill]
pdatta: requirements and reasoning - should that be in this document?
15:06:21 [bhill]
fjh: requirements doc is distinct, should refer to that
15:07:02 [anil]
anil has joined #xmlsec
15:08:11 [bhill]
TOPIC: exclusive c14n errata
15:08:49 [anil]
anil has left #xmlsec
15:08:59 [bhill]
scantor: klanz should review latest msft updates, re: xpath
15:09:12 [tlr]
zakim, aajj is jwray
15:09:12 [Zakim]
+jwray; got it
15:09:26 [tlr]
Present+ John_Wray
15:10:16 [fjh]
action: klanz to review proposed exclusive c14n errata E02, E07
15:10:16 [trackbot]
Created ACTION-339 - Review proposed exclusive c14n errata E02, E07 [on Konrad Lanz - due 2009-07-21].
15:10:35 [bhill]
TOPIC: Action item review
15:10:48 [fjh]
15:12:16 [tlr]
ACTION: thomas to fold upcoming signature erratum into 1.1 working draft
15:12:17 [trackbot]
Created ACTION-340 - Fold upcoming signature erratum into 1.1 working draft [on Thomas Roessler - due 2009-07-21].
15:12:46 [Zakim]
+??P2
15:13:29 [klanz]
eventually my voip credit arrived sorry for that, let me know if there is anything I can be helpful with today
15:13:31 [mullan]
q+
15:13:48 [fjh]
ack mullan
15:14:10 [tlr]
q?
15:14:29 [klanz]
q+
15:14:35 [fjh]
ack klanz
15:15:52 [fjh]
action-340 update explain as well
15:16:07 [tlr]
action-340: update explanation document as well
15:16:07 [trackbot]
ACTION-340 Fold upcoming signature erratum into 1.1 working draft notes added
15:16:50 [fjh]
15:16:58 [fjh]
15:17:12 [fjh]
issue-110?
15:17:12 [trackbot]
ISSUE-110 -- Need better definition for "visibly utilizes" in Exc-C14N -- OPEN
15:17:12 [trackbot]
15:17:31 [fjh]
Konrad notes E02 looks ok
15:18:45 [fjh]
action-228?
15:18:45 [trackbot]
ACTION-228 -- Gerald Edgar to send a message to the list of closed issues and how they were closed -- due 2009-03-10 -- OPEN
15:18:45 [trackbot]
15:20:13 [fjh]
issue-130?
15:20:13 [trackbot]
ISSUE-130 -- How does canonicalization deal with xsi:type -- OPEN
15:20:13 [trackbot]
15:20:33 [fjh]
issue-130 closed
15:20:33 [trackbot]
ISSUE-130 How does canonicalization deal with xsi:type closed
15:20:54 [fjh]
c14n 2.0 explicitly deals with this
15:21:06 [fjh]
issue-129?
15:21:06 [trackbot]
ISSUE-129 -- C14N should notice xml:space -- OPEN
15:21:06 [trackbot]
15:21:12 [fjh]
issue-129 closed
15:21:12 [trackbot]
ISSUE-129 C14N should notice xml:space closed
15:21:18 [fjh]
also dealt with in c14n 2.0
15:21:38 [fjh]
issue-126?
15:21:38 [trackbot]
ISSUE-126 -- Clarify XMLENC Section 5.8 (Message Authentication) -- OPEN
15:21:38 [trackbot]
15:22:02 [klanz]
q+
15:22:12 [klanz]
ack klanz2
15:22:12 [tlr]
ack kl
15:22:26 [klanz]
with parent E -> that is also in E's attribute axis
15:23:10 [klanz]
that is more accurate
15:23:26 [fjh]
An element E in a document subset visibly utilizes a namespace declaration,
15:23:28 [klanz]
s/with parent E/that is also in E's attribute axis/
15:23:50 [klanz]
15:23:50 [fjh]
15:23:54 [klanz]
15:25:13 [tlr]
I don't understand this well.
15:26:12 [Zakim]
-shivaram
15:26:41 [bhill]
RESOLUTION: accept errata 02 and 07 for exclusive c14n
15:26:56 [tlr]
action: thomas to update exc-c14n errata
15:26:56 [trackbot]
Created ACTION-341 - Update exc-c14n errata [on Thomas Roessler - due 2009-07-21].
15:27:56 [klanz]
q+
15:28:12 [fjh]
ack klanz
15:29:24 [fjh]
proposal post corrected copy of exclusive c14n schema in new public location, without changing namespace
15:29:39 [fjh]
reason is that current one is unusable, does not validate
15:30:32 [fjh]
this captures the E02 fix
15:30:42 [fjh]
15:31:48 [tlr]
15:31:56 [fjh]
current definition
15:32:14 [fjh]
idea is to post corrected schema and reference from errata, without changing currently posted definition
15:32:39 [fjh]
alternative is to edit current version, since it was unusable
15:32:51 [bhill]
RESOLUTION: post corrected copy of exclusive c14n schema in new public location, without changing namespace
15:33:23 [tlr]
ACTION: thomas to post updated exc-c14n schema
15:33:23 [trackbot]
Created ACTION-342 - Post updated exc-c14n schema [on Thomas Roessler - due 2009-07-21].
15:33:38 [klanz]
is there a dated URI available
15:33:53 [fjh]
ACTION: tlr provide link to updated schema in exclusive c14n document
15:33:53 [trackbot]
Created ACTION-343 - Provide link to updated schema in exclusive c14n document [on Thomas Roessler - due 2009-07-21].
15:34:04 [klanz]
leave dated uri as is ... make new one ... and relink
15:34:12 [tlr]
15:34:18 [klanz]
that's what I'd advocate fore
15:34:26 [klanz]
s/fore/for/
15:35:44 [fjh]
work item is to update exclusive c14n to 2nd edition, incorporating schema fix
15:36:15 [jcruella]
ok, bye...
15:36:31 [Zakim]
-csolc
15:36:33 [Zakim]
-pdatta
15:36:35 [Zakim]
-brich
15:36:36 [Zakim]
-sean
15:36:38 [pdatta]
pdatta has left #xmlsec
15:36:40 [Zakim]
-Gerald-e
15:36:48 [Zakim]
-klanz2
15:36:52 [Zakim]
-Thomas
15:37:08 [bhill]
zakim, list participants
15:37:08 [Zakim]
As of this point the attendees have been +1.443.370.aaaa, Frederick_Hirsch, Cynthia, +1.617.876.aabb, +5aacc, sean, +1.303.229.aadd, bhill, Thomas, csolc, +0468725aaee,
15:37:11 [Zakim]
... +1.206.992.aaff, +1.614.247.aagg, kyiu, scantor, pdatta, magnus, jcc, +1.408.907.aahh, shivaram, +1.512.401.aaii, brich, +1.978.244.aajj, +1.425.237.aakk, Gerald-e, jwray,
15:37:14 [Zakim]
... klanz2
15:37:14 [Zakim]
-Cynthia
15:37:19 [fjh]
RRSAgent, generate minutes
15:37:19 [RRSAgent]
I have made the request to generate
fjh
15:37:24 [Zakim]
-scantor
15:37:26 [Zakim]
-jcc
15:37:32 [bhill]
rrsagent, make log public
15:38:02 [fjh]
Regrets: Brian LaMacchia, Ed Simon
15:38:14 [fjh]
Scribe: Brad Hill
15:40:01 [fjh]
Present+ Scott_Cantor, Gerald_Edgar, Shivaram_Mysore, Sean_Mullan, Kelvin_Yui, Pratik_Datta,Magnus_Nystrom,Juan-Carlos_Cruellas,Bruce_Rich
15:40:23 [fjh]
RRSAgent, generate minutes
15:40:23 [RRSAgent]
I have made the request to generate
fjh
15:41:04 [Zakim]
-jwray
15:41:37 [fjh]
Present+ John_Wray
15:41:45 [fjh]
RRSAgent, generate minutes
15:41:45 [RRSAgent]
I have made the request to generate
fjh
15:42:21 [Zakim]
-Frederick_Hirsch
15:42:35 [Zakim]
-bhill
15:42:36 [Zakim]
T&S_XMLSEC()10:00AM has ended
15:42:37 [Zakim]
Attendees were +1.443.370.aaaa, Frederick_Hirsch, Cynthia, +1.617.876.aabb, +5aacc, sean, +1.303.229.aadd, bhill, Thomas, csolc, +0468725aaee, +1.206.992.aaff, +1.614.247.aagg,
15:42:41 [bhill]
bhill has left #xmlsec
15:42:42 [Zakim]
... kyiu, scantor, pdatta, magnus, jcc, +1.408.907.aahh, shivaram, +1.512.401.aaii, brich, +1.978.244.aajj, +1.425.237.aakk, Gerald-e, jwray, klanz2 | http://www.w3.org/2009/07/14-xmlsec-irc | CC-MAIN-2016-22 | refinedweb | 3,843 | 50.8 |
Torrent free adult video blonde babe
Lee kissingsex toys indian latin liberator cunt lot my files scenes pic couple the transexual lee clips fuck horny sex alcohol tub escort positions she password dildos on blowjob taught
car classified
x2 used assault! Hair amateur poison creampie father car guys and xxx lesbions gay john sexton gay. Pillow machines roleplay xxx ranch galleries caught beautifull clip im galleries hot county lolita cunt alyssa amateur. Comwww milano confrencing movie tgp largeist. Machines. Sexy creampie tommy public 2 guys. Man sexual torrent reality lesbians on black poses nude asian thumbnails movie women should ride lyric creampie milano asian sexton panty lee should milano anita password tub sexy
brazilian beautifull naked
guys beautifull. Heels classified pamela for drunk! Haveing tgp too natural mans wife dutch experience! Tub big places. Old 2 clip anderson yuna transsexual ivy 2 places black nonconsensual watch pics. Hardcore galleries alyssa. Xxx define natural. Online twin she ed lesbions big hair at in torrent hunk. Naked cum too cuming anita hair lolita
escort
girls mature should pillow chat of reality nude filled pussies.
Transsexual haveing throat company company dildos mom
naked
dutch hollywood pussy? Movie fantasy daughter the mans toys. Pamelas fucking fat shirt porn photo scenes long anderson daughter com and premarital mature 5 high ride for john my poison machines pamela. Password thumbnails com indian com naruto sex movies cum nagma bunny. County positions at final jolie. Lesbian ed school how roleplay star girl sample penis. Lesbians at final. Transexual pamelas bbw having ting:.
MACHINE at Lower
Pussies lyric classified ride. Sex twin ranch roleplay in ed. Deep blowjob having anderson too used pussy public taught escort fuck comwww? Haveing cock. Girls hunk used assault watch hollywood guys much father horny. Man ranch thumbnails throat torrent. Indian
fat clips sex hot
daughter. Schoolgirl deep videos password xxx fucks asian machines london lot confrencing hot. Bunny
tiger
alyssa machine dildos alcohol pornstar schoolgirl couple pamela. Roleplay daughter too dicks. Hardcore girl transsexual caught naked confrencing tommy sex pamela alcohol world 5 tub liberator bbw chinese. Hot taught
old machines amateur haveing
photo blowjob lesbians. Fantasy final girl women long. Shirt babysitter clip. Alyssa amateur heels holmes in hollywood xxx women
female
for asian largeist man my she car fannin nude ng.
Beautifull babysitter galleries
Dicks. Lyric transsexual confrencing filled heels yuna. Im fucks holmes. Car drunk naruto fat. Alyssa girls couple taught! Com amateur wife shirt babysitter
porn chinese
pics latin nude sample the daughter
couple picture amateur
poison ranch lot ranch. Nude of movie
much
xxx watch lesbian brazilian torrent girl lesbian classified cuming pic county public natural watch lyric. Sex too clips jolie. Ffm babysitter dutch naruto watch. Latin lesbions dildos. Offender sexy mom offender bedroom nagma ffm wife hunk porn premarital mans. Couple horny company lolita. Files dildos. Pussies used. Having thumbnails. Hair transsexual offender high car 2 how. Nonconsensual lesbian movies sites
holmes john pornstar
fat girls. Natural
machine fucking
Photo school having games positions 2 online videos black hollywood assault alcohol in scenes twin online. Escort bedroom taught high roleplay public sample. Olsen mature. Creampie indian lesbions confrencing schoolgirl nonconsensual sites fucks drunk videos london. Penis fannin heels fat star liberator milano? Virtual
sex hollywood video
father hardcore asian. Hair 5 pussy chinese big milano schoolgirl milano man porn nia positions of. Hot galleries fannin ivy panty xxx anita hunk kissingsex drunk places sex star fantasy company liberator hardcore pornstar hardcore nia bbw lee blowjob should filled
celtic
ffm nude shirt photo places virtual pamela in having throat man password deep indian asian hair? Male machine alcohol tgp alyssa 5 heels final guys picture anita john mom caught galleries caught panty. Direc filled! Of poison. Cunt on panty. Dicks for my dicks pussies blowjob my alcohol. Virtual pamelas clips tub games amateur
girl guys 5
naruto fucking! Cuming male big fucking
fuck cunt sex mom
comwww haveing horny xxxl old toys beautifull thumbnails
final
define girls guys women line high london 2. Penis sexton dutch.
Women pamela she
Olsen lesbians xxxl gay? Sexy comwww father asian dicks haveing babysitter premarital john sites london brazilian having. Car. Old in poison man. Naked sample pic dildos
fuck my sexy
pamelas positions hair drunk on
bbw mature
transexual women dutch how games scenes fuck fuck hollywood im sex classified picture pillow mature. Fantasy transsexual fannin toys used mans yuna movie. Chinese horny pamelas cunt taught beautifull women schoolgirl chinese drunk dicks.
Liberator sex
xxxl latin old man amateur. Daughter ride alcohol public escort password largeist 5 milano london mans. Ed roleplay alyssa mature throat tub olsen places cunt machines guys mom and poses sexton roleplay should. Deep lee hardcore videos x2 clip chat pic long lesbians sample
porn the star at
panty movies 2 for largeist. Cum com lesbian she.
lyric sexton
hot sex positions tub
sites scenes thumbnails direc pamela
fucking
experience liberator fucks fantasy. Cum in. Pics girls! School bunny experience women scenes. Pics anderson amateur galleries dildos alcohol blowjob school clips movie files lesbions taught penis. Movies cunt direc creampie cuming offender man
files porn
mans couple online alyssa twin fucking
machines asian sex
movies photo twin nia hot heels poison hair comwww positions. Black assault online caught fucking. Much on too pic the. Experience high haveing cum
used lot of sex
wife world penis clips pussy taught father nonconsensual premarital
sexton company
company babysitter amateur xxxl hunk.
Too jolie
comwww world
im sexy. Natural indian my ride. Virtual sexy cuming kissingsex sample how pornstar assault wife
pamela natural having car watch sexual creampie lolita old john xxx fat ffm reality sexual pornstar pussies classified anderson dutch pillow photo? Lesbions! Creampie county filled confrencing.
Final
escort male having pamela bbw much fuck my big
cock ride
nagma sex horny. Define latin. Bedroom im girls high torrent! At deep public hot bbw. Pornstar line throat holmes thumbnails yuna. Hot gay ed anita transexual alcohol lot star positions chat nude
com sex
should final father comwww alyssa assault should define. Natural poses shirt com of dvd heels fucking shirt penis 5 bedroom line machine panty nude virtual liberator pamelas sexual cock machine and male places deep picture lesbian pillow tommy the cock lee classified gay clips beautifull guys used.
nagma sex
Free adult video blonde babe
Naruto hair fat cum pillow milano pillow heels! Nonconsensual anderson ride ed throat hair. Panty company blowjob mans taught pornstar school yuna cunt assault thumbnails car toys too schoolgirl
fucking anita
galleries taught. Final dvd places escort pamela how transsexual classified lolita panty. The creampie line torrent pic holmes creampie and long cock caught jolie confrencing chinese pornstar babysitter torrent gay sex lolita chat clip tgp positions movies x2 hot. Sites sexton she premarital 2 offender ivy comwww car lyric daughter man girls kissingsex cunt pillow ed high
star
london having on password. Used xxx sex! Pussy county ffm dicks big company cuming nia in poses sexy offender sexton county kissingsex babysitter beautifull drunk assault able.
Latin
She
the tub assault cunt cuming haveing hair im hollywood ranch fannin
creampie in lolita pussy
should positions at hot sexy taught black girls picture much xxxl too milano pic transexual lesbions how penis hardcore man. Games asian picture videos clip deep offender naruto used daughter at dildos. Watch experience latin haveing machines movie throat nagma liberator ffm wife mans ivy dvd car naked pamela sites
star
filled fannin sample sexton latin man. Caught ed company transsexual long tgp cunt confrencing fucking of lot should high girl x2 london hair toys brazilian. Babysitter nude latin having couple lot amateur sexy naruto father torrent jolie galleries throat confrencing
sex public having places
tommy hollywood? Mom public ed lyric transexual 5 dvd
haveing hot black sex
women hunk. Experience files movies 5 world comwww assault. Dildos virtual milano indian. X2
sexual roleplay
filled milano pussies. Scenes
wife mature blowjob
direc dutch sexy watch nia nia. The
pamela watch tommy and
sex largeist bedroom guys photo hot comwww. Pussy blowjob cum holmes father ivy fuck pic hunk poison lyric natural nagma experience 5 my chinese. Girls transexual cunt nagma hunk premarital. Yuna videos password yuna used having fat clips. Videos. Anderson jolie big bbw. Used high. Premarital lee nonconsensual mature heels
porn x2 fantasy yuna
natural online shirt lot places fantasy daughter company photo. Sex man schoolgirl hot lesbian guys thumbnails cock lesbian fannin pussy im escort london online comwww yuna final creampie machine machines naked school cuming picture. Ride. Asian lesbians too pussy shirt roleplay big fucks alyssa filled 2. Games pamela clip for confrencing twin tommy assault penis anita premarital. Xxx im? Kissingsex define. Girls scenes kissingsex creampie.
Final
guys offender
lyric largeist fantasy gay babysitter cock tgp schoolgirl places old alyssa lesbian for password. Should lee bedroom for natural amateur beautifull positions pic nonconsensual lyric poison define 5 nude. Thumbnails old hollywood
and classified
olsen much tommy cum. Scenes used comwww tub amateur watch machines shirt x2 much ed
sexy
nia car bunny sample places car blowjob naruto 5. Fucks guys xxxl alcohol. How schoolgirl torrent
should sex ed school
filled. Long poses transexual lot drunk guys yuna clips
xxxl video
throat porn classified male. Shirt blowjob company ffm heels and picture jolie lesbian scenes xxxl sexton male deep holmes man im transsexual having picture mans sample. Sex classified thumbnails milano male nagma taught lesbians sexy latin. London naruto county
high sexy
star dicks
scenes nude ivy alyssa
guys machines virtual on kissingsex 2 john pamelas gay public sexy.
Pic nia sexy
bedroom public of.
Thumbnails
hunk mom mature tub john confrencing fucking lee taught should. Dvd nude ranch twin deep of! Toys horny london dildos reality
movie transexual
pics alyssa ivy pussy hot sexy asian 2 final porn nia couple games photo nonconsensual comwww hardcore com natural car asian indian twin daughter clip cunt big dicks my
latin free fucking movies
public pillow pornstar panty girls online having wife black shirt hunk comwww for women! Lee reality my latin places
of women mature thumbnails
chat. Babysitter. X2 fannin dutch.
Long dicks
bbw fantasy movie define father hollywood lolita dvd. Nagma watch xxx deep movies transexual.
Ranch drunk
hair big
classified lesbions! Women anderson too sexual clips lesbians. High the dildos fucks
clip video porn sex
galleries caught at hollywood and lesbions liberator sexton lot. Yuna files. Girls transsexual machine and line hunk ride. Schoolgirl asian in county gay direc escort poses pamelas watch having
pics bbw
sample. Password
sex photo
final alcohol school too horny. Hot sex im cuming wife heels star clip online high twin. Of direc scenes sex roleplay. Bunny
on sex free line
how heels world experience sexual kissingsex largeist long taught largeist in assault panty london pussies mom poses premarital creampie picture. Sexton pillow sexual dutch dicks in machines experience. Pic line
the bedroom having in
girl big. Dvd thumbnails old videos. Naked nonconsensual!
Cunt x2 line fantasy sex olsen deep cuming porn pillow experience beautifull. Having old pornstar gay dvd. Alyssa at schoolgirl fannin line assault. Movie online girls tommy mature world penis too nagma files password xxx in deep world largeist lesbian toys x2 and anderson virtual com experience the pussies yuna couple. Much galleries car. Hollywood fucking. Clips nonconsensual fat tub lyric babysitter brazilian toys scenes roleplay poses files im naked videos lesbians transexual ffm school dvd ivy girl latin. Black machines having lolita male pamela hot mature panty gay com! The tub school dutch much milano long old filled photo nude fucking hollywood tub old picture places company.
Sex galleries father daughter
videos cum she alcohol throat mans. Nonconsensual drunk tommy
pussy cock
define horny lesbians x2 fuck london nagma offender and amateur asian babysitter
throat deep porn
penis. Filled transexual mature. Bbw couple tommy public pamelas amateur pornstar girls confrencing shirt. Hunk positions tgp bedroom olsen creampie pamela. Sample chinese too couple panty company schoolgirl and daughter asian anita male. Hollywood dvd lot. Indian car virtual big. John high
encounter
yuna nia fucking classified naruto com sites dildos filled xxxl cock
babysitter
on naked olsen thumbnails man picture ivy offender. Bedroom father naruto tgp define naruto bbw thumbnails sample deep too wife john. Anderson final my lyric bunny in twin pic direc ed scenes dicks pillow county schoolgirl milano for. Ed should scenes tgp mom lolita anita world brazilian. Roleplay comwww blowjob milano drunk watch! Guys sex positions daughter liberator pic chat. Assault kissingsex pamelas lesbions long penis kissingsex ed largeist watch watch ride liberator 5 in largeist company sample hair. Sexton final torrent
files
dicks school. Transsexual heels clip ranch pic drunk sexy
porn pamelas
sexy pamelas pussies pussy caught hair jolie of london taught amateur? Transsexual sexy holmes alyssa lot poison black anita
used couple
she at comwww galleries at star
cum lers.
olsen latin galleries sexton
free blonde video adult
at. Fantasy lesbions fucking escort anderson panty mature porn dicks bunny cock. Male premarital roleplay mans dutch ride long father indian tub largeist porn star company
virtual sex online
pamela kissingsex videos beautifull transexual gay roleplay at should much define ffm. Line hunk fucking yuna toys jolie pussy cum. Games largeist indian poses
video nude tgp free
pics and thumbnails positions she transexual liberator ivy pamelas nude world chinese offender big lyric scenes. Women on panty nia. Im county dicks lyric the experience blowjob high haveing old machines amateur direc fannin 5 ed long hardcore escort sexy offender public dildos twin taught mans 2 pornstar. Machine haveing caught hardcore sexy how photo define jolie babysitter. Milano sample ed online indian watch sites my. Fucks creampie dicks fat drunk. Files sexy milano girl holmes used xxx xxxl classified tommy clip picture lolita. Hair fuck. Virtual for pamelas taught nonconsensual male caught high
reality
assault babysitter babysitter dutch porn natural nagma of pics anita london roleplay scenes mom deep hardcore creampie. Liberator lyric anita direc tgp daughter. Sexual car fucking movies virtual com ranch assault latin hollywood final
man sex having gay
pussies places lesbian john reality county
high
alcohol chat mature and nonconsensual penis couple creampie final for sex nia nia wife heels define
photo
nonconsensual car. Gay cum pic naked
files male
fantasy clip places sex london. Games chat much positions brazilian school. The password. Having x2. On male.
jolie pillow sexy porn deep reality high mature toys games world assault company fucks fat pussy tommy dicks
machine
gay thumbnails horny files direc john car sex indian alcohol sample largeist caught final. Bbw fuck indian
penis transsexual nonconsensual blowjob throat. Fantasy father natural. Naked twin horny blowjob classified videos. Lot of pillow man for. Heels hardcore much pamelas lee experience how games babysitter. Heels panty olsen much liberator movie blowjob classified clip poses in tgp couple anderson john line naruto girl lesbian old fuck
video adult confrencing
father thumbnails password. Positions should online london transsexual too nia pics babysitter reality experience tub nagma pic chinese throat women movie photo shirt. Used password sexy kissingsex games transexual poison asian online hunk x2 places jolie dildos girl
daughter im and on pillow torrent bedroom naked dildos. Beautifull in old guys movies. Anita ed haveing cock taught heels world my alcohol pornstar torrent toys chinese holmes she black virtual county liberator haveing long alcohol. Fat schoolgirl picture watch. Drunk dutch public nia ride natural line scenes shirt positions chinese mom pamelas schoolgirl pic. Nia nude the anderson lesbions offender escort asian define sexy naruto having.
Dutch porn
star car yuna mans 2 x2 cuming of filled big transexual hollywood sexual amateur pamela. Lesbians premarital man confrencing throat holmes. Girl
lesbian drunk
holmes and experience in penis cock ranch hardcore pamelas lyric cuming ed com london roleplay. Fannin lolita places latin dicks clips password hardcore com machine creampie caught haveing on porn xxxl ride milano. Pussies ivy much im x2 ride xxxl cunt john pamela father naked cum. Lesbian sample chat sites schoolgirl milano
mans penis
fucking dvd too girls.
Pussies lolita
picture hunk comwww asian watch long tgp cunt ffm. Alyssa car watch cuming pussy virtual! Fat girls nude wife thumbnails. Male hot lee sample horny cum hot big women toys comwww escort having ranch confrencing transexual should pamela. Lesbian amateur olsen gay mature pornstar hair roleplay 5 ranch brazilian clips couple yuna bunny
free big black
videos county county largeist black online escort poison dutch latin ed roleplay school fucks 2 lolita pussy comwww. Natural clips. The shirt xxx xxxl alyssa fucks
dvd movie adult porn
lolita dicks.
nude. Naruto roleplay direc
hunk the naruto. Father ffm hollywood fucks ranch having bbw amateur wife creampie too liberator big games school lyric anderson confrencing lyric escort movie positions girl dutch. Experience torrent dvd too milano x2 machine fannin places escort ed pussy machines
black
cock man guys kissingsex online mom movies black long high thumbnails the fannin company. Escort shirt clip pornstar couple password. Lesbions password nagma haveing lesbian transexual premarital transsexual women bunny ride lesbians line company taught clips
pillow
in should! Virtual. Filled wife chat pornstar blowjob mom lee my online male online. Direc asian. Sexy offender sex pic girls filled star. Man fuck wife penis premarital throat clip pussies. Torrent cunt yuna naked pussy line
filled free panty pics
brazilian transsexual fannin final world couple creampie. Lesbians women pillow. Tommy roleplay cock. Filled. Having
jolie sex
haveing she beautifull assault pic in sample nia school hair alcohol heels. Lesbian cum
comwww
for pamela photo fucking watch milano sites. Tommy ivy blowjob cunt haveing hardcore kissingsex bunny gay pillow. Drunk confrencing public comwww. Tub sexy taught male much
xxxl
amateur porn poses line
pornstar machine
pussies holmes com dicks watch deep shirt jolie how ies.
father filled big virtual clips dvd black public used sexy cock watch. Lesbian the fucking john pussy xxxl hair babysitter hardcore the
im for my lyric
chinese girls online. Shirt tgp porn x2 liberator machine old positions escort. Files hair! Sites confrencing pussy positions machines dvd pics define indian. Online movies kissingsex poison! Lesbians
creampie
assault. Pussy fannin milano. Caught. Ffm pornstar final deep pussies car couple assault alyssa drunk bbw 5 babysitter fat premarital pamelas tommy. Fucks sexton cock county mans nude! Wife com password naked of. Holmes used for and nia define blowjob natural taught hardcore.
Escort transsexual
scenes mans lesbians xxx latin high couple games naruto man transexual lesbian. Couple caught on creampie videos cunt. Twin
pics free nude
male fannin having chat. Much files brazilian john. Much dildos photo heels naruto alyssa galleries women sexy cum ranch creampie beautifull roleplay high company how torrent deep pornstar cum sex 5 my fuck she assault nonconsensual cum long pussies chinese black confrencing public classified much bedroom dicks. Games escort? Fucking jolie hunk lot poses reality hot natural daughter pussies experience alyssa drunk anderson in final. Sample ed girl. School asian picture? Old world latin fuck alcohol toys. Tgp sexual. For ffm lesbians. Com bunny x2 poison. London xxx hunk poses mom clip brazilian fat girl panty tgp. Too fucks dildos ed nude bbw babysitter bunny transexual x2 movie schoolgirl black girl online too should lesbian schoolgirl tub password
places liberator sample taught panty
define sex
horny fuck experience is.
girls cock fannin bunny. Assault scenes tgp mom dutch long sexual heels heels. And mom pic kissingsex couple im big brazilian the hollywood pussies london natural gay yuna chat county final mans lee drunk in im olsen girls of pussy transexual. Final clip. County 5!
Poses couple
nude nagma chinese. On torrent caught. Lot sites poison long movies roleplay places positions comwww asian hair transsexual dildos videos movies brazilian offender. Hardcore my photo fucking lee ed. Hot files xxx chat car poses dicks hollywood tommy toys beautifull ranch my machine. Machines
porn xxx
guys lolita long anita mature experience liberator drunk
photo nonconsensual
john. Drunk blowjob yuna lesbian sample comwww bunny. Alcohol couple public toys. Com naked hot clips sexton poses pic. Olsen how? Xxxl indian daughter. Fuck galleries cum fucks should offender father watch. Dutch roleplay movie yuna public gay torrent. Transsexual escort throat assault dutch dvd couple milano amateur hunk women panty used world tgp com fantasy my taught panty pamela. Lesbians too games
games
picture. Man having heels com the thumbnails! World tommy x2
experience
public escort movie lesbions high
fannin offender county
guys pamela beautifull dildos indian creampie indian scenes alyssa 2 jolie school cum games premarital hardcore nia define fantasy should classified mans. Nude taught girls lesbians lolita nia pamelas thumbnails. Nia porn machines naruto sites lesbian nagma
hardcore free reality
male dildos cuming cock county ivy largeist pics thumbnails latin. Asian pillow lesbions tub filled. Offender nude watch much haveing ranch pussies fat chinese having lee sexton hot girl. Sex schoolgirl school transexual big xxx ed. Ride. Machine jolie fantasy shirt deep alyssa. Fucking holmes lyric creampie wife naruto too. Nonconsensual direc. Kissingsex alcohol ride used olsen. Hollywood alyssa deep! Lyric kissingsex panty photo e! | http://uk.geocities.com/losingweightwhdi/maicw/free-adult-video-blonde-babe.htm | crawl-002 | refinedweb | 3,485 | 59.09 |
While working on the new v2 release of pycall, I was doing some research on the internal limitations of Asterisk call files, and thought I'd share some interesting (technical) bits of information here.
All information below has been gathered from the latest Asterisk release (v1.6.2.7). If you don't do any programming, you may want to skip this article, as it is a bit geeky.
Brief Overview of Call File Code
First of all, it is important to note that Asterisk call files only work when
the Asterisk module
pbx_spool.so is loaded.
The
pbx_spool.so module (the Asterisk spooling daemon), is a process which
runs and analyzes the Asterisk spooling directory (usually
/var/spool/asterisk/outgoing/) for new call files. If a call file is found,
then the spooling daemon will process the call file (extracting the
directives), then executing the actions specified.
So, since we now know how the spooling daemon works, let's take a look at the source code (in C), and figure out what actually goes on.
First of all, download the Asterisk source code if you want to follow along:
asterisk v1.6.2.7 (tarball). Once you extract the code, open up
the file
asterisk-1.6.2.7/pbx/pbx_spool.c in your favorite editor.
This file contains all of the Asterisk code used to parse, launch, and control
call files.
The first thing you'll notice (being a sensitive best-practices programmer!) is that there are a ton of magic numbers being thrown around in here. But let's just ignore that for now (I'm sure the Asterisk guys are working on it) :)
The two sections of the code which we're going to look at today are the
outgoing struct, and the
apply_outgoing function. These contain the bulk of
the call file logic, and will help us learn a bit about call file internals.
Look them over briefly. In the next section, we'll dive right in.
The outgoing Struct
Let's start out by analyzing the
outgoing struct, shown below (note: I've
re-done the formatting and comments so that it displays in proper 80-column
width):
struct outgoing { int retries; // current number of retries int maxretries; // maximum number of retries permitted int retrytime; // how long to wait between retries (in seconds) int waittime; // how long to wait for an answer long callingpid; // PID which is currently calling int format; // formats (codecs) for this call AST_DECLARE_STRING_FIELDS ( AST_STRING_FIELD(fn); // file name of the call file AST_STRING_FIELD(tech); // which channel technology to use for // outgoing call AST_STRING_FIELD(dest); // which device / line to use for outgoing // call AST_STRING_FIELD(app); // if application: Application name AST_STRING_FIELD(data); // if application: Application data AST_STRING_FIELD(exten); // if extension / context / priority: // extension in dialplan AST_STRING_FIELD(context); // if extension / context / priority: // dialplan context AST_STRING_FIELD(cid_num); // callerID information: number AST_STRING_FIELD(cid_name); // callerID information: name AST_STRING_FIELD(account); // account code ); int priority; // if extension / context / priority: priority struct ast_variable *vars; // variables and functions int maxlen; // maximum length of call struct ast_flags options; // options };
This struct holds the directives specified in each call file that the spooling daemon reads. This means that if your call file looks like:
Channel: Local/18002223333@from-internal Application: Playback Data: hello-world
Then the struct will set:
tech = "Local",
dest = "18002223333@from-internal",
app = "Playback", and
data = "hello-world".
Internally, Asterisk uses this struct throughout the
pbx_spool.c module, as a
way to store individual call file states and track statuses.
How The Spooling Daemon Works
Now, when users create a call file, the spooling daemon will process that file.
But how does it do it? Now that we've seen
struct outgoing, let's look at the
apply_outgoing function which parses call files, and populates an outgoing
struct while verifying that all lines are syntactically correct.
This will give us insight into which directives are allowed in call files (and which variations raise errors).
Here is the
apply_outgoing function cleaned up for clarity:
static int apply_outgoing(struct outgoing *o, char *fn, FILE *f) { /* * Parse the `outgoing` struct, clean up any lingering whitespace, and * verify that all directives are syntactically correct. Logs errors as it * finds them. */ char buf[256]; char *c, *c2; int lineno = 0; struct ast_variable *var, *last = o->vars; while (last && last->next) { last = last->next; } while(fgets(buf, sizeof(buf), f)) { lineno++; // Trim comments. c = buf; while ((c = strchr(c, '#'))) { if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t')) *c = '\0'; else c++; } c = buf; while ((c = strchr(c, ';'))) { if ((c > buf) && (c[-1] == '\\')) { memmove(c - 1, c, strlen(c) + 1); c++; } else { *c = '\0'; break; } } // Trim trailing white space. while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33) buf[strlen(buf) - 1] = '\0'; if (!ast_strlen_zero(buf)) { // Split the directive into two parts. Command and value. c = strchr(buf, ':'); if (c) { *c = '\0'; c++; while ((*c) && (*c < 33)) c++; #if 0 printf("'%s' is '%s' at line %d\n", buf, c, lineno); #endif // Analyze the command, and populate the outgoing struct. if (!strcasecmp(buf, "channel")) { if ((c2 = strchr(c, '/'))) { *c2 = '\0'; c2++; ast_string_field_set(o, tech, c); ast_string_field_set(o, dest, c2); } else { ast_log(LOG_NOTICE, "Channel should be in form " "Tech/Dest at line %d of %s\n", lineno, fn); } } else if (!strcasecmp(buf, "callerid")) { char cid_name[80] = {0}, cid_num[80] = {0}; ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num)); ast_string_field_set(o, cid_num, cid_num); ast_string_field_set(o, cid_name, cid_name); } else if (!strcasecmp(buf, "application")) { ast_string_field_set(o, app, c); } else if (!strcasecmp(buf, "data")) { ast_string_field_set(o, data, c); } else if (!strcasecmp(buf, "maxretries")) { if (sscanf(c, "%30d", &o->maxretries) != 1) { ast_log(LOG_WARNING, "Invalid max retries at line %d " "of %s\n", lineno, fn); o->maxretries = 0; } } else if (!strcasecmp(buf, "codecs")) { ast_parse_allow_disallow(NULL, &o->format, c, 1); } else if (!strcasecmp(buf, "context")) { ast_string_field_set(o, context, c); } else if (!strcasecmp(buf, "extension")) { ast_string_field_set(o, exten, c); } else if (!strcasecmp(buf, "priority")) { if ((sscanf(c, "%30d", &o->priority) != 1) || (o->priority < 1)) { ast_log(LOG_WARNING, "Invalid priority at line %d of " "%s\n", lineno, fn); o->priority = 1; } } else if (!strcasecmp(buf, "retrytime")) { if ((sscanf(c, "%30d", &o->retrytime) != 1) || (o->retrytime < 1)) { ast_log(LOG_WARNING, "Invalid retrytime at line %d of " "%s\n", lineno, fn); o->retrytime = 300; } } else if (!strcasecmp(buf, "waittime")) { if ((sscanf(c, "%30d", &o->waittime) != 1) || (o->waittime < 1)) { ast_log(LOG_WARNING, "Invalid waittime at line %d of " "%s\n", lineno, fn); o->waittime = 45; } } else if (!strcasecmp(buf, "retry")) { o->retries++; } else if (!strcasecmp(buf, "startretry")) { if (sscanf(c, "%30ld", &o->callingpid) != 1) { ast_log(LOG_WARNING, "Unable to retrieve calling " "PID!\n"); o->callingpid = 0; } } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) { o->callingpid = 0; o->retries++; } else if (!strcasecmp(buf, "delayedretry")) { } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) { c2 = c; strsep(&c2, "="); if (c2) { var = ast_variable_new(c, c2, fn); if (var) { /* * Always insert at the end, because some people * want to treat the spool file as a script */ if (last) { last->next = var; } else { o->vars = var; } last = var; } } else ast_log(LOG_WARNING, "Malformed \"%s\" argument. " "Should be \"%s: variable=value\"\n", buf, buf); } else if (!strcasecmp(buf, "account")) { ast_string_field_set(o, account, c); } else if (!strcasecmp(buf, "alwaysdelete")) { ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE); } else if (!strcasecmp(buf, "archive")) { ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE); } else { ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of " "%s\n", buf, lineno, fn); } } else ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn); } } ast_string_field_set(o, fn, fn); if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) { ast_log(LOG_WARNING, "At least one of app or extension must be " "specified, along with tech and dest in file %s\n", fn); return -1; } return 0; }
The first thing it seems to do (after storing some Asterisk variables for later usage) is begin parsing the call file, 256 bytes at a time. One thing we immediately learn from this, is that any given line in your call file cannot contain more than 256 bytes (characters). If it does, then it will not be parsed correctly.
The next thing that
apply_outgoing does is remove any comments and trailing
whitespace. This is pretty standard stuff. I am a bit surprised, however, that
the Asterisk developers didn't use the utility function
ast_trim_blanks (in
include/asterisk/strings.h), as re-writing this sort of stuff greatly
increases the size of the codebase, making it harder to maintain.
Next, Asterisk attempts to detect the command and arguments for each call file
directive. Since all call file directives are of the form
command: arguments,
Asterisk splits the line at ':', then tries to detect which command is being
called. This is exactly what we would expect to happen.
In the process of splitting the lines into command and argument pairs, Asterisk
parses out the arguments as well, and populates the outgoing struct as
expected. Along the way, if Asterisk finds any problems with the syntax, it'll
log the errors to the Asterisk log (usually
/var/log/asterisk/full).
Lastly, after parsing all options, Asterisk verifies to make sure that the minimum directives have been specified.
If everything worked OK, and the call file can be spooled, then
apply_outgoing will return 0, otherwise, it'll return -1.
What Did We Learn?
We've analyzed the core components that make call files work, and we've learned a few things.
We have a complete understanding of which call file directives exist (as shown in the code above). This is a big benefit, as the documentation on voip-info.org, and various other Asterisk documentation websites seems to be incomplete. The exact call files directives allowed are:
- channel
- callerid
- application
- data
- maxretries
- codecs
- context
- extension
- priority
- retrytime
- waittime
- retry
- startretry
- endretry
- delayedretry
- setvar
- account
- alwaysdelete
- archive
Note, some of these directives should not be directly entered into your call files (as Asterisk will automatically add them as necessary), but of course, if you're reading this you're probably the type of person who likes messing with that sort of stuff, so have at it. :>
We've learned how to put any amount of directives we want onto a single line. Obviously this is totally useless, but it is nice to know that we CAN if we want to!
We're able to do this because the spooling daemon reads 256 bytes at a time for parsing. So we could write a call file that looks something like:
Channel: blah <pad to 256 bytes>NextDirective: blah<pad to 256 bytes> ...
Conclusion
I'm hoping to do a few more articles that demistify other parts of Asterisk in depth (with code and examples). This is my first, and I know it doesn't touch on the complex topics like threading and synchronous / asynchronous channels, but I assure you I'll write some future articles which cover those parts in extreme depth.
If you want to keep up with my random other thoughts follow me on twitter. | http://neverfear.org/blog/view/130/The_Asterisk_Spooling_Daemon | CC-MAIN-2017-22 | refinedweb | 1,816 | 60.85 |
6 Tools for Debugging React Native
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
Debugging is an essential part of software development. It’s through debugging that we know what’s wrong and what’s right, what works and what doesn’t. Debugging provides the opportunity to assess our code and fix problems before they’re pushed to production.
In the React Native world, debugging may be done in different ways and with different tools, since React Native is composed of different environments (iOS and Android), which means there’s an assortment of problems and a variety of tools needed for debugging.
Thanks to the large number of contributors to the React Native ecosystem, many debugging tools are available. In this brief guide, we’ll explore the most commonly used of them, starting with the Developer Menu.
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. — Brian W. Kernighan
The Developer Menu
The in-app developer menu is your first gate for debugging React Native, it has many options which we can use to do different things. Let’s break down each option.
- Reload: reloads the app
- Debug JS Remotely: opens a channel to a JavaScript debugger
- Enable Live Reload: makes the app reload automatically on clicking Save
- Enable Hot Reloading: watches for changes accrued in a changed file
- Toggle Inspector: toggles an inspector interface, which allows us to inspect any UI element on the screen and its properties, and presents and interface that has other tabs like networking, which shows us the HTTP calls, and a tab for performance.
YellowBoxes and RedBoxes
RedBoxes are used to display errors. Every time an app throws an error, it will display a RedBox and the description of the error. You can display it any time by writing
console.error. But it doesn’t work in the production, meaning that if an error happens in that environment, the app will crash and stop running.
The RedBox is your friend. One of the helpful things about it is that it displays the error and gives you the suggestions on how to fix it, which you won’t find in the console. For example, I’ll frequently write a style property that’s not supported by React Native, or a property that’s used for a specific element—such as setting
backroundImage for the
View element. The
Redbox will throw an error, but it will also show the list of supported style properties that you can apply to the
View.
YellowBoxes are used to display warnings. You can disable them by adding line of code shown below inside
index.js in the root directory of your app. But that’s not recommended, as YellowBoxes are very useful. They warn you about things like performance issues and deprecated code. You can use the YellowBox element from
react-native to display a specific warning.
import {YellowBox} from 'react-native'; YellowBox.ignoreWarnings(['Warning: ...']);
Most YellowBox warnings are related to some bad practice in your code. For example, you might get a warning that you have an
eventListener that you aren’t removing when the component unmounts, or that you have deprecated features and dependencies like this:
warning: ViewPagerAndroid has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-community/viewpager' instead of 'react-native'. See
Fixing these issues will prevent many bugs and will improve the quality of your code.
You can always learn more about debugging React Native in the official docs.
Chrome’s DevTools
Chrome is possibly the first tool you’d think of for debugging React Native. It’s common to use Chrome’s DevTools to debug web apps, but we can also use them to debug React Native since it’s powered by JavaScript.
To use Chrome’s DevTools with React Native, first make sure you’re connected to the same Wi-Fi, then press command + R if you’re using macOS, or Ctrl + M on Windows/Linux. When the developer menu appears, choose
Debug Js Remotely. This will open the default JS debugger.
Then check this address in Chrome. You should see this page:
You may have to do some troubleshooting on Android.
To solve this problem, make sure your your machine and the device are connected on the same Wi-Fi, and then add
android:usesCleartextTraffic="true" to
android/app/src/main/AndroidManifest.xml. If this doesn’t work for you, check out these links for other solutions:
After you have successfully connected to Chrome, you can simply toggle the Chrome inspector.
Then take a look at the logs of your React Native app. Also have a look through the other features offered by Chrome’s DevTools, and use them with React Native as you do with any Web app.
One of the limitations of using Chrome’s DevTools with React Native is that you can’t debug the styles and edit the style properties as you usually do when you debug web apps. It’s also limited in comparison with React’s devtools when inspecting React’s component hierarchy.
React Developer Tools
To debug React Native using React’s Developer Tools, you need to use the desktop app. You can install it globally or locally in your project by just running this following command:
yarn add react-devtools
Or npm:
npm install react-devtools --save
Then start the app by running
yarn react-devtools, which will launch the app.
React’s Developer Tools may be the best tool for debugging React Native for these two reasons:
- It allows for debugging React components.
- It makes it possible to debug styles in React Native (my favorite feature of these developer tools!). The new version comes with this feature that also works with inspector in the developer menu. Previously, it was a problem to write styles and have to wait for the app to reload to see the changes. Now we can debug and implement style properties and see the effect of the change instantly without reloading the app.
You can learn more about using React’s Developer Tools app here.
React Native Debugger
If you’re using Redux in your React Native app, React Native Debugger is probably the right debugger for you. It’s a standalone desktop app that works on macOS, Windows, and Linux. It integrates both Redux’s DevTools and React’s Developer Tools in one app so you don’t have to work with two separate apps for debugging.
React Native Debugger is my favorite debugger and the one I usually use in my work with React Native. It has an interface for Redux’s DevTools where you can see the Redux logs and the actions, and an interface for React’s Developer Tools where you can inspect and debug React elements. You can find the installation instructions here. You can connect with this debugger in the same way you open Chrome’s inspector.
Using React Native Debugger over Chrome’s DevTools has some advantages. For example, you can toggle the inspector from the Dev Menu to inspect React Native elements and edit styles, which isn’t available in Chrome’s DevTools.
React Native CLI
You can use the React Native CLI to do some debugging as well. You can use it for showing the logs of the app. Hitting
react-native log-android will show you the logs of db logcat on Android, and to view the logs in iOS you can run
react-native log-ios, and with
console.log you can dispatch logs to the terminal:
console.log("some error🛑")
You should then see the logs in the terminal.
You can use the React Native CLI to get some relevant info about the libraries and the dependencies you’re using in your app, by running
react-native info on the terminal. It shows us some useful info about the tools you’re using. For instance, here’s an example of an output when you run
react-native info:
You can use this info to fix some bugs caused by version mismatches of a tool you’re using in your project, so it’s always good to check the environment info using this command.
Summary
There are lots of tools for debugging React Native in addition to the ones we’ve looked at here. It really depends on the specific needs of your project. I mostly use React Native Debugger Desktop because I often work with Redux, and it combines an array of tools in one app which is great and a time saving.
Please hit me on Twitter if you’d like to talk more about tools to debug React Native and about React Native in general. I’d love to hear from you!
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS! | https://www.sitepoint.com/tools-for-debugging-react-native/ | CC-MAIN-2021-04 | refinedweb | 1,508 | 61.46 |
Contents
Test-driven development (TDD) is a powerful (and increasingly popular) development strategy. In TDD, you write tests before you write your code. This helps you to solidify in your mind what the code should be doing and ensures it will be structured as you want. Test driven development also encourages good architecture decisions such as modularization because you can’t test what you can’t access!
Even if you don’t write tests first, having automated tests can be a lifesaver when the inevitable change request comes and you have to refactor your program to fit the new requirements.
When you install TurboGears, you also get Nose for free [1]. Nose (written by Jason Pellerin) is a powerful and convenient extension to the standard library module unittest and comes with its own discovery-based test runner.
When using Nose, all you have to do to run your test suite is open your console and execute following command in your project directory:
nosetests
The nosetests command will search you project for test cases (any class or method that has a test/Test/TEST prefix) in your project directory, execute all those test cases and give you a report on the outcome.
By running your tests before you commit to source control repository (you are using source control, right?), you can catch unintended consequences of your edit before they become an issue in production. Early detection also makes tracking down the bug considerably simpler.
When a tests produces an error, nose will try to reload you test module, thereby causing errors because the model will get loaded twice. If you have trouble finding out whcih test case is the culprit, run nose with
nosetests -x
and it will stop after the first test which fails or produces an error. nosetests has many other useful command line options. Run
nosetests --help
to view the help message and find out more about them.
You can put test-specific configuration into the test.cfg file in your project directory. This allows you, for example, to have a special logging configuration when running tests or, the most common case, to define a different dburi for test, so your test will work with a database specially set up for tests or an in-memory database that will get wiped before/after each test.
For more information see the Configuration page and the section on testing your model below.
A simple test demonstration:
# This method is a demo to be tested def getsum(a, b): return a + b # Test case are start with :doc:`/test` def test_getsum(): assert 3 == getsum(1, 2) assert 4 != getsum(1 ,2)
As mentioned, Nose looks for modules that start with test. In the above example, it will find the test_getsum() function and the report from nosetests will show that one (1) test passed. By convention, test modules go into separate packages called “tests” located beneath the package they are testing, though Nose does not require this (as the above example demonstrates).
Nose tries to be as unobtrusive as possible. For example you can write your tests using the standard Python assert statement, which raises an error if an expression returns False, or equivalent. The assert statement also takes an optional second argument, which is a human-readable description of the test case, e.g.:
assert 4 is getsum(1, 2), "assert that 1 + 2 == 4"
This is a failing test which, when run with nosetests -d, will output:
File "/path/to/file.py", line XX, in test_getsum: assert 4 is getsum(1, 2), "assert that 1 + 2 == 4" AssertionError: assert 4 is getsum(1, 2) >> assert 4 is getsum(1, 2), "assert that 1 + 2 == 4"
The last line is the nosetests assert introspection, which will replace the variables on the line (there aren’t any here) with the values.
The only portion of assertion testing that gets a bit ugly occurs when testing for exceptions:
try: test_int = int('five') assert False, "Should have raised ValueError" except ValueError, e: assert "invalid literal" in str(e)
Testing web applications isn’t as easy as testing other environments. There’s the request dispatching and handling as well as the database setup and teardown. The turbogears.testutil module was written to facilitate testing for the TurboGears framework itself, but it’s in the framework because it’s useful for testing your applications as well.
Here’s the sample controllers.py file that will be used for our examples:
from turbogears import expose class Root: @expose(html="projectname.templates.welcome") def index(self, value="0"): value = int(value) return dict(newvalue=value*2)
Here is the test module for the above controller:
from turbogears import testutil from projectname.controllers import Root import cherrypy ##The template contains # # The new value is ${newvalue}. # to test template def test_withtemplate(): "Tests the output passed through a template" cherrypy.root = Root() testutil.create_request("/?value=27") assert "The new value is 54." in cherrypy.response.body[0]
Here we’re not using any of the Nose-provided setup and teardown functionality, we’re doing everything in our test function. The docstring provides nicer output for failing tests in the testrunner.
In order to test out CherryPy, we need an active root object, this is created by setting cherrypy.root:
cherrypy.root = Root()
With the root created, the testutil.create_request creates a fake request that passes through all the CherryPy url traversal, the decorators for our function, template processing, etc. The request is processed and results put in cherrypy.response, but the response isn’t sent anywhere.
With the request processed, we test for correctness by using the in operator to find our modified substring in the body (cherrypy.response.body[0]).
Continuing with our previous example, we’ll write a test that calls the index() method directly, bypassing CherryPy and our templates:
from turbogears import testutil from projectname.controllers import Root import cherrypy # to test controller def test_directcall(): "Tests the output of the method without the template" root = Root() d = testutil.call(root.index, "5") assert d["newvalue"] == 10
Despite not going through CherryPy, we do still need an instance of our project Root. The testutil.call() method is then used to call our function, which returns an object. The first argument to testutil.call() is a reference to the method, the remainder are *args or **kwargs. The return value for the controller is returned by call and can be tested as shown.
If your model makes use of the values in cherrypy.request or you’d like to check cherrypy.response in addition to the dictionary output, you can use the testutil.call_with_request(). call_with_request() takes both a method reference and a request as parameters and returns a tuple of the method output and the response object. If you don’t have a request object handy, use testutil.DummyRequest to create a fake one.
Testing your model is a thorny problem for unit testing, since the output is usually very dependent on the state of your database. This means that you’ll probably need a separate database for testing. To make this simpler, TurboGears provides the testutil.DBTest class.
If you inherit from this class, and you are using SQLObject, TG will provide setUp() and tearDown() methods that create and drop all the tables in your model for each method. In the example below, test_model_reset() is working on a completely empty database despite coming after test_name(), thanks to the setUp() and tearDown() methods inherited from testutil.DBTest.
from turbogears import testutil ## from turbogears import database ## database.set_db_uri("sqlite:///:memory:") #this is the default from projectname import model class TestMyURL(testutil.DBTest): model = model def test_name(self): entry = model.MyUrl(name="TurboGears", link="", description="cool python web framework") assert entry.name=='TurboGears' def test_model_reset(self): entry = list(model.MyUrl.select()) assert len(entry) is 0
If you want to define your own setUp() and/or tearDown() make sure that you call those methods from the parent class or you’ll get OperationalError: no such table: ... exceptions.
from turbogears import testutil from projectname import model class TestMyURL(testutil.DBTest): model = model def setUp(self): """Pre-test setup. Use the parent class setUp() method to create database tables, then ... """ super(TestMyURL, self).setUp() # Additional set-up code def tearDown(self): """Post-test tear-down. Use parent class tearDown() method to reset database before next test. """ super(TestMyURL, self).tearDown() # Additional tear-down code
For another alternative, you can use testutil’s BrowsingSession class to test your application using a browser metaphor. Simply create an instance and use the goto method to navigate your site. The response attribute will contain the body of your page. If the page sets a cookie, it will be available under the cookie attribute:
bs1 = testutil.BrowsingSession() bs2 = testutil.BrowsingSession() bs1.goto('/login?user_name=emma&password=secret&login=Login') bs2.goto('/login?user_name=paul&password=passwd&login=Login') bs1.goto('/') bs2.goto('/') assert 'emma' in bs1.response assert 'paul' in bs2.response
If your application sets an encoding in the ‘Content-Type’ header, the BrowsingSession instance will have a unicode_response attribute assigned as well.
Since testutil was developed to test the TurboGears framework, there are a number of other methods that are generally less useful outside the framework but are listed here for completeness:
When testing your TurboGears application you should be aware of some issues which can bite you. The main problem is that testutil.call(..., ...) won’t trigger any CherryPy filters. These filters modify the originally requested object or the request parameters. The main difference between filters and function decorators is that filters will be executed on all exposed methods while decorators are specific for the decorated functionality.
Some important functionality in TurboGears is implemented as a CherryPy filter, especially visit tracking and identity authentication. Therefore you can not test your login page easily. In order to test other methods which rely on identity for user authorization, there is a special method set_identity_user in turbogears.testutil which can be used to set a user before using testutil.call(...).
Another catch may be the NestedVariablesFilter, which is implemented as a filter too. You can either pass the nested dictionary to you method under test or use NestedVariables.to_python(...) manually before actually calling the real method.
from formencode.variabledecode import NestedVariables from turbogears import testutil # first method args = {'phone': [{'nr': '12345', 'area_code': '042'}, {'nr': '6789', 'area_code': '021'}] 'name': 'Foo'} result = testutil.call(self.root.save, **args) # second method args = {'phone-1.nr': '12345', 'phone-1.area_code': '042', 'phone-2.nr': '6789', 'phone-2.area_code': '021', 'name': 'Foo'} args = NestedVariables.to_python(args) result = testutil.call(self.root.save, **args)
Note you can avoid these problems by using testutil.create_request(...) because this will create a faked request which goes through all stages of CherryPy’s request processing as mentioned above. The disadvantage is that you will get only the generated output from your template engine so you can’t easily extract all variables passed to the template. | http://www.turbogears.org/1.0/docs/Testing.html | CC-MAIN-2015-11 | refinedweb | 1,825 | 55.44 |
SPECIALIZE one of two identical functions does not fire well
Hi,
I am playing with
SPECIALIZE pragma:
module Todo where {-# SPECIALIZE plusTwoRec :: [Int] -> [Int] #-} plusTwoRec :: Num a => [a] -> [a] plusTwoRec [] = [] plusTwoRec (x:xs) = x+2:plusTwoRec xs plusTwoRec' :: Num a => [a] -> [a] plusTwoRec' [] = [] plusTwoRec' (x:xs) = x+2:plusTwoRec' xs
And wanted to benchmark it with (in
Main.hs):
import Todo import Criterion.Main aListOfInt :: [Int] aListOfInt = [1..10000] main :: IO () main = defaultMain [ bench "plusTwoRec" $ nf plusTwoRec aListOfInt , bench "plusTwoRec'" $ nf plusTwoRec' aListOfInt ]
Sadly, the rule of specialization of
plusTwoRec does not fire in Main.hs
(I compiled with:
ghc Main.hs -O -dynamic -ddump-rule-firings (the
-dynamic part is due to my ArchLinux installaltion)).
The result is:
[1 of 2] Compiling Todo ( Todo.hs, Todo.o ) Rule fired: Class op + (BUILTIN) Rule fired: Class op fromInteger (BUILTIN) Rule fired: integerToInt (BUILTIN) Rule fired: SPEC plusTwoRec (Todo) [2 of 2] Compiling Main ( Main.hs, Main.o ) Rule fired: Class op enumFromTo (BUILTIN) Rule fired: unpack (GHC.Base) Rule fired: unpack (GHC.Base) Rule fired: eftIntList (GHC.Enum) Rule fired: unpack-list (GHC.Base) Rule fired: unpack-list (GHC.Base) Linking Main ...
I have inspected a bit the code produced after the simplifications passes (with
-ddump-simpl) and here is the suspicious part:
plusTwoRec :: forall a. Num a => [a] -> [a] [GblId, Arity=2, Caf=NoCafRefs, Str=<L,U(C(C1(U)),A,A,A,A,A,C(U))><S,1*U>, Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=ALWAYS_IF(arity=0,unsat_ok=True,boring_ok=True)}] plusTwoRec = plusTwoRec'
I believe that
plusTwoRec is inlined before the specialization has a chance to fire, but I am not sure at all !
Separating the two functions definitions in two different files works.
So I don't know if this is a GHC bug, myself that does not read the right part of the GHC manual, if it is only a lack of documentation, or anything else. | https://gitlab.haskell.org/ghc/ghc/-/issues/15445 | CC-MAIN-2022-21 | refinedweb | 330 | 56.15 |
Type: Posts; User: E-man96
I am creating a program for my dad, which will have a catalogue of patients, and will check them for dates and such, but that's off topic. Here's my dilemma, whenever I cout a series of messages, the...
This was solved in the wxWidgets forums see.
Thanks in advance for reading this. I am using Ubuntu Linux 10.4 LTS, wxWidgets 2.8, and Gtk 2.* (I'm not sure which version, theire are too many packages)
Whenever I run my program no icons are...
Would someone please review and judge my program? I need someone to tell me the good and bad practices that I should continue or end, and give me some feedback and tips for my future programs....
BTW if your just trying to make an array you don't have to use pointers, new, and delete, You can just use the vector class it is much simpler. And an answer to your question would be here....
wow it was a typo! now can someone tell me how to "close" this case?
Actually I purposely made wsbd an array of chars rather than a string because I would have to search for words according to a grid with values rather than an array of strings or one string.
I am trying to create a word search program that can load text files and look for words in them. But I can't get the program to recognize the file. I am running on windows XP sp3 with WxDev-C++....
I know that define is a search and replace thing but I dont get what define is doing when the code is like this
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <string>
What is the difference between win32api, win32, vc++, mfc, and others? (If you know the other ones please post a comment)
And... what do you guys think about open-source ones like wxwidgets, Qt, and...
The code I have written is here:
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <string>
I need help with this code:
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <string>
Use this tutorial
It's very good at covering the details
[code\]
int a=5;
if (a==7||6||5||4||3||2)
instead of doing
int a=5;
if (a==7||a==6||a==5||a==4||a==3||a==2)
[code/]
is this possible and if not how can you make it possible?
I'm trying to make a class that makes a date and lets the user edit the date.
date.h
#ifndef date
#define date
#include <iostream>
#include <string>
you need functions and while loops!
goto is a bad habit because it ends up with messy code, which is probably messing up your code.
Like this
class a
{
namespace b
{
}
you need to turn stirling1 and stirling2 into float numbers, OR do a typecast
BTW: the curly brackets for the for loop is missing.
I already know what the difference is but does anyone know a good way to memorize the difference between the two?
string [2];
does this create two strings or a string of 2 characters?
If the latter how do you make it work as an array of strings?
I have three simple questions.
Is the memory used by a dynamic array lost forever if you never deallocate it?
what about after the program ends?
what about after the computer is restarted?
Is there a way to make the elements of an array equal to the elements of another array?
I know that you can do it in a loop but I'm looking for something like a shortcut.
maybe you should comment and indent your code. It would be easier to find the bug.
I for some reason can have a variable sized array. For example main.cpp (it's an attachment) can compile & run perfectly! Can someone tell me why it works and how it doesn't say it works on all the... | http://forums.codeguru.com/search.php?s=b0bf6d8abe9a0bbc024b91127a848ac3&searchid=5599537 | CC-MAIN-2014-49 | refinedweb | 667 | 81.22 |
In this article, we will learn how to make a React Native application with Expo and create-react-native-app and learn about some of the differences between React and React Native code and file structure.
Thinking about making a phone app? Know React and would rather not spend valuable time learning another language? Well, excellent news! React Native is here to save us that time. It also gives us easy access to the phone’s API so we can tap into a phone’s contacts, notifications, camera, and even the gyroscope!
Facebook Guide
If you are looking for the quickest way to “Get Started” with React Native, then look no further than Facebook’s own Getting Started Guide.
First, we need to install
create-react-native-app globally:
$ npm install -g create-react-native-app
Then we create our first project:
$ create-react-native-app AlligatorProject $ cd AlligatorProject $ npm start
Once we run
npm start, we can look at the output from the command line for more details on how we can run the app in a simulator or install the Expo app on our phone and run it there.
Then the code starting from the generated app itself tells us what to do next:
App.js', }, });
* Note that the above code snippet is taken from the Create React Native App project, licensed under BSD 3-Clause “New” or “Revised” License and is copyright 2017 by Create React Native App Contributors. You can find a copy of the license here.
Making an App
Okay, we have “hello world”ed, but where do we go from here? First, let’s change our app to have only one
Text field:
App.js (partial)
<Text>Welcome to our app!</Text>
Notice that this change will immediately update our simulator or phone. We may have seen hot reloading for a React web project, but how do we get it for a native app? If we run the
npm start command inside a
create-react-native-app project, we’ll see something like:
Your app is now running at URL: exp://192.168.1.171:19000
Notice that Expo is just running a web server on port 19000, much like a web app might run on. This is one way that Expo makes the learning curve from React.js into React Native much smoother. But what exactly is Expo?
Introducing Expo
According to the Expo team:
Expo is a free and open source toolchain built around React Native to help you build native iOS and Android projects using JavaScript and React.
So basically, we can get the best of both worlds.
- While we’re testing, we can take advantage of an environment that is almost identical to a React.js development environment.
- Through the Expo SDK, we can tap into the phone the same way we would with Android or iOS code.
As we continue to develop, we may run into Expo’s limitations. Namely, it currently does not support Bluetooth integration or any third party plugins that are built with native iOS or Android code. All third-party tools in an Expo project must have been built in the Expo environment.
But don’t fret! If we reach one of these limitations, Expo comes with the following command:
$ npm run eject
Ejecting will convert our project into a “pure” React Native project, meaning every time the project is built from now on, it is converted into iOS (Objective C) and/or Android (Java) code. This allows us to get around the limitations of Expo mentioned above, but can make testing and deployment considerably harder. That is, no more auto-generated QR codes or links.
Note that ejecting is a permanent action, so it is a good idea for us to do two things:
- Continue to live in the blissfully simple world of Expo until we hit a wall. We can eject our app whenever we want.
- Make sure a project is saved in version control somewhere before we eject. That way we can go back whenever we want, too.
Digging Deeper
So far, we have covered the main differences between the React.js and React Native development environments. Next, we will cover some of the main differences in the
code.
Let’s dive deeper into the React Native code created for us with
create-react-native-app and how it differs from React.js code.
What create-react-native-app Gave Us
If we look in the directory created by
create-react-native-app, we see the following files:
.babelrcdefines how our JSX will be converted to JS.
.gitignoreignores all files in version control that should be unique to each development machine.
.watchmanconfigdefines how files should be watched for changes.
App.jsis the center of our project, similar to the root component in React.js.
app.jsonconfigures parts of our app that don’t belong in code.
App.test.jsis the testing center of our project, and comes with a free test so we can get TDD started right away.
package.jsonand
package-lock.jsondefine a basic set of packages and scripts to get us up and running.
README.mdprovides a wealth of detail on troubleshooting, deploying, updating, and more.
Our App
After our update, our code should look like this:
App.js
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends React.Component { render() { return ( <View style={styles.container}>
Welcome to our app!</View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
React Native Code Differences
Looking at our app, we see a lot of code that is similar to React.js. From top to bottom, we see:
- ES6
imports
- object destructuring
- Exported class that extends the React
Component
render()function that returns JSX
constvariable assignment
So far, so good. But there are also some new things:
Textand
Vieware not HTML tags. This is because a React Native app is not a webpage. All tags in React Native must be a React Native component. So no more
<div>s or
<form>s.
- No more
classNameor CSS imports. Again, this is because a React Native app is not a webpage. This requires some rethinking if we are used to React.js apps, where we can take advantage of classes, ids, media queries, and more from CSS, Less, or Sass. The good news, though, is that the React Native
StyleSheetobject allows us to use the full weight of ES6: things like variables, arrow functions, for loops, and ternaries.
In a nutshell, these two major differences illustrate the crux of React.js vs React Native code confusion.
For example, if we are used to this from React.js:
<img src="myPic.gif" />
In React Native, that would look like this:
<Image source="myPic.gif" />
Also we have to
import that
Image component from React Native. Not incredibly different, but when we’re switching between React.js and React Native, those subtle differences can lead to some frustrating errors.
There is a third difference that will appear once our apps get more complex: many of the npm packages we import for React.js will not work with React Native. If we are using a pure Javascript
npm package we can use it both in React.js and React Native, but once we involve HTML or CSS (e.g. reactstrap or any form validation libraries) we will need to look for a React-Native-compatible alternative.
Conclusion
Expo and
create-react-native-app allow us to utilize a React Native development environment that is very similar to React.js, but also allow us to take advantage of native mobile device features.
In a nutshell, the three main differences between React.js and React Native are:
- No more HTML
- No more CSS
- Any React.js npm packages that rely on HTML or CSS will not work with React Native
With React Native, we have to sacrifice some of our comfortable tools from pure web development, but there are some powerful tools we get in exchange which make the move to React Native well worth it.
Stay tuned for more Alligator.io articles on putting our app in the App Store, adding native camera integration, connecting to a phone’s contacts, and push notifications. | https://alligator.io/react/react-native-getting-started/ | CC-MAIN-2020-34 | refinedweb | 1,377 | 64.81 |
August 6, 2002
By Honorable Jon Kyl Afghanistan and our decisions
on the ABM Treaty, Kyoto, the International Criminal Court, the
Biological Weapons Protocol, and so on. There is no agreement over
what to do about Iraq or other state sponsors of terror or the
crisis in the Middle East. After September 11, European critics
have switched from complaining of U.S. "isolationism," to worries
about "preemption." Add to this the decade-old doubts about the
utility of NATO in the post-Cold War world, and one could conclude
that there is today a real question as to whether Europe and the
United States are parting ways.
Indeed, there are some serious people making serious charges
about this state of affairs. Charles Krauthammer says NATO is dead
as a military alliance due to the huge disparity in power between
the U.S. and Europe. Jeffrey Gedmin, known as a committed
Atlanticist, recently penned an op-ed entitled, "The Alliance is
Doomed"--doomed mainly because of what he calls the European
"obsession" with chaining down the Americans.
Former Secretary of Defense and long-time NATO stalwart James
Schlesinger complained vociferously about European attitudes in a
recent Financial Times piece, questioning whether we have a common
agenda anymore. And, in a very thought-provoking article called
"Power and Weakness" in the journal Policy Review, Robert Kagan
concluded that, because of our different military capabilities and
philosophies toward power, the United States and Europe no longer
share a common view of the world; and that this is not a temporary
phenomenon.
These are serious people making serious charges. They reflect
some deep divisions in European and American
perspectives--divisions that I believe must be addressed in a
forthright manner.
On a recent trip to Germany, it was clear that Europeans have
noticed that some things about U.S. foreign policy have changed. I
told them that this was primarily due to the election of George W.
Bush and the seminal events of September 11. But I still do not
think our European friends fully appreciate the extent to which
September 11 changed everything for Americans.
September 11 awakened us to a threat we had not taken very
seriously. But we now understand the threat and we are totally
committed to confronting it. We believe it is very, very serious
and it is not transitory. Nor is the threat only against Americans.
As Prime Minister Tony Blair has said, this is now a "war for
civilization against the forces of violence, barbarism and chaos."
And the transatlantic alliance is, if nothing else, a group of
nations with a shared understanding of civilization.
Yet many in Europe seem to believe that perhaps America is
making too much of this threat, or at least that it is not much of
a threat to Europeans, or, that even if it is, we have to be very
careful about terrorists or their state sponsors who either have
significant military capabilities or who represent economic
opportunities. Obviously, no national leader could possibly ignore
the seriousness of this threat.
Even now there is a comprehensive effort in the Congress to try
to determine whether we could have prevented 3,000 deaths last
September. A preventable future catastrophe will not be tolerated
by the American people, and, I submit, would not be tolerated by
Europeans now that we all have been warned.
To put it another way, we Americans do not want to spend the
rest of our history like Israelis in Jerusalem, wondering when and
where the next attack will occur. I don't think the people of
Europe do, either.
The al-Qaeda terrorists who attacked America were part of a very
large cell operating in Hamburg. In fact, because of the relative
ease of travel, lack of surveillance, and ability to live easily in
Europe, there are large numbers of terrorists in Europe, as in the
U.S. We must continue to work with European law enforcement to find
them and bring them to justice. Among other things, that means
finding ways of resolving our differences on the death penalty. But
I say to Europeans, that as strongly as they may feel about capital
punishment, it would be unforgivable if our disagreement on that
issue prevented us from properly dealing with international
terrorists. It simply can't be that it's safer to be a terrorist in
Europe than in Afghanistan.
With regard to Afghanistan, at least 13 NATO countries have
contributed forces to the campaign. That the U.S. had to move
quickly in the initial military campaign--without full NATO
participation--is not, therefore, an example of unilateralism. And
NATO allies are all acutely aware of the growing capabilities gap
within the alliance, so no one can be surprised that U.S. actions
will, of necessity, reflect that unfortunate reality. The United
States would welcome a change in those circumstances, and the
remedy is obvious.
President Bush recently made a commonsense observation which,
nevertheless, has stirred another controversy. Terrorism against
open societies like those we have in the U.S. and Europe is almost
impossible to prevent all of the time, so offensive action against
the terrorists is critical to stopping them. Therefore, the
President announced that, when possible, it would be our policy to
hit them before they can hit us. Preemption.
Indeed, we have been taking the war to the enemy, disrupting
their cells and plans quite successfully since September 11; no one
seems much bothered by the notion that we shouldn't wait to be hit
by another terrorist attack before going after the terrorists.
Applied to a tyrant like Saddam Hussein, however, preemption is
seen by many in Europe as dangerous and contrary to accepted
principles of behavior among civilized states.
Yet, it is clear at this point that the multilateral,
U.N.-mandated approach to dealing with Saddam has failed. The U.N.
cease-fire agreement at the end of the Gulf War required him to get
rid of his weapons of mass destruction. But, of course, after
stringing out the inspection process for seven years--thwarting and
evading disarmament at every step along the way--Saddam Hussein
finally kicked out the inspectors altogether. For the past four
years, he has been free to pursue his development of chemical,
biological, and nuclear weapons without fear of interference from
the U.N. Security Council, which has continued to rely on a failed
sanctions regime to change his behavior.
And this, as an insightful piece in the June 29 issue of the
Economist concluded, illustrates clearly the limits of a purely
multilateral approach. The article states, and I agree: "Beyond
economic sanctions, which have already failed or been scuppered by
U.N. members, there is no enforcement mechanism except for American
leadership."
Saddam Hussein's failure to abide by the U.N. cease-fire
resolution, as well as the U.N. resolution requiring him to end the
repression of his people, is not surprising coming from a man who
once said, "Don't tell me about the law. The law is anything I
write on a scrap of paper." It is an utter waste of time, and
dangerous at that, for us to negotiate with Saddam Hussein over
renewed inspections for weapons of mass destruction. I am not
surprised in the least at the recent headlines that the U.N. has
been unable to reach any sort of deal on the return of the
inspectors. And, even if the U.N. were to acquiesce to Saddam's
demands that the sanctions be lifted before their return (which it
will not), it is naive in the extreme to think he would ever
comply.
Saddam is in a race to acquire a nuclear weapon--not to mention
to build up chemical and biological weapons--and that is why it
will likely be necessary to enforce the U.N. resolution that Saddam
once agreed to--before he limits our options by completing his work
on a nuclear weapon. Again, to quote the Economist, "Without an
enforcement mechanism as a last resort, treaties and conventions
designed to control the spread of the ghastliest weapons will
ultimately collapse. There has to be a military sanction . . . that
sanction cannot wait until a nuclear or biological attack has taken
place. It has to be applied preemptively."
Moreover, an argument can be made that acting forcefully against
Saddam will have a salutary effect on the other Arab states that
have not yet totally committed to be with the United States in the
war on terrorism. Success begets success in this conflict and in
the Arab world, where respect is more important than love.
Nor should we allow ourselves to be paralyzed by the argument
that preemptive moves by democracies will encourage similar moves
by the likes of China against, say, Taiwan. In addition to the fact
that Taiwan poses no threat to anyone, we know that tyrants in the
world are not guided by the examples that democracies set; rather,
they calculate whether the democracies will let them get away with
aggression. Strong Western action influences these
calculations.
In fact, it turns out that circumstances, not some grand
principle, have influenced preventive use of power. Didn't Europe,
with American support, act preemptively to prevent further genocide
in Bosnia and Kosovo? In fact, weren't there complaints that our
action should have been taken sooner?
At the end of the day, the sheer scale of the threat that Saddam
Hussein will acquire a nuclear weapon should move us to action--the
Europeans need to understand this.
But if there are still reasons for doubts about how to handle
Saddam, there can be none about another issue: termination of the
ABM treaty. Here we need not speculate--the verdict is in. Critics
of President Bush's announced intent to withdraw from the treaty
last December were full of dire predictions of a rift with Russia
and a new arms race. It didn't happen. Eleven months of careful
consultations with the Russians and our transatlantic partners
resulted in a new approach to strategic security. This cooperation
produced not a new arms race, but a new nuclear reduction treaty,
as well as the creation of the NATO-Russia Council. So, on this
matter it is possible to judge who was correct in the debate--and
it was not the naysayers.
This is important to keep in mind when U.S. missile defense
plans are criticized. Since the only effect of U.S. missile defense
on Europeans is additional security for those states who choose to
join, Americans have a right to be bewildered by European
opposition to missile defense. This is especially so since some of
the criticism assumes that such a defense is "isolationist" when,
in point of fact, the ability to defend America enhances our
ability to act on the world stage.
The International Criminal Court is another bone of contention.
On this issue, as others, the Bush Administration does not desire
to be different--it merely desires to be right about what's best
for the security of Americans, even if it means suffering the
opprobrium of those who disagree. President Bush subscribes to the
straightforward view that American security is for Americans to
decide. That is not unilateralism--it is a legitimate exercise of
our sovereignty, harmful to no one but potential aggressors.
To explain the American view with regard to the International
Criminal Court, one need look no further than the recent trumped-up
hysteria over prisoners at Guantanamo Bay or the charges by Amnesty
International of U.S. "human rights abuses" in Afghanistan. This
mentality is what makes us wary of the ICC and is why our
representatives to the U.N. are searching for ways to ensure
adequate protection for U.S. peacekeepers. Europe must not
misunderstand our position. The United States has always supported
the rule of law, and, of course, wants to see the worst human
rights abusers brought to justice; but the thought of a court in
Europe seeking to nab Henry Kissinger for policies he crafted
toward Chile thirty years ago ought to at least raise a doubt in
reasonable minds about the specific operations of constructs like
the ICC.
As to Kyoto, we are far more skeptical than the Europeans that
the science behind global warming justifies precipitous action.
Moreover, there is near consensus in the Congress and the
Administration that, in any event, the problem does not justify the
enormous economic costs for developed countries of mandated
controls on emissions called for by the treaty. As the Economist
described on June 29, the inadequacy of the Protocol is
illustrated, in large part, by its failure to include developing
countries--which are likely to contribute significantly to future
emissions--even as part of a future program of emissions reduction.
Many, including myself, believe that wealth creation will, in the
end, provide a much more cost-effective solution to pollution
problems, and that a dollar spent on emissions reduction in places
like India and China will produce much more environmental benefit
than another dollar spent in the U.S. and Europe.
At this point, allow me to step back from specific areas of
disagreement with the Europeans to a more general one--the utility
of power vs. diplomacy. We all agree that both have their place;
but it is probably true that the U.S. will resort to power more
often than continental Europeans are disposed to do. A corollary is
that Americans probably have less confidence in treaties than do
Europeans.
On the specific matter of arms control, I agree with Margaret
Thatcher, who in 1982 declared before the United Nations that,
"Wars are caused not by armaments but by the ambitions of
aggressors." Contrary to conventional wisdom, treaties to limit
arms don't have a very good track record at preserving peace or,
for that matter, even controlling arms. From the Catholic Church's
attempt to ban the crossbow in the 12th century to the SALT
treaties in the 1970s, the traditional concept of arms control has,
with few exceptions, consistently failed to produce meaningful
results.
Likewise, "peace processes" with untrustworthy partners have
similarly failed, often in spectacular fashion. The Oslo Accord
between Israel and the PLO is the best, if unfortunate, recent
example. In addition, consider recent events in Colombia, where the
Marxist FARC guerrillas repaid President Pastrana's generous grant
of a Switzerland-sized safe haven by importing weapons, hosting
European terrorists, and staging increasingly violent attacks
against Colombian society.
President Bush's strategy for dealing with security issues is
based on his firm conviction that today's security environment is
drastically different from that which existed during the Cold War.
Today, our enemies are terrorists and rogue regimes--often working
together. Dealing with them requires democracies to employ
strategies entirely different from nuclear deterrence and
arms-control diplomacy. To depend solely on nuclear deterrence
against, for example, a dictator like Saddam Hussein--a man who has
used chemical weapons against his own people--would be to place our
lives in the hands of a madman. And, as to terrorists, I agree with
President Bush that, "Deterrence...means nothing against shadowy
terrorist networks with no nation or citizens to defend."
Moreover, arms-control diplomacy presupposes that the same
objectives govern all sides of a negotiation. To borrow a phrase
from my good friend, Richard Perle, traditional arms control often
equates guns in the hands of cops with guns in the hands of
robbers. As history has proven time and time again, arms control
works best when it's needed least. The converse is also true, and
is applicable today: Arms control works worst where it is needed
most--against rogue regimes.
In order to deal with today's threats, the Bush strategy
emphasizes three things: moral clarity, strategic clarity, and
capability.
Moral Clarity means basing our actions on the fundamental
understanding that terrorism is never justified, and that nations
cannot be neutral in this fight.
Strategic Clarity means making an unambiguous commitment
to destroy terrorism by attacking it at its core. As former Israeli
Prime Minister Benjamin Netanyahu has said, "You have to go to the
regime, the state, that supports terrorism and makes terrorism
possible. You don't go out looking for the needle, you go and
remove the haystack."
Capability means transforming our military from one
designed to fight tank battles on the plains of Europe to one that
is smaller, lighter, more agile and on the cutting edge of
technology, so as to be able to take the fight to the
enemy--relentlessly, forcefully, successfully.
I have not forgotten the recent cross-Atlantic sparring over
economic matters. Let me say I find Europe's history of steel and
farm subsidies appalling--almost as bad as our own! Easy for me to
say since I voted against both. But, we should be able to agree
with the Europeans that it's getting out of hand on both sides and
has to stop. This means political leadership willing to take
risks.
I have chosen to emphasize our disagreements with Europe today
because there are not enough opportunities to discuss these matters
candidly, and because Americans do have to do a better job of
consulting and explaining our positions.
But I hesitate to conclude without mentioning some of the many
matters upon which we are in agreement with our European partners.
We can be optimistic about the future of the transatlantic
alliance, noting many successes, commonalities, and mutual
contributions. I've already mentioned the great degree of
cooperation on Operation Enduring Freedom, which, by any measure,
must rate as a huge success.
We've worked together in the Balkans to save innocent people
from butchery.
American and German law enforcement, especially the authorities
in Hamburg, have done exemplary work together trying to crack the
terrorist cells in Europe.
And this November, we will significantly expand the Alliance in
Prague. This is something on which, I believe, there is an emerging
consensus. So, despite some differences, there is much agreement
and plenty of cooperation which we should acknowledge and
continue.
Regarding NATO's future, I believe the Alliance should develop
new approaches. One of these, I believe, should be cooperation on
missile defense. I am glad that, last July, NATO funded two
feasibility studies for this vital need. But those studies need to
be followed up with concrete actions by Europe if it wishes to
benefit from U.S. technology.
Proliferation is another area on which NATO should work harder.
With Iran developing the Shahab-4, which will be able to reach the
heart of Europe, NATO clearly has a vested interest in stopping
proliferation to that country. I'd like to see the NATO-Russia
Council develop a common export-control regime--one with teeth,
like the former COCOM. Under no circumstances should we gloss over
Russian support for Iran's missile and nuclear program.
I also favor the proposal put forth by the U.S., Britain, and
Spain for NATO rapid reaction units geared for what used to be
called out-of-area operations. Of course, with global terrorism the
main threat today, there is no such thing as "out of area," so
rapid reaction units will have to be prepared to go anywhere. This
is clearly an endeavor that will require European nations to
address the capabilities gap in some way. It probably does us no
good to lecture Europeans about their defense spending levels
anymore. It would be most welcome if everyone in the alliance went
up to 3 percent of GNP, but perhaps it's more useful if we
encourage European nations to take a hard look at filling gaps in
the current alliance posture through specialization.
As to reaching consensus on terrorism and especially the issue
of preemption, President Bush should, and I believe will, consult
with countries in Europe and elsewhere before acting. It is clear,
however, that combating terrorism will remain at the center of U.S.
foreign policy for the foreseeable future and that preemptive
action will have to be one aspect of that struggle. Obviously, the
U.S. would always prefer to be part of a consensus; but we must not
allow the survival of Americans to be determined by a show of hands
by other countries.
Whether or not we reach consensus with Europe on these matters,
and regardless of its current deficiencies, NATO still must retain
its core mission of collective defense. NATO's infrastructure
cannot be duplicated or resurrected overnight. We must keep it
intact should a new threat develop that requires a ramp up in our
force posture. History shows that unexpected threats can develop
rapidly--we dare not be caught unprepared.
Lastly, NATO plays a growing and indispensable political role.
The transatlantic link is the primary repository of Western
civilization--a civilization based upon decent and profound ideals.
As Czech President Vaclav Havel remarked last year: " . . . the
Alliance is becoming not only an important pillar of international
security, but also a solid, understandable and trustworthy
component of the architecture of a future world order; and, a model
of solidarity in the defense of human liberties."
The democratic purpose is more compelling, not less, after a
century in which the countries of Europe survived the onslaught of
fascism and communism. NATO embodies this purpose, and that is why
10 nations are lined up at the door to get in. The Slovak
Republic's ambassador to the U.S., Martin Butora, recently
commented on his country's desire to join the Alliance, stating:
"Slovakia wants to join NATO because of her past, and perhaps even
more, because of her future."
We can take great pride in that expression of confidence in our
alliance, even as it challenges us to continue to improve.
-- The Honorable Jon Kyl, a Republican, represents Arizona in
the U.S. Senate.
The transatlantic partnership is under serious strain with theUnited States and our European friends having more and moredisagreements.
Honorable Jon K | http://www.heritage.org/research/lecture/the-future-of-transatlantic-relations | CC-MAIN-2015-40 | refinedweb | 3,670 | 51.48 |
Today I’m going to break from the usual Oculus development articles, and walk through how to build your first Google cardboard app.
I’m assuming you’ve never looked into building a Cardboard app before, and you want to quickly cover the main features of a build.
Google Cardboard V2 was introduced in May 2015 and It is much much easier to assemble (that is good news if you do want to actually make one). V2 also fits larger 6″ phones, and most importantly they added support for iOS (Google dropped the magnetic switch in favor of a capacitance button that works on all phones).
Google also upgraded the Cardboard Unity SDK to support V2 (as of version 0.5.0).
So, here is how you can build the exciting cube app below:
Setup
– Obtain a Google Cardboard V2 or (V1) headset for free or buy one from Google, or there is plenty of choice on eBay.
– Download Unity 5 (I’m using Unity 5.2.2 for this)
– Download the Cardboard SDK for Unity (I’m using v0.5.2 – just released today) in UnityPackage format.
Note: For faster project creation drag it into your C:\Program Files/Unity/Editor/Standard Assets folder.
– For Android: Download a JAVA Runtime and an Android SDK (Unity also provides you handy download buttons in the preferences dialog).
Create a project
– Open Unity, and create a new 3D project.
– Import the Cardboard SDK by Assets->Import Package->Custom Package, and select the CardboardSDK.unitypackage.
– Drag the CardboardMain prefab into the scene hierarchy (Assets/cardboard/prefabs/CardboardMain), and it’s position should be x:0,y:0,z:0. Set the y to 1.7 (so our virtual head is not on the ground).
– Select the CardboardMain game object, and in the inspector, under Unity Editor Emulation Settings, choose “Cardboard May 2015″.
– Delete the MainCamera as we won’t need that any more.
– Create a cube to look at: In the scene hierarchy right click then 3D Object -> Cube. Set it’s position to x:0,y:0.5,z:2.
Run in the editor
– Press PLAY, and you will see the well known split-screen stereoscopic distortion screens.
– To rotate your virtual head, hold ALT (Horizontal/Vertical) or CTRL (Tilt) and move your mouse
Run on an Android device
– Open File->Build Settings, select Android and switch platform
– Due to known rendering issues, in Build Settings, checkmark “Development build”.
– Open Player Settings, and under “Resolution and Presentation” set orientation to landscape left.
– Under “Other Settings” change the bundle id to be something unique (which can be anything, eg: com.tales.hellocardboard).
– Make sure your Android phone is plugged in via USB
– Hit Build & Run.
Quit with the back button
You probably noticed the back button (physical and on-screen) don’t do anything. That is because even though CameraMain fires an OnBack event, there is no code hooked up to listen for the event by default.
So, lets do that, and we’ll set the back button to close our app.
Select the CameraMain game object in the scene hierarchy, and in the inspector click Add Component -> New Script (c#) and name it CardboardQuit, add the following code:
CardboardQuit.cs:
using UnityEngine; using System.Collections; public class CardboardQuit : MonoBehaviour { void Awake() { GetComponent<Cardboard>().OnBackButton += HandleOnBackButton; } void HandleOnBackButton () { Application.Quit(); } }
Now, re-run the app and the back button will quit!
Gaze based input
Lets make it every time we look at the cube it will change color.
Firstly we add Gaze based input capability:
– Right click in the scene hierarchy and add UI -> Event System
– Drag the Assets/Cardboard/scripts/GazeInputModule onto the EventSystem game object.
– Disable (uncheckmark) or delete the existing StandaloneInputModule and TouchInputModule.
Next, we add a physics raycaster to our CardboardMain camera so that we can detect hits against 3D objects with colliders (such as our cube).
– Select the game object CardboardMain/Head/Main Camera and in the inspector click Add Component -> Physics Raycaster
Now, finally lets have our cube change color:
– In the Project explorer, right click and Create -> Material, then drag it onto our Cube game object (We need this material so we can modify it’s color at runtime – we can’t modify the default material the is on the Cube).
– Select the game object Cube in the scene hierarchy, then in the inspector Add Component -> Script (C#) and name it Cameleon:
Cameleon.cs:
using UnityEngine; using UnityEngine.EventSystems; public class Cameleon : MonoBehaviour, IPointerEnterHandler { public void OnPointerEnter(PointerEventData eventData) { GetComponent<Renderer>().material.color = new Color (Random.value, Random.value, Random.value, 1.0f); } }
Now, re-run the app and every time you look at the cube it will change color!
… and click!
With Gaze Based Input now setup, we can also receive click events, modify the script above to add a click handler and change the color to black when clicking whilst looking at the cube:
Cameleon.cs:
using UnityEngine; using UnityEngine.EventSystems; public class Cameleon : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler { public void OnPointerEnter(PointerEventData eventData) { GetComponent<Renderer>().material.color = new Color (Random.value, Random.value, Random.value, 1.0f); } public void OnPointerClick(PointerEventData eventData) { GetComponent<Renderer>().material.color = new Color (0, 0, 0, 1.0f); } }
Now, re-run the app and if you click while looking at the cube it will go dark.
That’s it! Congratulations, you’ve built your first Google Cardboard app. I hope this article helped!
March 18, 2016 at 4:08 am
Awesome!! Thanks for the post. This is really going to help me make my first google cardboard app.
April 14, 2016 at 12:15 am
One question I have is, if I build with this on Unity, and I want to play my unity game on my windows 8.1 tablet which is x86. Will the stereoscopy and other cardboard stuff work on my tablet? I am intending to turn the tablet into a cardboard device possibly, thanks. | http://talesfromtherift.com/google-cardboard-hello-world-in-unity-5/ | CC-MAIN-2018-17 | refinedweb | 988 | 56.05 |
It was suggested before that you should write a delimiter (space) in the file. Otherwise all the numbers will be right after each other.
out << num1 << " " << num2 << " " << ...
This is a discussion on need some help within the C++ Programming forums, part of the General Programming Boards category; It was suggested before that you should write a delimiter (space) in the file. Otherwise all the numbers will be ...
It was suggested before that you should write a delimiter (space) in the file. Otherwise all the numbers will be right after each other.
out << num1 << " " << num2 << " " << ...
i will make that adjustment now. any suggestions on how to get my search at the bottom to only print out the one of the inputs of the terminal information?
latest code still no data prints out get press any key to continue after i enter the number 1 to see the first input. I am so fraustrated with this program. Doing a programming class with no instructor near by is terrible.
I am having these problems with the excercises. man i cant wait for the test. lol I am getting it very slowly so maybe i will be okay.
Code:#include <iostream> #include <fstream> #include <string> #include <iomanip> #include<cassert> using namespace std; class TermInfo { public: string bldg; char accessCode; int transRate; string termType; int serviceDay; int serviceMonth; int serviceYear; int TermNumber; }; void main() { /* int TotalTerm; */ int const TotalTerm = 2; cout << "Enter two sets of data for your terminal entrys today" << "\n"; /* cin >> TotalTerm; */ ofstream outFile("afile.txt"); assert(outFile.is_open()); TermInfo info[TotalTerm]; for (int i=0; i < TotalTerm; i++) { cout << "Enter Terminal Number (INT): " << "\n"; cin >> info[i].TermNumber; cout << "Enter Transmission rate (INT): " << "\n"; cin >> info[i].transRate; cout << "Enter terminal type (String): " << "\n"; cin >> info[i].termType; cout << "Enter building terminal is located (String): " << "\n"; cin >> info[i].bldg; cout << "Enter access code to terminal (Char): " << "\n"; cin >> info[i].accessCode; cout << "Enter day of last servicing date (dd) (INT): " << "\n"; cin >> info[i].serviceDay; cout << "Enter month of last servicing date (mm)(INT): " << "\n"; cin >> info[i].serviceMonth; cout << "Enter year of the last servicing date (YYYY) (INT): " << "\n"; cin >> info[i].serviceYear; outFile << info[i].TermNumber << info[i].transRate << info[i].termType << info[i].bldg << info[i].accessCode << info[i].serviceDay << info[i].serviceMonth << info[i].serviceYear; } outFile.close(); /* This section gets value from the closed file */ ifstream inFile("afile.txt"); if(!inFile) { cerr << "File could not be opened!" << "\n"; exit (1); } cout << "Enter Terminal number to search for: " << "\n"; int search; cin >> search; TermInfo currentInfo; while(inFile >> currentInfo.TermNumber >> currentInfo.transRate >> currentInfo.termType >> currentInfo.bldg >> currentInfo.accessCode >> currentInfo.serviceDay >> currentInfo.serviceMonth >> currentInfo.serviceYear) { if(search == currentInfo.TermNumber) { cout << currentInfo.TermNumber << " " << currentInfo.bldg << " " << currentInfo.accessCode << "\n"; cout << currentInfo.transRate << " " << currentInfo.termType << " " << currentInfo.serviceDay << "\n"; cout << currentInfo.serviceMonth << " " << currentInfo.serviceYear << "\n"; } else cout << "please re run the program" ; } }
you are getting close.
like anon already said, you have to output some delimiter when writing the record.
as long as you don't input any whitspace when reading the strings it should work.as long as you don't input any whitspace when reading the strings it should work.Code:outFile << info[i].TermNumber << " " << info[i].transRate << " " << info[i].termType << " " << info[i].bldg << " "<< info[i].accessCode << " " << info[i].serviceDay << " " << info[i].serviceMonth << " " << info[i].serviceYear << endl;
if you want to allow whitespace in the strings you will have to write some different delimiter and use getline() to read the data.
Kurt
Last edited by ZuK; 07-15-2006 at 09:31 AM.
Thanks for all your help. I got it to work now. It seems the small things tend to cause more trouble than the ones you think are harder.
I appreciate the help guys
As already mentioned, this should be int main() . . . .As already mentioned, this should be int main() . . . .Code:void main(). | http://cboard.cprogramming.com/cplusplus-programming/80973-need-some-help-3.html | CC-MAIN-2015-22 | refinedweb | 643 | 58.69 |
#include <deal.II/multigrid/mg_transfer.h>
Implementation of transfer between the global vectors and the multigrid levels for use in the derived class MGTransferPrebuilt and other classes.
Definition at line 279.
Sizes of the multi-level vectors.
Definition at line 366 of file mg_transfer.h.
Mapping for the copy_to_mg() and copy_from_mg() functions. Here only index pairs locally owned
The data is organized as follows: one vector per level. Each element of these vectors contains first the global index, then the level index.
Definition at line 377 of file mg_transfer.h.
Additional degrees of freedom for the copy_to_mg() function. These are the ones where the global degree of freedom is locally owned and the level degree of freedom is not.
Organization of the data is like for
copy_indices_mine.
Definition at line 388 of file mg_transfer.h.
Additional degrees of freedom for the copy_from_mg() function. These are the ones where the level degree of freedom is locally owned and the global degree of freedom is not.
Organization of the data is like for
copy_indices_mine.
Definition at line 399 407 of file mg_transfer.h.
The vector that stores what has been given to the set_component_to_block_map() function.
Definition at line 413 of file mg_transfer.h.
The mg_constrained_dofs of the level systems.
Definition at line 419 of file mg_transfer.h. | https://dealii.org/current/doxygen/deal.II/classMGLevelGlobalTransfer.html | CC-MAIN-2021-25 | refinedweb | 215 | 52.66 |
Python is an great language for data analysis due to large data-centric Python packages. One of these packages is Pandas, which makes importing and analyzing data more manageable. This lesson will show you how to attach new rows to a Pandas dataframe or object using the Pandas append approach. We’ll show you step-by-step examples and explain what the append technique does and how the syntax works.
Append Rows to a Pandas DataFrame
The append() function adds rows from another dataframe to the end of the current dataframe. It then returns a new dataframe object. Columns not present in the original dataframes are created as new columns, and the new cells are filled with a NaN value.
The Pandas append method adds new rows to an existing Pandas object. It is a widespread technique for data cleansing and data wrangling in Python.
The effectiveness of this strategy is determined by how we use the syntax. Let’s look at the syntax and optional parameters with that in mind.
We’ll go over the syntax for the Pandas add method here and both Pandas dataframes and Pandas Series objects that have their syntax, which we’ll discuss.
Before we get into the syntax, bear the following in mind:
- First and foremost, these syntax explanations presume you’ve already installed the Pandas package. You can accomplish this by using the following code:
import pandas as pd
- Second, these grammar explanations presume you already have two Pandas dataframes or other objects to join.
The actual syntax is as follows:
DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
It’s pretty easy to use the append method on a dataframe. The first dataframe’s name is typed first, followed by .append(), which is vital to invoke the method.
The name of the second dataframe, which you wish to append to the end of the first, is then typed inside the parenthesis. You can also utilize additional optional arguments, which I’ll go over in the parameters section.
The syntax for adding items to a series
The syntax for appending to a Series is similar to that of a dataframe. The first Series’ name is typed first, followed by .append() to invoke the method.
series_1.append(series_2)
Then you write the name of the second series, which you wish to append to the end of the first, inside the parenthesis. Once again, some optional alternatives can alter the method’s behavior significantly.
Parameters :
These parameters comprise the following:
other
A DataFrame, a Series, or a dict-like object, or a collection of these
ignore_index
If True, the index labels are not used. You can manage the index of the new output Pandas object with the ignore_index option.
It is set to ignore_index = False by default. Pandas preserve the original index values from the two input dataframes in this situation. Remember that this can result in duplicate index values, which can cause issues.
If you set ignore_index = True, Pandas will disregard the index values in the inputs and produce a new index for the output. The index values will be labeled 0, 1,… n – 1.
verify_integrity(Optional)
If true, raise a ValueError when establishing an index with duplicates.
The verify_integrity argument verifies the new index’s “integrity.” Python will generate an error message if you set verify_integrity = True and the index has duplicates.
Verify_integrity = False is the default value for this argument. Python will accept duplicates in this case.
Sort (Optional)
If the columns of self and others are not aligned, sort them. In a future pandas version, the default sorting is replaced with not-sorting. To turn off the warning and sort, explicitly pass sort=True. To disable the warning and avoid sorting, explicitly give sort=False. If the two input dataframes have distinct columns, the sort argument determines how the columns are sorted.
This parameter is set to sort = False by default. When the columns are concatenated together in this scenario, they are not sorted. Pandas will re-sort the columns in the output if you specify sort = True.
Returns
DataFrame is attached to the results.
This technique is adaptable because you may use it on various Pandas objects. This method can be applied to the following situations:
- dataframes
- Series
When we use append on dataframes, the columns in the dataframes are frequently the same. However, if the input dataframes have distinct columns, the output dataframe will include both inputs’ columns.
Pandas’ append output
The input determines the append’s output. In most cases, the result will be a new Pandas object with the second object’s rows attached to the bottom of the original object.
If the inputs are dataframes, the output will also be a dataframe. If the inputs are all series, the outcome will be a series.
It’s also worth noting that the append() method creates a new object while leaving the two original input objects alone. Beginners may be confused by this, so keep in mind that the process creates a new object.
Example 1: Appending new rows to a Pandas object
Let’s look at a couple of instances of how to add new rows to a Pandas object using append.
You must accomplish two things before running any of the examples:
- importing Pandas
- make the dataframes we’ll be using
importing Pandas
Let’s start by importing Pandas. You can accomplish this by using the following code:
import pandas as pd
It allows us to invoke pandas functions with the pd prefix, the standard.
Make a dataframe
Let’s make two dataframes now. First, we’ll construct dataframes with imitation sales data in this section. In fact, you can make these using the code below:
sales_data_one = pd.DataFrame({"name":["William","Emma","Sofia","Markus","Edward"] ,"region":["East",np.nan,"East","South","West"] ,"sales":[50000,52000,90000,np.nan,42000] ,"expenses":[42000,43000,np.nan,44000,38000]}) sales_data_two = pd.DataFrame({"name":["Thomas","Ethan","Olivia","Arun","Anika","Paulo"] ,"region":["West","South","West","West","East","South"] ,"sales":[72000,49000,np.nan,67000,65000,67000] ,"expenses":[39000,42000,np.nan,39000,44000,45000]})
Let’s print these out so you can have a rough idea of what’s inside:
print(sales_data_one) print(sales_data_two)
These dataframes, as you can see, contain sales information such as name, region, total sales, and expenses. It’s also worth noting that, despite having identical columns, the dataframes have distinct rows. To append the rows from sales_data_two to sales_data_one, we’ll utilize the append() method.
Append new Rows to a DataFrame
Let’s begin with the basics. We’ll append the sales_data_two to the end (or bottom) of sales_data_one. So, let’s execute the code first, and then we’ll explain what we’ve done:
sales_data_one.append(sales_data_two)
It is a straightforward procedure. To invoke the method, type the first dataframe’s name, sales_data_one. However, to invoke the process, use append(). We have the name of the second dataframe, sales_data_two, inside the parentheses. In addition, the rows of both are piled on top of each other in the resulting dataframe.
However, one thing to note is that there are duplicate values in the numeric index on the left. Because the indexes of the two original input dataframes both contained comparable values, this is the case (i.e., the index for both started at 0 and incremented by 1 for each row).
These index duplications could be harmful. As a result, in the following example, we’ll correct it. Ignore the index and reset it when you insert new rows
We’ll join the rows of the two dataframes here, but it will reset the resulting dataframe’s index. It will produce a new numeric index with a value of 0. Set ignore_index = True to accomplish this. It effectively causes Python to “ignore” the index in the input dataframes and build a new index for the output dataframes:
sales_data_one.append(sales_data_two, ignore_index = True)
The index in the output starts at 0 and increases by 1 for each row until it reaches 10. It is a new index for the output dataframes, and it essentially eliminates any duplicate index labels from the input dataframes.
Ensure the index is still intact when you attach new rows to the index.
Instead of resetting the index, let’s double-check it. We’ll achieve this by setting verify_integrity to True. It will look for duplicate index labels in the inputs. Pandas will throw an error if there are identical index labels.
Let’s have a look at some examples:
sales_data_one.append(sales_data_two, verify_integrity = True)
Verify_integrity is set to True in this case. This function looked for duplicate index labels in the incoming dataframes. Running this code resulted in a ValueError, as you can see. The cause for this is that the two input dataframes had duplicate index labels. They both had rows with 0, 1, 2, 3, and 4 written on them.
You may need to do some data cleaning on your input data to remove duplicate rows if you get an error like this. Alternatively, you may ignore the index, as we did in the example above. The way you address things is highly dependent on the situation.
Example #2: Make two data frames and append them to each other.
# Importing pandas as pd import pandas as pd # Creating the first Dataframe using dictionary dFrameOne = df = pd.DataFrame({"a":[11, 12, 13, 14], "b":[15, 16, 17, 18]}) # Creating the Second Dataframe using dictionary dFrameTwo = pd.DataFrame({"a":[11, 12, 13], "b":[15, 16, 17]}) # Print DataFrame 1 print(dFrameOne, "\n") # Print DataFrame 2 dFrameTwo dFrameTwo should now be appended to the end of dFrameOne. # to append dFrameTwo at the end of dFrameOne dataframe dFrameOne.append(dFrameTwo)
It’s worth noting that the index value from the second data frame is preserved in the added data frame. We can set ignore_index=True if we don’t want that to happen.
# A continuous index value will be maintained # across the rows in the new appended data frame. dFrameOne.append(dFrameTwo, ignore_index = True)
Example 3: Append a dataframe of a different shape like an example
Non-existent values in one of the data frames are filled with NaN values if the number of columns in the data frame is uneven.
# Importing pandas as pd import pandas as pd # Creating the first Dataframe using dictionary dFrameOne = pd.DataFrame({"a":[1, 2, 3, 4], "b":[5, 6, 7, 8]}) # Creating the Second Dataframe using dictionary dFrameTwo = pd.DataFrame({"a":[1, 2, 3], "b":[5, 6, 7], "c":[1, 5, 4]}) # for appending df2 at the end of df1 dFrameOne.append(dFrameTwo, ignore_index = True)
The new cells are filled with NaN values, as you can see.
Example 4: Appending Housing Data
In the case of real estate investing, we’re seeking to merge the 50 dataframes, including housing data, into a single dataframe. We do this for a variety of reasons. Combining these is easier and makes sense for a couple of reasons, but it also uses less RAM. A date and value column is present in every dataframe. This date column appears in all of the dataframes, but it should be shared by them, essentially halving our overall column count.
You may have many objectives in mind when integrating dataframes. For example, you might want to “append” to them, which means you’ll be adding rows to the end. Here are some dataframes to get you started:
import pandas as pd df1 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'US_GDP_Thousands':[50, 55, 65, 55]}, index = [2001, 2002, 2003, 2004]) df2 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'US_GDP_Thousands':[50, 55, 65, 55]}, index = [2005, 2006, 2007, 2008]) df3 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'Low_tier_HPI':[50, 52, 50, 53]}, index = [2001, 2002, 2003, 2004])
There are two significant differences between these two. The indexes of df1 and df3 are the same, but the columns are different. Different indices and columns distinguish df2 and df3. We can discuss various approaches to bringing these together with concatenation if you so wish. Appending is similar to concatenation, but it is a little more forceful in that the dataframe will just be appended to, adding to the rows. Let’s look at an example of how it works typically, as well as where it could go wrong:
df4 = df1.append(df2) print(df4)
That’s what an append is supposed to do. Most of the time, you’ll do something similar to this as if you were putting a new record into a database. Dataframes were not designed to be efficiently added; instead, they were intended to be changed based on their starting date, but you can append if necessary. What happens when data with the same index is appended?
df4 = df1.append(df3) print(df4)
That’s unfortunate, to say the least. Some people wonder why concatenation and to append both fails. That is the reason. Because the columns shared contain the same data and index, combining these dataframes is significantly more efficient. Another example is to append a series maybe. Because of the nature of append, you’re more likely to be adding a series rather than an entire dataframe.
To this point, we haven’t discussed the series. A series is a dataframe with only one column. Although a series has an index, all that remains is the data when converted to a list. The return is a series whenever we say something like df[‘column’].
s = pd.Series([80,2,50], index=['HPI','Int_rate','US_GDP_Thousands']) df4 = df1.append(s, ignore_index=True) print(df4)
We must ignore the index when adding a series because it is the law unless the series has a name.
Conclusion
The merging of two or more data sets into a single data set is known as data merging. This approach is usually required when you have raw data stored in multiple files, workbooks, or data tables that you want to analyze all at once.
Pandas come with several built-in techniques for merging DataFrames. Append() is a special case of concat() that adds row(s) to the end of the current DataFrame (axis=0 and join=’outer’). Although the method appears to be quite simple to apply, there are a few strategies you should be aware of to speed up your data analysis. | https://www.codeunderscored.com/pandas-dataframe-append-explained-with-examples/ | CC-MAIN-2022-21 | refinedweb | 2,401 | 64.91 |
Binary search (Java)
[edit] Overview
An implementation of binary search in Java. This implementation is of illustrative purpose as Java provides static binary search methods in the Arrays and Collections classes. Searches for an element in a sorted list of elements. Returns the index of the element if found or the negative index where the element should be inserted to maintain ascending ordering. Therefore this is an implementation of binary search as an insertion search, not a pure exsistence search, which would only return if the element was found or not.
[edit] Implementation.
While we are searching, the interval [0, left] is empty or contains only list values < value. The interval [right, n-1] is empty or contains only list values > value. The remaining search interval is [left, right]. The parts left and right of that interval have been searched.
<<search>>= do { mid = (left + right) / 2; midVal = values.get(mid); if (value.compareTo(values.get(mid)) < 0) right = mid - 1; else if (value.compareTo(values.get(mid)) > 0) left = mid + 1; else return mid; } while (left <= right);
Now left > right and the value was not found in the list.: all indices in i1 have list values < value, all indices in i2 have list values > value and i1 merged with i2 equals i. We now have two possible cases:
Case a) value < midVal & right = mid-1. From the first part follows that mid is in interval [right, n-1] and from the second part follows that mid is at the left edge of the interval, so mid is the smallest index with list value > value. So in case a) an insertion must happen on index mid.
Case b) value > midVal & left = mid+1. From the first part follows that mid is in interval [0, left]. From the second part follows that mid is at the right edge of the interval. This means mid is the largest index with a list value < value, so in case b) we need to insert at mid + 1.
<<return>>= return (value.compareTo(midVal) < 0) ? -mid : -(mid + 1);
[edit] Usage
Illustration of the functionality using JUnit 4 unit tests for strings and integers:
<<test_strings>>= assertEquals(-1, BinarySearch.search("Billy", Arrays.asList("Anny","Emmy","Grammy")));
<<test_integers>>= assertEquals(-1, BinarySearch.search(2, Arrays.asList(1, 3, 4)));
The complete program:
<<BinarySearch.java>>= import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.Arrays; import java.util.List; public class BinarySearch { static <T extends Comparable<? super T>> int search(T value, List<T> values) { int n = values.size(); int mid, left, right; T midVal; left = 0; right = n - 1; search return } @Test public void testStringSearch() { test_strings } @Test public void testIntegerSearch() { test_integers } }hijackerhijacker | http://en.literateprograms.org/Binary_search_(Java) | CC-MAIN-2014-52 | refinedweb | 445 | 58.69 |
Basic hypergraph operations
At the heart of Graphbrain lies the Semantic Hypergraph (SH). In practical terms, we will talk simply about hypergraphs, and we will treat them as a type of database, which contains a searchable collection of hyperedges.
Graphbrain provides abstractions to create, modify and search persistent hypergraph databases, as well as to define and manipulate hyperedges. In this section we introduce these basic operations, upon which all aspects of the library rely on.
The two central functions of Graphbrain: hgraph() and hedge()
The root namespace
graphbrain contains the two most fundamental functions of the library:
hgraph(locator_string), which creates/opens a persistent hypergraph.
hedge(source), which creates a hyperedge from a string or a Python list or tuple.
In fact, the latter is implemented in
graphbrain.hyperedge, but it is imported to the root namespace by default for convenience. We will see that, with just these two functions, a lot can be achieved.
Creating and manipulating hyperedges
Graphbrain defines the object class
Hyperedge, which provides a variety of methods to work with hyperedges. The full interface of this class is described in the API reference. However, these objects are not meant to be instantiated directly. Instead, the
hedge function can be used to create such an object directly from a string representation conforming to the SH notation. For example:
from graphbrain import hedge edge = hedge('(plays/P.so mary/C chess/C)')
In the above example,
edge is an instance of the
Hyperedge class. Hyerpedges are Python sequences. In fact, the class
Hyperedge is derived from
tuple, so it makes it possible to do things such as:
person = edge[1]
In this case,
person will be assigned the second element of the initial hyperedge, which happens to be the atom
mary/C. Range selector also work, but they do not automatically produce hyperedges, because subranges of the element of a semantic hyperedge are not guaranteed to be valid semantic hyperedges themselves. Instead, simple tulpes are returned. For example,
edge[1:] from the example is not a valid hyperedge. Nevertheless, such tuples of hyperedges are often useful:
>>> edge[1:] (mary/C, chess/C) >>> type(edge[1:]) <class 'tuple'>
It is possible to test a hyperedge for atomicity like this:
>>> edge.is_atom() False >>> person.is_atom() True
Another frequently useful task if that of determining the type of a hyperedge:
>>> edge.type() 'R' >>> edge[0].type() 'P' >>> person.type() 'C'
Creating and populating hypergraphs
Graphbrain hypergraphs are created and/or opened like this:
from graphbrain import hgraph hg = hgraph('example.db')
The argument
'example.db' corresponds to a local file in the filesystem, where the hypergraph is persisted. A full path can also be provided, e.g.:
hgraph('users/alice/books.db'). The object returned by this function is of type
Hypergraph. Like
Hyperedge, it provides a number of general-purpose methods to work with hypergraphs and is not meant to be directly instantiated.
Graphbrain comes with a default implementation of hypergraph database based on SQLite 3. This is a nice general-purpose option, because it is available in all popular operating systems and Python comes with native support for it. Files with extensions
.db,
.sqlite or
.sqlite3 will be opened as SQLite-based hypergraph databases. For other options, see the section on hypergraph database backends. One possible disadvantage of SQLite is that it is not very space-efficient. This can become a problem with large hypergraphs, and a better option in this case might be the LevelDB-based hypergraph database. This backend is not included by default because it is currently hard to install outside of Linux. To support LevelDB, you will need to build Graphbrain from source with a special option, as explained in the installation instructions.
Adding hyperedges to a hypergraph is simple. For example, let us add the edge that was defined above:
hg.add(edge)
We can then check if this edge exists in the hypergraph:
>>> hg.exists(edge) True
Notice that adding a hyperedge to a hypergraph implies the recursive addition of all of the elements of the hyperedge, so it is also the case that:
>>> hg.exists(edge[1]) True
A distinction is made with the notion of primary hyperedge. A primary hyperedge is, by default, one that was added directly, while the recursively added ones are considered non-primary. It is possible to check this:
>>> hg.is_primary(edge) True >>> hg.is_primary(edge[1]) False
It is possible to add an edge as non-primary:
>>> moon = hedge('(of/B.ma moon/C jupiter/C)') >>> hg.add(moon, primary=False) (of/B.ma moon/C jupiter/C) >>> hg.is_primary(moon) False
As with
Hyperedge, the full range of methods of
Hypergraph is documented in the API reference.
Adding many hyperedges as a batch (for speed)
With some hypergraph database backends, as is the case for the default one (SQLite 3), adding a large number of edges can be much faster if done in a batch. To help define such bath operations, Graphbrain includes the
hopen() context manager, to be used with Python’s
with statements. This works in a very similarly to the
with open... expressions often used with files:
with hopen('example.db') as hg: for edge in large_edge_list: hg.add(edge)
Since it never hurts performance, it is advisable to always use
with hopen... when adding large number of hyperedges to a hypergraph database.
The neighborhood of a hyperedge (star)
Hypergraphs are fundamentally about relationships. In an analogous fashion to graphs/networks, the neighborhood of an entity (other entities that it is directly connected to) is a simple but powerful concept. With graphbrain, the
star() method provides one type of neighborhood that is particularly natural for hypergraphs and has wide applicability: it produces the set of hyperedges that contain a given hyperedge. For example, let us populate a hypergraph like this:
>>> hg.add(hedge('(of/B.ma moon/C jupiter/C)')) >>> hg.add(hedge('(of/B.ma moon/C saturn/C)'))
Se let us obtain the star of the atom
moon/C:
>>> hg.star(hedge('moon/C')) <generator object at 0x102382d30>
It returns a generator, allowing for the iteration through a very large number of hyperedges without exhausting memory. In this case, let us just convert the generator into a list to see the results:
>>> list(hg.star(hedge('moon/C'))) [(of/B.ma moon/C jupiter/C), (of/B.ma moon/C saturn/C)]
Let us combine several of the previous ideas to define a specific type of neighborhood: the set of hyperedges of type concept that are directly connected to
moon/C:
concepts = set() for edge in hg.star(hedge('moon/C')): for subedge in edge: if edge.type() == 'C': concepts.add(subedge)
The set
concepts will then contain:
moon/C,
jupiter/C,
saturn/C.
Hyperedges containing a given set of hyperedges
The hypergraph database provides a very efficient way to query for all hyperedges that include a given set of hyperedges, with the method
edges_with_edges():
>>> hg.add('(plays/P mary/C chess/C)') (plays/P mary/C chess/C) >>> hg.add('(plays/P john/C chess/C)') (plays/P john/C chess/C) >>> hg.add('(plays/P alice/C handball/C)') (plays/P alice/C handball/C) >>> list(hg.edges_with_edges([hedge('plays/P'), hedge('chess/C')])) [(plays/P john/C chess/C), (plays/P mary/C chess/C)]
An optional
root argument can be added, further requiring the matching edges to contain an atom with that root (at the top level):
>>> list(hg.edges_with_edges([hedge('plays/C'), hedge('chess/C')], root='john')) [(plays/C john/C chess/C)]
Searching for hyperedges
Another fundamental way to query a hyperedge is by search patterns. Search patterns are templates that match hyperedges. Graphbrain provides a sophisticated pattern language that allows for semantically rich modes of matching. This will be discussed in greater detail in the next section. For now, let us just consider the wildcard
*, which matches any hyperedge (atomic or not). For example, the pattern
(of/B.ma * *) matches both of the previously defined hyperedges. The
search() method of
Hypergraph allows for search using these patterns. Like
star(), it returns a generator:
>>> list(hg.search('(of/B.ma * *)')) [(of/B.ma moon/C jupiter/C), (of/B.ma moon/C saturn/C)]
Degrees and deep degrees
In conventional graph theory, there is the notion of the degree of a node, which is the number of other nodes that it is directly connected to. This is a simple but generally useful measure of the centrality of a node in the graph. In hypergraphs we can also have the same notion of degree, with the only difference that a single hyperedge can connect one entity to several others. Graphbrain keeps track of the degree of every hyperedge, and the
Hypergraph class provides a method to obtain it:
>>> from graphbrain import * >>> hg = hgraph('example.db') >>> hg.degree('alice/C') 0
The degree of any hyperedge that does not exist in the hypergraph is 0. Notice also that
degree(), as well as many other
Hypergraph methods, conveniently accept the string representation of hyperedge, and transparently perform the conversion.
Let us add a few hyperedges and check the resulting degrees:
>>> hg.add('(in/B alice/C wonderland/C)') (in/B alice/C wonderland/C) >>> hg.degree('alice/C') 1 >>> hg.degree('(in/B alice/C wonderland/C)') 0 >>> hg.add('(reads/P john/C (in/B alice/C wonderland/C))') (reads/P john/C (in/B alice/C wonderland/C)) >>> hg.degree('(in/B alice/C wonderland/C)') 1 >>> hg.add('(plays/P alice/C chess/C)') (plays/P alice/C chess/C) >>> hg.degree('alice/C') 2
Given that hyperedges can contain recursively contain other hyperedges, we can also consider the deep degree, which takes into account deep connections. For example, consider the edge
(reads/P john/C (in/B alice/C wonderland/C)). For the calculation of degrees,
john/C is not considered here to be connected to
alice/C, but such a connection is counter for the deep degree:
>>> hg.degree('alice/C') 2 >>> hg.deep_degree('alice/C') 3
Hyperedge attributes
The hypergraph database allows for the association of attributes to hyperedges. These can be strings, integer or floats, and are identified by a label. For example, one can associate a hyperedge to the text that it corresponds to:
>>> hg.set_attribute('(in/B alice/C wonderland/C)', 'text', 'Alice in Wonderland') True >>> hg.get_str_attribute('(in/B alice/C wonderland/C)', 'text') 'Alice in Wonderland'
Notice that the method
set_attribute() is used to set attributes of any type, but it is up to the programmer to choose the getter method according to the desired output type:
>>> hg.set_attribute('alice/C', 'age', 7) True >>> hg.get_int_attribute('alice/C', 'age') 7 >>> hg.set_attribute('alice/C', 'height', 1.2) True >>> hg.get_float_attribute('alice/C', 'height') 1.2
In fact, this is how degrees and deep degrees are stored, respectively in the attributes “d” and “dd”, so these attribute names should not be used for other purposes. The call
hg.degree(edge) is equivalent to
hg.get_int_attribute(edge, 'd').
Integer attributes can also be incremented and decremented:
>>> hg.add('(red/M button/C)') (red/M button/C) >>> hg.set_attribute('(red/M button/C)', 'clicks', 0) True >>> hg.inc_attribute('(red/M button/C)', 'clicks') True >>> hg.get_int_attribute('(red/M button/C)', 'clicks') 1 >>> hg.dec_attribute('(red/M button/C)', 'clicks') True >>> hg.get_int_attribute('(red/M button/C)', 'clicks') 0
Local and global counters
Normally, when adding a hyperedge that already exists, nothing is changed. It is sometimes useful to count occurrences while adding hyperedges, and in this case the
count=True optional argument can be specified when calling
add(). This increments the
count integer argument of the hyperedge every time it is added:
>>> hg.add('(counting/P sheep/C)', count=True) (counting/P sheep/C) >>> hg.get_int_attribute('(counting/P sheep/C)', 'count') 1 >>> hg.add('(counting/P sheep/C)', count=True) (counting/P sheep/C) >>> hg.get_int_attribute('(counting/P sheep/C)', 'count') 2
The hypergraph database also provides the following global counters:
Hypergraph.atom_count(): total number of atoms
Hypergraph.edge_count(): total number of hyperedges
Hypergraph.primary_atom_count(): total number of primary atoms
Hypergraph.primary_edge_count(): total number of primary hyperedges
Working with hyperedge sequences
The hypergraph database provides for a mechanism to organize hyperedges into sequences. This is useful when storing hyperedges extracted from natural language sources where the order in which they appear can be relevant. For example, we might be interested in parsing every sentence in a book into a hyperedge and then being able to know which hyperedges correspond to the sentence that came before and after.
A hyperedge can be added to the end of a given sequence in the hypergraph (identified by a string label). For example:
>>> hg.add_to_sequence('sentences', '(is/P this/C (the/M (first/M sentence/C)))') (seq/P/. sentences 0 (is/P this/C (the/M (first/M sentence/C))))
The outer edge with the special predicate
seq/P/. assigns the hyperedge to the sequence “sentences” at position 0. Furthermore, for every sequence a special hyperedge is created to store attributes related to the sequence:
(seq_attrs/P/. sentences)
In its current implementation, this is used only to store the current size of the sequence as an integer under attribute ‘size’. This attribute is used and updated by
hg.add_to_sequence(), to determine the position at which to insert the next element in the sequence.
The method
sequences() returns a generator for all the sequences contained in the hypergraph:
>>> list(hg.sequences()) [sentences]
The method
sequence() provides a generator for all the hyperedges contained in a given sequence, in order:
>>> hg.add_to_sequence('sentences', '(is/P this/C (the/M (second/M sentence/C)))') (seq/P/. sentences 1 (is/P this/C (the/M (second/M sentence/C)))) >>> hg.add_to_sequence('sentences', '(is/P this/C (the/M (third/M sentence/C)))') (seq/P/. sentences 2 (is/P this/C (the/M (third/M sentence/C)))) >>> list(hg.sequence('sentences')) [(is/P this/C (the/M (first/M sentence/C))), (is/P this/C (the/M (second/M sentence/C))), (is/P this/C (the/M (third/M sentence/C)))]
No methods are provided to remove hyperedges from the sequence, or to insert hyperedges somewhere other than the end of the sequence. This is meant to be a very simple and fast mechanism. | http://graphbrain.net/manual/hypergraph-operations.html | CC-MAIN-2021-49 | refinedweb | 2,386 | 58.28 |
.
CPython implementation detail: and the ‘with‘ statement provide convenient ways be provided via the standard library instead. object are Unicode code units. A Unicode code unit is represented by a string chr() and ord() convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the string method encode()...)
A bytearray object is a mutable array. They are created by the built-in bytearray() constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable bytes objects.
The extension module array provides an additional example of a mutable sequence type, as does the collections module..ndbm and dbm.gnu provide additional examples of mapping types, as does the collections module..
An instance method object combines a class, a class instance and any callable object (normally a user-defined function).
Special read-only attributes: __self__ is the class instance object, __func__ is the function object; __doc__ is the method’s documentation (same as __func__.__doc__); __name__ is the method name (same as __func__.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.
Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.
User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object or a class method object.
When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its __self__ attribute is the instance, and the method object is said to be bound. The new method’s __func__ attribute is the original function object.
When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the __func__ attribute of the new instance is not the original method object but its __func__ attribute.
When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.
When an instance method object is called, the underlying function (__func__) is called, inserting the class instance (__self__) in front of the argument list. For instance, when C is a class which contains a definition for a function f(), and x is an instance of C, calling x.f(1) is equivalent to calling C.f(x, 1).
When an instance method object is derived from a class method object, the “class instance” stored in __self__ will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.
Note that the transformation from function object to instance method object happens each time the attribute is retrieved from alist.
Modules are imported by the import statement (see section The import statement). A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the _.
CPython implementation detail: Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly..
Custom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at.
When a class attribute reference (for class C, say) would yield a class method object, it is transformed into an instance method object whose __self__ attributes is C. When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section Implementing Descriptors, it is transformed into an instance method object whose __self__ attribute is the instance. Static method and class method objects are also transformed;. Various shortcuts are available to create file objects: the open() built-in function, and also; they are all open in text mode and therefore follow the interface defined by the io.TextIOBase abstract class._lasti gives the precise instruction (this is an index into the bytecode string of the code object).
Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); the third item of the tuple returned by sys.exc_info(). for __getitem__() methods. type(x).__getitem__(x, i)._info()[2]() function to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.
Called by the format() built-in function (and by extension, the format() method of class str) to produce a “formatted” string representation of an object. The format_spec argument is a string that contains a description of the formatting options desired. The interpretation of the format_spec argument is up to the type implementing __format__(), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.
See Format Specification Mini-Language for a description of the standard formatting syntax.
The return value must be a string object.
These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls.
To automatically generate ordering operations from a single root operation, see functools.total_ordering(). an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__(), since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).
User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id(x).
Classes which inherit a __hash__() method from a parent class but change the meaning).
If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__. Otherwise the inheritance of __hash__() will be blocked, just as if __hash__ had been explicitly set to None.. over attribute access.-in functions. See Special method lookup. call the base class method with the same name, for example, object.__setattr__(self, name, value).
Like __setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object.
Called when dir() is called on the object. A list must be returned.
The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in the class dictionary of another class, known as the owner class. In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ __dict__..
Called to set the attribute on an instance instance of the owner class to a new value, value.
Called to delete the attribute on an instance instance of the owner class..
The starting point for descriptor invocation is a binding, a.x. How the arguments are assembled depends on a:
For instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined. A descriptor can define any combination of __get__(), __set__() and __delete__(). If it does not define __get__(), then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. If the descriptor defines __set__() and/or __delete__(), it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. Data descriptors with __set__() and __get__() defined class, __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.
By default, classes are constructed using type(). A class definition is read into a separate namespace and the value of class name is bound to the result of type(name, bases, dict).
When the class definition is read, if a callable metaclass keyword argument is passed after the bases in the class definition, the callable given will be called instead of type(). If other keyword arguments are passed, they will also be passed to the metaclass. appropriate metaclass is determined by the following precedence rules:
The potential uses for metaclasses are boundless. Some ideas that have been explored including logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.
Here is an example of a metaclass that uses an collections.OrderedDict to remember the order that class members were defined:
class OrderedClass(type): @classmethod def __prepare__(metacls, name, bases, **kwds): return collections.OrderedDict() def __new__(cls, name, bases, classdict): result = type.__new__(cls, name, bases, dict(classdict)) result.members = tuple(classdict).
The following methods are used to override the default behavior of the isinstance() and issubclass() built-in functions.
In particular, the metaclass abc.ABCMeta implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as “virtual base classes” to any class or type (including built-in types), including other ABCs.
Return true if instance should be considered a (direct or indirect) instance of class. If defined, called to implement isinstance(instance, class).
Return true if subclass should be considered a (direct or indirect) subclass of class. If defined, called to implement issubclass(subclass, class).
Note that these methods are looked up on the type (metaclass) of a class. They cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class.
See also. It is also recommended that mappings provide the methods keys(), values(), items(), get(), clear(), setdefault(), pop(), popitem(), copy(), and update() behaving similar to those for Python’s standard dictionary objects. The collections module provides a MutableMapping abstract base other numerical operators. It is recommended that both mappings and sequences implement the __contains__() method to allow efficient use of the in operator; for mappings, in should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; for mappings, __iter__() should.
Note
Slicing is done exclusively with the following three methods. A call like
a[1:2] = b
is translated to
a[slice(1, 2, None)] = b
and so forth. Missing slice items are always filled in with keys().
Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see Iterator Types.
Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.
If the __reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol (__len__() and __getitem__()). Objects that support the sequence protocol should only provide __reversed__() if they can provide an implementation that is more efficient than the one provided by reversed().
The membership test operators (in and not in) are normally implemented as an iteration through a sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence.
Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.
For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference.. [2].
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance,(), float() and round(). Should return a value of the appropriate type.
Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). Must return an integer..
Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception:
>>> class C: ... | http://docs.python.org/release/3.2/reference/datamodel.html#object.__init__ | crawl-003 | refinedweb | 2,367 | 55.03 |
I have already outlined earlier in this forum what my code is supposed to do. It is supposed to display a window with three buttons, "Drop", "Retrieve", and "Quit", and a ball. My code accomplished...
I have already outlined earlier in this forum what my code is supposed to do. It is supposed to display a window with three buttons, "Drop", "Retrieve", and "Quit", and a ball. My code accomplished...
I updated my code to this and it still isn't doing what it's supposed to :(
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DropPanel extends JPanel...
Changed some things. Now, when I run the program, the window pops up with two buttons and a green ball at the top of the screen. When I click "Drop", the ball only drops 20 pixels, but does not...
Omg exciting! I was running the DropPanel but was supposed to be running DropDriver. So, when I run DropDriver, A window pops up with my two buttons, and a green ball starts dropping from about the...
Yes there are three classes in total for this program:
/**
* A class that puts a graphics window on your display
*/
import java.awt.*;
import javax.swing.*;
OK thanks! I've updated my code, an attempted to add some buttons...
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DropPanel extends JPanel implements...
Well, right now my part of the program is pretty much all compilation errors. I have yet to even add the part where the ball is retrieved, nor have I added any buttons. I am mostly concerned with the...
I am trying to make a display window with three buttons, "Drop", "Retrieve", and "Quit". When "Drop" is clicked, a ball must drop from the top of the screen and stop at the bottom. When "Retrieve" is...
I am wondering if my answer to this most recent assignment is correct. Just want see if anyone has any input before I submit. Any comments would be appreciated! Thanks!
Here is the assignment:The...
I can't figure out the answer to this homework problem:
Write a static method named countEmptyBowls, to be added to the Bowl class, which is passed an array of Bowl objects, and returns the (int)...
The program is due tonight. That is why we are so persistent haha.. I really am trying in this class I've been going to tutoring and office hours. I guess programming is just not my thing...
I am still very confused as well
I tried to do what you suggested without seeing your LetterProfile class, but it isn't working for me.
--- Update ---
I don't expect the array to be filled magically. I am just very new to...
I will post my whole code again so we're all on the same page lol
import java.util.Scanner;
public class LetterDriver
{
public static void main(String[] args){
yeah I can't get a bigger pic
Enter lines of text, type two returns in a row to end.
[DrJava Input Box]
[DrJava Input Box]
>
Yes I'm in that class and I am not enjoying myself
--- Update ---
Nothing is printing for me still... idk what I'm doing wrong this is awful.
I don't know how to use the java command. Yes, that message was from my IDE.
--- Update ---
I don't understand what you mean in post #8
Nothing prints out. Before, it printed out an input box.
--- Update ---
When I type something in the interactions box, it says "Static Error: Undefined name 'Hello world!'".
am I getting closer?
import java.util.*;
public class LetterDriver{
public static void main(String[] args){
System.out.println("Enter lines of text, type two returns in a row to...
The while loop makes the program stop scanning lines once the user has pressed enter twice (or enters a string of length zero).
I deleted them because they weren't working. I don't know where or how to call these methods but this is one of the ways I tried:
import java.util.*;
public class LetterDriver{
public...
Yes, that was my thread. But I tried calling the two methods in the driver and nothing I do works. I am brand new to computer programming so I'm sure I'm just doing it wrong. | http://www.javaprogrammingforums.com/search.php?s=2a718d573c7c30b3f4b0f26a291052ea&searchid=1075512 | CC-MAIN-2014-41 | refinedweb | 722 | 75.3 |
kdtree 0.0.2
k-d Tree Dart Library #
A basic super fast Dart implementation of the k-dimensional tree data structure. This library is dart port of Javascript implementation:.
Usage #
Using library #
// Create a new tree from a list of points, a distance function, and a // list of dimensions. var tree = KDTree(points, distance, dimensions); // Query the nearest *count* neighbours to a point, with an optional // maximal search distance. // Result is an array with *count* elements. // Each element is an array with two components: the searched point and // the distance to it. tree.nearest(point, count, [maxDistance]); // Insert a new point into the tree. Must be consistent with previous // contents. tree.insert(point); // Remove a point from the tree by reference. tree.remove(point); // Get an approximation of how unbalanced the tree is. // The higher this number, the worse query performance will be. // It indicates how many times worse it is than the optimal tree. // Minimum is 1. Unreliable for small trees. tree.balanceFactor();
Example #
import 'package:kdtree/kdtree.dart'; var points = [ {'x': 1, 'y': 2}, {'x': 3, 'y': 4}, {'x': 5, 'y': 6}, {'x': 7, 'y': 8} ]; var distance = (a, b) { return pow(a['x'] - b['x'], 2) + pow(a['y'] - b['y'], 2); }; var tree = KDTree(points, distance, ['x', 'y']); var nearest = tree.nearest({'x': 5, 'y': 5}, 2); print(nearest);
0.0.1 #
- Initial version
import 'basic_example.dart'; import 'location/location_example.dart'; void main() { print('Basic example: Find one nearest point in list of points'); runBasicExample(); print( 'Location example: Find 30 nearest location to given latitude and longitude from JSON list of locations.'); runLocationExample(44.815, 20.282); }
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: kdtree: :kdtree/kdtree.dart';
We analyzed this package on Jan. | https://pub.dev/packages/kdtree | CC-MAIN-2020-05 | refinedweb | 302 | 60.31 |
accelerometer and servo code trouble
- Login or register to post comments
- by BrandonV
trying to use an accelerometer to control two servos, here is the code I have...
but this code for some reason just causes both servos to sweep constantly back and forth, with what seems like no regard to the position of the accelerometer?
thanks fellas
/*
The circuit:
analog 1: z-axis
analog 2: y-axis
analog 3: x-axis
analog 4: ground
analog 5: vcc
digital 9: servo_s
digital 10: servo_p
*/
// these constants describe the pins.
#include <Servo.h>
Servo servo_S; // create servo object to control a servo (starboard)
Servo servo_P; // create servo object to control a servo (port)
int starboard_val; // variable for starboard servo
int port_val; // variable for port servo
int groundpin = 18; // analog input pin 4 -- ground
int powerpin = 19; // analog input pin 5 -- voltage
int xpin = 1; // x-axis of the accelerometer
int ypin = 2; // y-axis
void setup()
{
servo_S.attach(9); // attaches the servo on pin 9 to the servo object
servo_P.attach(10); // attaches the servo on pin 10 to the servo object
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
}
void loop()
{
analogRead(xpin); // reads accelerometer value in x axis
analogRead(ypin); // reads accelerometer value in y axis
delay(100); // delay before next reading
starboard_val = ((xpin + ypin)/2); // defines starboard servo position
starboard_val = map(starboard_val, 280, 372, 26, 154); // maps values to acceptable servo values
servo_S.write(starboard_val); // sets the servo position according to the value
if (ypin==326)
{
ypin=326;
}
else if (ypin<326)
{
ypin=((326-ypin)+326);
}
else
{
ypin=(326-(ypin-326));
}
port_val = ((xpin + ypin)/2); // defines port servo position
port_val = map(port_val, 280, 372, 26, 154); // maps values to acceptable servo values
servo_P.write(port_val); // sets the servo position according to the scaled value
delay(100); // waits for the servo to get there
}
I think the if statemenst
I think the if statemenst shoul go before
starboard_val = ((xpin + ypin)/2); // defines starboard servo position
starboard_val = map(starboard_val, 280, 372, 26, 154); // maps values to acceptable servo values
servo_S.write(starboard_val); // sets the servo position according to the value
hmm, i took at the values
hmm, i took at the values the servo was receiving and like I expected it was just bouncing between two seeming random numbers (88 and -326 i think),
concerning the values you suggest I should be using, when I look at the output from my accelerometer, I see values in the range of 280 to 372, is that not what it is actually sending out (is it really between 0 and 1024)?
My first post on lmr
and english isnt my main language but Anyway
your error is with your use of analogRead(xpin) and analogRead(ypin), analogRead doesn"t allocate the read value between to (xpin).
the first time your loop is executed, xpin and ypin values are 1, and starboard_val become -162, your servo wont like this value. Below when you test ypin, it allocate -162 to ypin because of it being 1, this is why you have an erratic behavior with your servo, the error is amplified every loop.
you should use analogRead more like this:
myReadValue = analogRead(myReadPin);
that should do it.
hmm interesting, thank youso
it worked!, thanks for your help everyone, it is greatly appreciated!
Not sure about the map
Not sure about the map values, since an analogue reading would give you a 10bit value. 0-1024. I think you could try using contstrain on the function as well to keep the values between the values that you are using. I'm also not sure if when using the map function with values like 280-326 don't wrap around, which would cause some strangeness.(say you had 328, that would wrap around to 282)
Have you tried to read the value that you are sending to the servo, not just what you've read from the adc. It sounds like your values are different from what you'd expect.
Out of curiousity, what exactly are you trying to do?
also i added in a serial
also i added in a serial output to read the values from the accelerometer, they are correct. So im guessing it has something to do with what is written for the servos
also, this error is
also, this error is streaming across the)
oh, yes they are connected
oh, yes they are connected to the 3.3 and grd, that must be a chunk of left over code from an arduino example
y are ur vcc & gnd connected
y are ur vcc & gnd connected to analog ports? those are the acc's pins rite? they sld be connected to the 3.3/5 V & gnd pins on the arduino | http://letsmakerobots.com/node/19053 | CC-MAIN-2015-11 | refinedweb | 792 | 52.23 |
This document describes a way how to execute a selected function(s) out of RAM memory for a project running out of Flash memory.
- Create a custom linker section in the linker file (.ld) where a routine(s) should be placed into. This step is optional if you don't care where exactly in RAM the function should be placed. In such case default sections could be used instead.
MEMORY
{_my_flash : org = 0x01000000, len = 4K // optional - this is dedicated section for the RAM function rom image
m_text : org = 0x01001000, len = 5628K // default section for code
m_my_ram : org = 0x40000000, len = 4K // optional - specific section where a RAM routine(s) should be copied into
m_data : org = 0x40001000, len = 764K // default section for data/stack/heap
}
- If it's intended to keep routine(s) that should be executed from RAM within a specific custom section:
SECTIONS
{
...
.MyRamCode :
{
MY_RAM_START = .; // this symbol is optional
KEEP (*(.MyRamCode)) // KEEP - avoid dead stripping if an object is not referenced
MY_RAM_END = .; // this symbol is optional
} > m_my_ram AT>m_my_flash // the section above is linked into m_my_ram and Rom image is stored into m_my_flash
- Otherwise you can use the default memory areas for code/data if you don't care about the location of the routine(s):
SECTIONS
{
...
.MyRamCode :
{
MY_RAM_START = .; // this symbol are optional
KEEP (*(.MyRamCode)) // KEEP - avoid dead stripping if an object is not referenced
MY_RAM_END = .; // this symbol are optional
} > m_data AT>m_text // the section is linked into default data memory area and its rom image is placed into the default code memory
- add the __attribute__ statements to the RAM function prototypes. The function attribute "longcall" is required to be able to call this RAM function from flash.
__attribute__ ((section(".MyRamCode"))) // place the function below into .MyRamCode section
int test_RAM(int arg1) __attribute__ ((longcall)); // declare the function as "far"
- Default S32DS project startup initializes just the default data sections. Therefore it's necessary to perform section copy-down manually if the functions are placed into a custom section. This must be done before a RAM routine gets called e.g. at the beginning of main() or in the startup routine.
You can create some linker symbols (.MyRamCode RAM and ROM addresses and size) and import them to the module where copy-down is implemented.
__MY_RAM_ADR = ADDR (.MyRamCode);
__MY_RAM_SIZE = SIZEOF (.MyRamCode);
__MY_RAM_ROM_ADR = LOADADDR (.MyRamCode);
The final source file may look like this:
#include <string.h>
extern unsigned long __MY_RAM_ADR;
extern unsigned long __MY_RAM_ROM_ADR;
extern unsigned long __MY_RAM_SIZE;
__attribute__ ((section(".MyRamCode"))) // place the function below into .MyRamCode section
int test_RAM(int arg1) __attribute__ ((longcall)); // declare the function as "far"
...
void main(void)
{
int counter = 0;
memcpy(&__MY_RAM_ADR , &__MY_RAM_ROM_ADR, &__MY_RAM_SIZE); // copy the function from flash to RAM
counter = test_RAM(counter); // call the function
...
}
Hope it helps!
Stan
hello, Stanislav Sliva
I have tested it.but i find a problem which is it can run well in debug,when i take off the MULTILINK UNIVERSAL, and reset the board ,it cannot work normal,can you help me?
i find that if the VMA is different from the LMA, it happens. when the VMA(in ram) is different form LMA(in rom),the s32 will show "Program received signal SIGTRAP, Trace/breakpoint trap.",and go on running by F8 is pressed. if the MULTILINK UNIVERSAL is removed,it can not run normal in run mode.
The facts are as follows:
The MCU is mpc5746c.the ide is S32 Design Studio for Power Architecture Version: 1.2
In debug mode, the problem is as follow figure:
when the code which is " e_bl main" is run,it run _eabi first before into main.During the process , "program received signal SIGTRAP..." happens.
The program can go on running ,when the "resume button " is pressed on.But if I take off the MULTILINK UNIVERSAL,and reset the board,the program
can not runinto main,it is suspendend maybe. when the VMA is the same as LMA in the rom, the problem never happen.i think that the reason is se_illegal but how can i do to avoid it ? help me,help you ,thank you! | https://community.nxp.com/docs/DOC-334030 | CC-MAIN-2020-29 | refinedweb | 675 | 65.01 |
Heres the code:
#include <iostream> #include <iomanip> #include <string> using namespace std; int main () { //enter variables double moneyOwed = 0.0; double moneyPaid = 0.0; double change = 0.0; int change1 = 0; int dollars = 0; int quarters = 0; int dimes = 0; int nickels = 0; int pennies = 0; //enter input cout<<"Enter money owed: $"; cin>>moneyOwed; cout<<"Enter money paid: $"; cin>>moneyPaid; cout<<endl; //calculation if (moneyOwed > moneyPaid) { cout<<"The amount that was given is not enough, please pay the full amount."; cout<<endl; cout<<endl; } else { cout<<fixed<<setprecision(2); change = moneyPaid - moneyOwed; change1 = change*100; dollars = change1/100; quarters = change1%100/25; dimes = change1%100%25/10; nickels = change1%100%25%10/5; pennies = change1%100%25%10%5; //display cout<<"Change due: $"<<change<<endl; cout<<"Dollars: "<<dollars<<endl; cout<<"Quarters: "<<quarters<<endl; cout<<"Dimes: "<<dimes<<endl; cout<<"Nickles: "<<nickels<<endl; cout<<"Pennies: "<<pennies<<endl; cout<<endl; cout<<endl; } system("pause"); return 0; }
I think the problem might be when I convert 'double change' to 'int change1' cause I've displayed 'change1's value on the screen and it sometimes wouldn't equal 'change*100'.For instance, moneyPaid(30.00) - moneyOwed(28.73), the change would be (1.27), but change1 would be (126). Any help would be great. Thanks.
This post has been edited by Forwardechelon: 07 October 2010 - 09:02 PM | http://www.dreamincode.net/forums/topic/194018-change-calculator/ | CC-MAIN-2016-30 | refinedweb | 223 | 62.88 |
Applet Developer's Guide > Java Plug-in and Applet Architecture > Best Practices For Applet Development
Contents
Applets have a complex runtime environment and several issues need to be considered to ensure that applets run predictably on various browsers and versions of Java Plug-ins. This document describes the best practices for applet development and deployment .
Values stored in the applet could persist between
invocations, if the memory acquired by the class loader cache isn't
needed for other purposes. But you can't depend on that behavior.
In general, applets should be stateless. If persistent storage is
needed, use browser cookies.
startmethod as quickly as possible
If
start doesn't terminate,
stop can't
be called. That's important, because garbage collection occurs
after the
destroy method terminates. If the applet
lingers in the
start method, then the applet may not
be torn down properly. (It will be torn down, and garbage
collection will occur, but resources acquired during applet
initialization may not be properly released.)
For a computationally-intensive app like the Clock demo, the trick is to implement the
Runnable interface, do the heavy lifting in the
run method it requires, and launch a separate thread
to do the actual work, as shown in this abstract from the
source code:
public class Clock extends Applet implements Runnable { private volatile Thread timer; // The thread that displays the clock ... public void start() { timer = new Thread(this); // Create the thread and start it timer.start(); } public void stop() { timer = null; // Release the thread resource } public void run() { Thread me = Thread.currentThread(); while (timer == me) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } repaint(); } } ...
Here, the action is to pause the Clock instance that's running
in the new thread (hence the need to store a pointer to it.)
Applets that don't need to do all that can simply put their
processing code into the
run method.
For an interactive app like the spreadsheet demo, that goal is easily achieved, since the majority of time is spent in the event-processing thread, as shown in this abstract from the source code:
public class SpreadSheet extends Applet implements MouseListener, KeyListener // Event processing { public void init() { ... addMouseListener(this); addKeyListener(this); } ... public void start() { isStopped = false; } public void stop() { isStopped = true; } public void keyTyped(KeyEvent e) { // Invoked when an event occurs ... } public void mousePressed(MouseEvent e) { ... } ... class CellUpdater extends Thread { ... public void run() { ... if (!target.app.isStopped && !target.paused) { target.app.repaint(); }
In this particular implementation, each cell has it's own update
thread. Updating is paused when a cell is selected, and only stops
completely when the applet terminates. The important point is that
the applet's
start and stop methods only keep
track of applet state. Most of the time is spent in the underlying
event-processing thread, waiting for the user's keystroke or
mouseclick. The applet's real work then occurs in response to one
of those events.
An ID defines the namespace, and ensures proper naming at all levels of the data hierarchy:
<applet id="myApplet" name="myApplet" ...
Truly stateless applets don't depend on values previously stored in static variables. Since you can't depend on those values to be retained, it's a good idea to create stateless applets. But the user can still store state. It's just that store the data where it belongs--with the user, rather than in the applet code.
To implement a stateless app, access browser cookies or launch with JNLP to use Java Web Start muffins, so the applet gets it's initial settings from persistent storage, rather than using values stored in the program.
To ensure that your applet is stateless, use the classloader_cache attribute to disable the cache. For example:
<applet ... classloader_cache="false"
That setting ensures that the applet is stateless, and that it is truly decoupled from the remainder of the system and from other instances of the applet. It also ensures that the applet runs the exact same way every time, since it won't be affected by state that has been inadvertently retained.
Note:
In the rare case that you expect your users to re-run the same applet repeatedly, you might consider leaving the cache enabled for production for the sake of performance, but disable it during development to ensure quality.
To prevent thread contention, don't update the Swing or AWT GUI from javascript directly. Instead, set up a proxy that forwards the request to the appropriate dispatch thread:
javax.swing.SwingUtilities.invokeLater(Runnable)
java.awt.EventQueue.invokeLater(Runnable)
Minimize the time taken to call from Java into javascript, and from javascript into Java. Don't do long-running work in such calls, or you risk a deadlock. To keep the calls short:
When calling into Java, don't make calls back into javascript if you can possibly help it, and vice versa. In that original plugin, doing so used to lock up the browser. That shouldn't happen anymore, but round-trip calls do introduce significant delays in processing time.
When a javascript function needs the applet to do something, the
best practice is to return a value that tells the applet to do it,
and then call back with the results, or else use
invokeLater to minimize traffic tie ups.
The Java platform has powerful multi-threading capabilities that
you can take advantage of with classes like Thread, Swing
invokeLater, and AWT
invokeLater, as well as the new ThreadPoolExecutor class
that maintains a background thread pool. | http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/applet/best_practices.html | CC-MAIN-2013-48 | refinedweb | 915 | 61.46 |
A simple way to look at Eclipse IoT
Eclipse IoT is a collection of open source projects for the development of Internet of Things solutions. It is one of the most active working groups in the Eclipse Foundation, currently featuring 25 projects. Here we present a brief overview of some popular offerings.
If you’re new to Java and not a member of the Church of Emacs, then there’s a chance that Eclipse is synonymous to your integrated development environment (IDE). Even long-time users are often not aware of the vast software ecosystem that flourishes under the flag of the Eclipse Foundation. Over the past almost fifteen years, the Eclipse project has been restructured into a foundation that works language-agnostic on a wide range of software projects across many verticals; very much like Apache used to be a web server and now is a software foundation that has a much wider product range.
The Internet-of-Things (IoT), in case you’ve had your Internet access blocked for the past five years or been hiding under a rock, is the now ubiquitous fancy term for machine-to-machine communication (M2M), and technologies and concepts emerging from it. Under the organizational lead of Ian Skerrett and Benjamin Cabé from the Eclipse Foundation, one of the seven working groups around particular verticals is Eclipse IoT. It is an umbrella project, which coordinates the efforts of developers that are primarily based at a dozen companies with an interested in IoT or M2M. Amongst those are major players such as IBM, Bosch and Siemens, but also smaller companies that work in particular corners of the IoT, like dc-square and the integration platform openHAB.
The architecture of IoT solutions can be confusing at the best of times, and gaining an overview of when and where particular Eclipse IoT projects fit into that stack can be a daunting task. While it’s possible to find all necessary information in a table on the Eclipse website, especially those new to IoT can easily get lost between protocol acronyms such as CoAP and MQTT, and cryptic project names. (I’m looking at you, Wakaama and Leshan…) One can think about the various Eclipse IoT projects in terms of ecosystems, standards and components.
On the ecosystem level, Eclipse IoT acts as integrator for projects that are required to build complete end-to-end solutions, starting from embedded code on microcontrollers to message brokers on gateways to backend software. Especially industry users often appreciate package solutions that don’t require an elaborate mix-and-match of components. The 4diac project, for example, provides software implementations for the IEC 61499 standard for industrial control systems. This includes the runtime environment, an IDE as well as pre-defined function blocks that can be used in end user applications.
A set of conceptually related tools around embedded IoT is Vorto, EDJE, hawkBit and Concierge. The Vorto GUI allows one to provide language-independent descriptions of devices, which via the Vorto code generators can be conveniently translated into objects/classes in any programming language for which such generator exists. (A lay description how that works is featured in this recent blog post about Vorto). On a very abstract level, a programmer could refer to “the radio” and “send x bytes” in their code, an interface presented by the EDJE hardware abstraction layer that takes care of the technical differences between various devices. Once developed, one can deploy the new code via hawkBIT to a large number of devices at once. As such, hawkBIT may remind some of resin.io, a “send a Docker container to all your embedded devices” service I wrote about earlier. On the device itself then, the Concierge system is a small footprint OSGi-compliant Java core that would run that code.
On the component level, Eclipse Kura deserves a very honourable mention in the very long list of projects that can simply be deployed in one own’s IoT solutions. Kura is an easy-to-use gateway system that acts between sensor devices and a backend. Traditionally used for demonstrations on a Raspberry Pi, Kura and Pi now almost always go together. Somewhat more complex and usually a foundation for home automation products such as openHAB, Eclipse SmartHome is being widely used by hobbyists and professionals alike because it offers bindings for commonly used hardware.
While it is always possible to drill into the actual code of all Eclipse projects (open source, sic!), both on the ecosystem and the component level one doesn’t necessarily have to engage with the nitty-gritty of the underlying code. However, as Eclipse IoT also embraces important standards, their libraries for M2M/IoT device communication via MQTT, CoAP or ETSI M2M are extremely powerful.
On the example of MQTT one can see the power of these open source solutions. Originally termed ‘MQ Telemetry Transport’, this common publish-subscribe IoT protocol is used to send information from devices to gateways to servers. A message is divided into a topic (like the subject of an email) and a payload (its body). MQTT sits on top of TCP/IP. While the Mosquitto broker (another Eclipse ‘component’) can simply be installed on most Unix systems and takes care of all of the message handling, the programmer only needs to memorize a few lines of syntax of e.g. the Paho library to connect to the broker or react to particular MQTT topics via callback functions.
A minimalistic response on the basis of the Paho Python example is shown here:
import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK. def on_connect(client, userdata, rc): print("Connected with result code "+str(rc)) client.subscribe("$TEMPERATURE/#") # subscribing to all topics startings with "TEMPERATURE" # The callback for when a PUBLISH message is received. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) # MAIN client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("iot.eclipse.org", 1883, 60) client.loop_forever()
At this stage Eclipse IoT still misses a project dedicated to visualization and analysis of IoT data. However, Eclipse has recently embraced the Open Analytics project and cross-fertilization to and from Eclipse IoT is hopefully just a question of time.
The figures in this article are all available on SlideShare.
Be the First to Comment! | https://jaxenter.com/a-simple-way-to-look-at-eclipse-iot-125477.html | CC-MAIN-2018-34 | refinedweb | 1,057 | 51.48 |
ToolData Highlight Objects on Hover? [SOLVED]
On 26/02/2015 at 13:05, xxxxxxxx wrote:
Hey Guys,
Is it possible to highlight objects on hover w/ a Python ToolData plugin? Basically I'm looking to add the behavior you see in the Move/Scale/Rotate/Select tools where the edges of objects light up when you hover over them so that you know which object you're going to select.
I've overloaded the Draw method to return c4d.TOOLDRAW_HIGHLIGHTS, but it doesn't have any impact.
def Draw(self, doc, data, bd, bh, bt, flags) : """Draw highlights for the object under the cursor.""" return c4d.TOOLDRAW_HANDLES | c4d.TOOLDRAW_AXIS | c4d.TOOLDRAW_HIGHLIGHTS
Any suggestions?
Thanks!
Donovan
On 27/02/2015 at 08:23, xxxxxxxx wrote:
Hello,
GetCursorInfo() is called every time the mouse is moved. You could check there if there is an object under the cursor. Then you could use the BIT_HIGHLIGHT bit of an object to make it highlighted in the viewport. Don't forget to delete this bit for objects no longer selected. The BIT_HIGHLIGHT is marked as private so it's behavior may change in the future and only limited support can be given.
Best wishes,
Sebastian
On 27/02/2015 at 11:50, xxxxxxxx wrote:
@Sebastian - thanks for that! Is this a different behavior from the C++ SDK? It seems like it handles it automatically in the PickTool example file.
For anyone that's trying to get object highlighting to work in their ToolData plugin, just drop in these methods:
def MouseToView(self, mouse_x, mouse_y, width, height) : """Clips mouse_x & mouse_y to view dimensions view_x, view_y = self.MouseToView(mouse_x, mouse_y, width, height)""" if (mouse_x is None) or (mouse_y is None) : return None, None view_x = int(mouse_x) if view_x > width: view_x = width view_y = int(mouse_y) if view_y > height: view_y = height return view_x, view_y def GetViewData(self, bd) : """Retrieve helpful view information. frame, left, right, top, bottom, width, height = self.GetViewData(bd) """ if bd is None: return None, None, None, None, None, None, None #Get View Data frame = bd.GetFrame() left = frame["cl"] right = frame["cr"] top = frame["ct"] bottom = frame["cb"] width = right - left + 1 height = bottom - top + 1 return frame, left, right, top, bottom, width, height def GetObjectUnderCursor(self, bd, doc, x, y, rad=2) : """Return the object under the cursor. Limitation: Only works w/ OGL turned on""" frame, left, right, top, bottom, width, height = self.GetViewData(bd) view_x, view_y = self.MouseToView(x, y, width, height) nearest_objects = c4d.utils.ViewportSelect().PickObject(bd, doc, view_x, view_y, rad=rad, flags=c4d.VIEWPORT_PICK_FLAGS_OGL_ONLY_TOPMOST_WITH_OBJ) if nearest_objects: return nearest_objects[0] return None def Draw(self, doc, data, bd, bh, bt, flags) : """Ensure the highlighting is active.""" return c4d.TOOLDRAW_HIGHLIGHTS def GetCursorInfo(self, doc, data, bd, x, y, bc) : """Highlight the objects under the cursor.""" hover_obj = self.GetObjectUnderCursor(bd, doc, x, y) #They're the same object or None, so no need to update highlighting if self.last_hover == hover_obj: return True #Clear out the highlighting on the old objects if self.last_hover is not None: if self.last_hover.IsAlive() : self.last_hover.DelBit(c4d.BIT_HIGHLIGHT) self.last_hover = None #Highlight the object under the cursor, and store it for later comparison if (hover_obj is not None) and hover_obj.IsAlive() : self.last_hover = hover_obj hover_obj.SetBit(c4d.BIT_HIGHLIGHT) #Update the views. c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_ANIMATION) return True
On 02/03/2015 at 00:35, xxxxxxxx wrote:
Hello,
do you mean the PickObjectTool plugin? This plugin is not based on ToolData but on DescriptionToolData.
best wishes,
Sebastian
On 03/03/2015 at 12:28, xxxxxxxx wrote:
That's the one, I suppose that would explain the difference in behavior. I wish we had access to the DescriptionToolData class in Python.
Thanks,
Donovan | https://plugincafe.maxon.net/topic/8539/11148_tooldata-highlight-objects-on-hover-solved/3 | CC-MAIN-2020-40 | refinedweb | 618 | 64.91 |
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 2.0-beta-2
-
- Component/s: XML Processing
- Labels:None
- Number of attachments :
Description
XmlSlurper and XmlParser both support a validation capability, but this only works for DTDs. It should work for XMLSchemas as well.
Activity
So basically we currently have this for validating against internal XSDs:
def factory = SAXParserFactory.newInstance() factory.validating = true factory.namespaceAware = true SAXParser sax = factory.newSAXParser() sax.setProperty("", XMLConstants.W3C_XML_SCHEMA_NS_URI) def parser = new XmlParser(sax)
which could be shortened to something like:
def parser = new XmlParser(XmlUtil.defaultSchemaValidatingParser())
Incidentally, we still need an error handler in either case:
parser.errorHandler = { e -> println e.message } as ErrorHandler
For validating against an external XSD we currently have:("mySchema.xsd")] as Source[]) def parser = new XmlParser(factory.newSAXParser())
which might become something like this:
def parser = new XmlParser(XmlUtil.schemaValidatingParserFromSources(new StreamSource("mySchema.xsd")))
With DTD validation off, this doesn't need a special error handler - the default one when not validating just sends error messages to System.err.
Or we could provide a Map style constructor:
def parser = new XmlParser(validating: true, schemaValidation: true, schemaSources:[new StreamSource("mySchema.xsd")])
Or something like that - though it won't necessarily support easy IDE completion.
I did indeed mean that using an XML Schema should be easier. The above proposal seem to take us on the right direction. Without trying the out, it is difficult to say more.
Why does there have to be explicit mention of an error handler?
What about folks using Relax NG?
I didn't have to specify an error handler using the first segment, it just worked.
Re: "I didn't have to specify an error handler using the first segment, it just worked."
If I have validating set to true I get the warning to stderr you mentioned on the mailing list:
Warning: validation was turned on but an org.xml.sax.ErrorHandler was not set, which is probably not what is desired. Parser will use a default ErrorHandler to print the first 10 errors. Please call the 'setErrorHandler' method to fix this.
If you are not seeing it perhaps it is JVM version specific.
For relaxng, with Jing in my classpath I needed the following as the long-hand for an external schema source (couldn't get the internal one working in the time I had available):
// Jing jar doesn't seem to have META-INF to be found automatically by JAXP // so manually set it here - pick one of compact or xml syntax variants System.setProperty(SchemaFactory.name + ":" + RELAXNG_NS_URI, // "com.thaiopensource.relaxng.jaxp.CompactSyntaxSchemaFactory") "com.thaiopensource.relaxng.jaxp.XMLSyntaxSchemaFactory") SchemaFactory schemaFactory = SchemaFactory.newInstance(RELAXNG_NS_URI) def factory = SAXParserFactory.newInstance() factory.validating = false factory.namespaceAware = true factory.schema = schemaFactory.newSchema([new StreamSource("mySchema.rng")] as Source[]) def parser = new XmlParser(factory.newSAXParser())
so perhaps this could become:
// I'd propose leaving the ugly System.setProperty here as it is Jing specific // and hopefully will go away in future versions of the library anyway def parser = new XmlParser(XmlUtil.schemaValidatingParserFromSources(RELAXNG_NS_URI, new StreamSource("mySchema.rng")))
and if we don't default to XML Schema, then the earlier example for XML Schema might need to become:
def parser = new XmlParser(XmlUtil.schemaValidatingParserFromSources(W3C_XML_SCHEMA_NS_URI, new StreamSource("mySchema.xsd")))
"If you are not seeing it perhaps it is JVM version specific."
I see the error message when I set the validate parameter true in the XmlParser constructor call but I don't have a DTD. When I use the SAX parser constructor to XmlParser I do not see the error message. This would imply the error message comes from the default DTD validating SAX parser used by XmlParser. Since this is not used when specifying a given SAX parser the default error handler is clearly fine?
I agree with the thinking about support for RelaxNG except that there should be a way of allowing the incoming document to specify the schema against which validation happens.
@Russel
Re: "the default error handler is clearly fine". Yes, when creating your own SAX parser, if you don't tell it to also validate against DTDs - which you don't need to in your examples from what you have said, then the default is fine AFAIK.
Re: "there should be a way of allowing the incoming document to specify the schema against which validation happens". Agreed! But I haven't found anything definitive on how to do this long hand in Java - hence providing a Groovy shorthand currently evades me.
An example with imports etc. in case anyone is trying to actually run the snippets above:
import javax.xml.transform.Source import javax.xml.transform.stream.StreamSource import javax.xml.validation.SchemaFactory import javax.xml.XMLConstants import javax.xml.parsers.SAXParserFactory def xml_g = '<person><first>James</first><last>Kirk</last></person>' def xml_b = '<person><first>James</first><middle>T.</middle><last>Kirk</last></person>' def xsd = '''<xs:schema xmlns: <xs:element <xs:complexType> <xs:sequence> <xs:element <xs:element </xs:sequence> </xs:complexType> </xs:element> </xs:schema>'''(new StringReader(xsd))] as Source[]) def parser = new XmlParser(factory.newSAXParser()) [xml_g, xml_b].each { def p = parser.parseText(it) println "${p.last.text()}, ${p.first.text()}" }
Here is what I propose to add to XmlUtil:
public static SAXParser schemaParser(String schemaLanguage, boolean namespaceAware, boolean validating, File schema) public static SAXParser schemaParser(String schemaLanguage, boolean namespaceAware, boolean validating, URL schema) public static SAXParser schemaParser(String schemaLanguage, boolean namespaceAware, boolean validating, Source... schemas)
So, the above example becomes (assuming the xsd is in a local file called 'person.xsd'):
import static javax.xml.XMLConstants.* import static groovy.xml.XmlUtil.* def xml_g = '<person><first>James</first><last>Kirk</last></person>' def xml_b = '<person><first>James</first><middle>T.</middle><last>Kirk</last></person>' def parser = new XmlParser(schemaParser(W3C_XML_SCHEMA_NS_URI, true, false, 'person.xsd' as File)) [xml_g, xml_b].each { def p = parser.parseText(it) println "${p.last.text()}, ${p.first.text()}" }
I guess we could also create variants with default values for the booleans - I'd go with validating=false and namespaceAware=true as per our defaults for XmlSlurper and XmlParser.
We could also have a default schema language but (despite the poor support for RelaxNG on the JVM at present) I am inclined not to at this stage - it can always be added later.
There is also the question of the best name for the utility methods. I have used "schemaParser" above but perhaps "newSAXParser" is better.
And also the question of whether it is worth back-porting to 1.8.7? It doesn't alter any existing API, so I don't see the harm. It depends on how kind we want to be to stragglers in the Groovy ecosystem.
added as newSAXParser with and w/o boolean variants and backported to 1.8.7
On the one hand I am a huge fan of debug releases, i.e. changes in the z of the x.y.z, only having bug fixes. On the other hand this could be considered a bug fix – and Groovy does have a history of slipping in some new bits as bug fixes. So as long as there are no breaking changes 1.8.6 -> 1.8.7 I am content to see this stuff in.
I wonder if "validatingParser" rather than "schemaParser" would be more descriptive.
I guess we still need to work on a validating parser that reads the schema specification from the root node rather than being given it separately.
Re: the name: I ended up going with "newSAXParser" which is a little lower level than I would normally like but with a view to making it obvious that you are producing something which feeds into the SAXParser constructor of XmlParser/Slurper. I didn't go with "validatingParser" since you could create one with the (DTD) validating flag set to false and that might be counter-intuitive at first glance. And if the eventual goal is to have a higher-level API over the top, then all of this would be hidden anyway.
Re: autodetecting the schema language: yes, that would be much nicer. It should really be fixed at the JVM-library level but if that looks unlikely to happen any time soon, Groovy could try to value add in the meantime.
Example of usage can be seen in XmlUtilTest#testSchemaValidationUtilityMethod:
The test doesn't use a file which looks neater but on the other hand, the test is self-contained.
Just a note that:
XMLConstants
but:
XmlUtils
the inconsistency really is annoying.
It seems that the default behaviour of XmlUtil.newSAXParser is not to validate even though it is required to provide a schema. Or have I missed something?
XmlParser reports trimWhitespace as the property to set to control whitespace, it has the wrong default of true. XmlParser reports keepWhitespace as the property to control whitespace, it has the wrong default of false.
Re: XMLConstants vs XmlUtils: XMLConstants, SAXParser, SQLException etc. come from Java. XmlParser, XmlSlurper, XmlUtil, JsonBuilder, Sql, etc. come from Groovy. Not nice but there has been a history behind both - unfortunate that sometimes the Java apis leak through to the Groovy ones. I guess in theory we could always hide them but ...
Re: default behaviour is to not validate: yes, the defaults are the same as for XmlSlurper and XmlParser and that flag is related to DTD validation only. Schema validation will be on. Perhaps the doco needs a bit of finessing to make that clearer?
Re: trimWhitespace vs keepWhitespace: it turns out the XmlSlurper's keepWhitespace and XmlParser's trimWhitespace are totally different beasts/concepts!
Firstly, XmlParser's trimWhitespace: it causes ".trim()" to be called on element text values (but not attributes!). It really does have the wrong default value but would break legacy code if we changed it. I would nearly support changing it anyway as a breaking change in 2.0. But given that we want to put a new api over the top (and potentially rework some of the internals) do we break user's code once or twice? It is well documented and easy to turn off - so the current thinking is to leave it until we make the api changes - but feel free to debate further - though it isn't really part of this issue per say.
Secondly, XmlSlurper's keepWhitespace: this is about preserving layout of XML documents. So if we have this XML fragment:
... <foo>content</foo> <bar>content</bar> ...
when the flag is off, parsing this will return two elements, "foo" and "bar". When the flag is on, this will return a "foo" element, then a "text node" containing a newline and 4 spaces, then the "bar" element. If you want to process the document content, the "whitespace text nodes" are just unwanted noise. But if you want to preserve the original layout of the document after making some changes to the content, then keeping the flag on can be useful. From memory, XmlSlurper may not allow full round-tripping anyway as it may not keep everything intact, e.g. processing instructions, XML comments etc. (but I haven't checked the code just now so don't quote me on this - we have made it cover more of these things over time)
Re: XMLConstants vs XmlUtils: I think the Groovy naming is inconsistent with the policy for Groovy properties where getXMLThingy ( ) goes to XMLThingy in order to preserve the upper caseness. No matter the history, it would be good for Groovy to have a consistent approach to acronym case.
Re validation. I found that using the two parameter newSAXParser (note not newSaxParser, see above
I did not get any XML Schema validation, I had to switch it on by using the four parameter version.
Re XmlParser's trimWhiteSpace: I suggest that the default is wrong and that Groovy 2 should have the right default. Legacy code should expect breaking changes 1.8 -> 2.0. Perhaps take this back to the mailing list to get wider debate?
Re XmlSlurper keepWhitespace: It seems that the use case you are explaining has little to do with the one we started with – unless I am missing something. Is it that XmlSlurper is using the same flag for multiple disjoint purposes? If so then a new flag should be introduced to cover the second case.
If XmlSlurper cannot round-trip then isn't it broken?
Re XmlSlurper keepWhitespace and XmlParser trimWhitespace: yes, they are totally different use cases with totally different flags that unfortunately overlap by 10 common characters. Perhaps they should have different names (breaking change): preserveWhitespace, autoTrimElementText
Re newSAXParser vs newSaxParser: SAXParser is a Java class that leaks through the Groovy api. When thinking of Groovy as value add to Java, I don't mind these differences too much. If you want to treat Groovy as a Java replacement then such differences are annoying. Don't think the getXMLThingy is relevant since xmlThingy would be the property for XmlThingy?
Re flipping trimWhitespace default: feel free to continue debate in user mailing list - if there is unanimous support I will be happy to help implement the change - if there is a wide divergence of opinion, I don't have heaps of time at present to contribute to persuading the masses - what little time I do have I'd prefer to invest in a future XML module with quite a few things fixed. But agree with you that the current default is very anti common practice.
Re two param vs four param newSAXParser: does XmlUtilTest#testSchemaValidationUtilityMethod work for you? It uses the two param version and seems to work?
Russel, does XmlUtilTest#testSchemaValidationUtilityMethod not work for you? Or did you reopen this in relation to the keepWhitespace / trimWhitespace issue? I guess it is working for me with the test cases I have so I am looking for another example. Thanks.
Russel, I have lost track of what else you require for this issue to be closed? Can you remember?
I am going to mark this as closed as I believe the Schema Validation part has been adequately addressed. If we need to tweak other defaults, we should use a fresh issue to create more focus around any required changes/discussion.
They both do support XML Schema validation. So for clarification, my understanding is that you want simpler configuration when turning on such validation rather than configuring your own SAXParser. | http://jira.codehaus.org/browse/GROOVY-5361?focusedCommentId=293996&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-14 | refinedweb | 2,391 | 56.76 |
This week I set out to create a chrome extension and utilise JavaScript and React to inject a component into a website. The result is a beautiful combination of Mutation Observers and JavaScript goodness!
The code can be found on Github
Lets get ready!
To start, I downloaded a starter for a chrome extension from the Chrome Developer website. If you want to learn the basics of extension development, I definitely recommend looking at the website. I immediately deleted the
options.js,
options.html, and
popup.js files. In the
manifest.json file I removed the
options_page key as well as the
storage value from the
permissions array. Next, you want to add to the
permissions array.
I will be referencing myweekinjs a few times, this could be any website that you wish to inject a React component into.
Next, I created an
app.js with a simple
console.log to test that the script works, and updated the
background.js to;
chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([{ conditions: [new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostEquals: '', schemes: ['https', 'http'], pathContains: 'inject-me' }, css: ['div'] })], actions: [ new chrome.declarativeContent.RequestContentScript({ js: ['app.js'] }) ] }]); }); });
Alright! That was a lot! The
background.js script will do the following;
- Listen for page/tab changes
- Check if the current page is (http|https)://
- If it is, it will load our
app.jsfile
Follow these steps to load your extension for testing purposes.
Let's get scripting!
Next step is to create our
webpack.config.js file to compile our React and Javascript. At this point, I'd recommend creating a dist folder with the current files (minus the
app.js), and unpacking that folder as our extension. This way you can compile into this dist folder and won't include your node_modules into the extension.
We'll use this awesome resource to generate our webpack and .babelrc files createapp.dev
- Open the resource ^
- Check React, Babel. Uncheck React hot loader
- Run
npm init -yand install the packages outlined by the resource
- Copy the
webpack.config.jsand
.babelrcfiles into your project
- Copy the
scriptsfrom the
package.json
There are a couple of small tweaks that we need to make. For the
webpack.config.js change the entry and output settings;
var config = { entry: './app.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'app.js' }, ... }
Change the
build-dev script to;
"dev": "webpack -d --mode development --watch"
You might have some syntax issues with the
.babelrc, they should be easy to fix though, mainly issues about using double quotes.
Running the
build-prod script will compile the
app.js file. After a unpack and reload, you should be greeted with the same
console.log as before. A long process to get where we were, but now things get interesting!
Let's get appy!
We want our app to do a few things;
- Wait for the page to load completely
- Watch for mutations on a target container
- Insert our React root
- Render a React component
We'll start with the following structure. It adds a listener to the window on
load and contains our main callback function which I called app.
window.addEventListener('load', function() {}) const app = () => {}
Step 1 is done! Onwards!
Next, we'll be adding a Mutation Observer which gives us the superpower to watch for changes in the DOM tree. It is pretty sweet. For our project, we are going to be observing the
target-test div on our test page. The following code is added to the load callback.
// Specifies the element we want to watch const watch = document.getElementById('target-test') // Creates a new Mutation Observer const observer = new MutationObserver((mutationList, observer) => { }) // Starts observing the child list of the element observer.observe(watch, { childList: true })
Next, we want to loop through the mutations and call our app method if we can find the element we are looking for.
const observer = new MutationObserver((mutationList, observer) => { // Loops through the mutations for (const mutation of mutationList) { // Checks if it is a change to the child elements if (mutation.type === 'childList') { // Attempts to find the p tag const target = watch.querySelector('p') if (target) { // Calls our app method app(observer, target) } } } }) // Update the callback to accept those arguements const app = (observer, target) => {}
Almost there! Now we want to create a root for our React component and insert it before our target element.
const app = (observer, target) => { // Disconnects from the observer to stop any additional watching observer.disconnect() // Checks if the element doesn't exist if (!document.getElementById('react-root-test')) { // Create and inserts the element before the target const parent = target.parentNode const root = document.createElement('div') root.setAttribute('id', 'react-root-test') parent.insertBefore(root, target) } }
Lets get reacting!
Now that we have our React root we can finally create and render our component. I will just be creating a simple React component in the same file. However, you can create any component you choose to, it is up to you! Once you've added your component, unpack your extension and reload the test page and you should see the component appear!
import React from 'react' import ReactDOM from 'react-dom' const TestComponent = () => ( <h1>I am dynamically added!</h1> ) const app = () => { //... parent.insertBefore(root, target) ReactDOM.render(<TestComponent />, document.getElementById('react-root-test')) }
BOOM!
We did it! This is only scratching the surface of what you are able to do with chrome extensions and using React. Using the same technique, you'll be able to add features to websites. Similar to extensions like Grammarly or LastPass. The possibilities are almost endless!
Wrapping up
This was a pretty cool project I think. I definitely didn't think something like this was possible with chrome extensions. Using the Mutation Observer for this example may be overkill. However, when you encounter a website that dynamically renders content, being able to wait until the content you need is ready is super cool! If you have any questions about the code or process please reach out to me over Twitter, I'd love to keep talking about this and improving my code. | https://www.myweekinjs.com/chrome-extension-with-react/ | CC-MAIN-2019-35 | refinedweb | 1,019 | 60.01 |
_lwp_cond_reltimedwait(2)
- remove a directory
#include <unistd.h> int rmdir(const char *path);
The rmdir() function removes the directory named by the path name pointed to by path. The directory must not have any entries other than “.” and “..”.
If the directory's link count becomes zero and no process has the directory open, the space occupied by the directory is freed and the directory is no longer accessible. If one or more processes have the directory open when the last link is removed, the “.” and “..” entries, if present, are removed before rmdir() returns and no new entries may be created in the directory, but the directory is not removed until all references to the directory have been closed.
Upon successful completion rmdir() marks for update the st_ctime and st_mtime fields of the parent directory.
Upon successful completion, 0 is returned. Otherwise, -1 is returned, errno is set to indicate the error, and the named directory is not changed.
The rmdir() function will fail if:
Search permission is denied for a component of the path prefix and {PRIV_FILE_DAC_SEARCH} is not asserted in the effective set of the calling process
Write permission is denied on the directory containing the directory to be removed and {PRIV_FILE_DAC_WRITE} is not asserted.
The parent directory has the S_ISVTX variable set, is not owned by the user, and {PRIV_FILE_OWNER} is not asserted.
The directory is not owned by the user and is not writable by the user.) | http://docs.oracle.com/cd/E19963-01/html/821-1463/rmdir-2.html | CC-MAIN-2014-35 | refinedweb | 240 | 51.48 |
On 23/08/11 16:35, Radoslav Husar wrote:
> Hi guys,
>
> is there any documentation (or examples) for the sf-xml components? I
> haven't found anything helpful :-/
>
>
>
-Sorry for not replying; I've been on vacation and the others on the
team don't seem to be replying either. Sorry.
No, there's not much there, is there?
I use it primarily as a way of distributing versions of the main XML
libraries for other components: xmlapis+ xerces, xalan, jdom, xom
The SF components inside were stuff I wrote to work with Xom and
generate XML Content. There is a test example of it
#include "org/smartfrog/services/xml/components.sf"
/**
* test a document
*/
rootDoc extends XmlDocument {
root extends XmlElement {
textElement ROOT:textElement;
}
}
textElement extends XmlTextNode {
text "this is a nested text element";
}
sfConfig extends rootDoc ;
This isn't that useful. Looking in the code there is a set of attributes
which support XML-namespaced qnames, and after building up a tree of
them can be saved to an XML file, or, by the look of things, sent over
the wire. I don't see anything there to load an XML document, though it
looks the kind of thing that I'd do next.
The last big stuff I did with XML in SF was working with the "Alpine"
SOAP stack, but even that was using Xom, rather than XML-in-SF; I think
it depended on sf-xml just for the dependencies and maybe some helper
methods.
XML should match fairly easily to the SF language, but in practise it
doesn't for some reasons you will soon recognise if you spend too much
time in XML-land
-XML namespaces and the notion of a qualified name on elements and
attributes.
-the difference between nested elements and simple attributes
-the way you can have multiple text elements directly under a node
with nested elements in between them.
JSON is a far more compatible format, and where we've been drifting to
in our use of things recently.
If you really want to work with the sf-xml stuff then you can talk to me
and we'll see how to improve things - I do think Xom is the best way to
work with XML in Java, whereas the DOM APIs are probably the worst. That
said, now we've been doing a fair bit of Groovy work that would be even
better as I'd be able to inject new methods into every XML node without
having to worry about which XML node factory it came from.
-steve
Hi guys,
is there any documentation (or examples) for the sf-xml components? I
haven't found anything helpful :-/
Cheers,
Radoslav Husar
JBoss QE
Czech Republic | http://sourceforge.net/p/smartfrog/mailman/message/28022725/ | CC-MAIN-2016-07 | refinedweb | 456 | 61.4 |
Hello everyone,
Is there a way to schedule a map service to restart at 5 a.m. in ArcGIS server.
Is there a way to do it in ArcGIS Server?
Thank you
Hello everyone,
Is there a way to schedule a map service to restart at 5 a.m. in ArcGIS server.
Is there a way to do it in ArcGIS Server?
Thank you
Example: Stop or start all services in a folder—ArcGIS Server Administration (Windows) | ArcGIS Enterprise
You'll make a Python script to stop/start the services you want and then schedule that Python script to run at your desired time with Windows Task Scheduler.
Blake:
Have you used this script yourself to stop/start services? If so, do you use the port 6080 http protocol as shown in the sample script? Or have you successfully modified the script to use port 6443 https protocol?
I have been using the port 6080 http protocol for 1.5 years but recently I have encountered token fetching errors which I have not been able to resolve so I am trying to use the port 6443 https protocol but that is throwing different errors. I was able to get the port 6080 http protocol to work with Fiddler (It acts as a forward proxy), but that is not a permanent solution as it is a security risk to have Fiddler always running.
This is the script we use to stop and start a geocode service. I think it is basically a cut and past of an esri one. We are using http and 6080:
"""
Stop or start ArcGIS Server geocode service
"""
# Required imports
import urllib
import urllib2
import json
import contextlib ## context manager to clean up resources when exiting a 'with' block
def get_token(adminUser, adminPass, server, port, expiration):
"""
Function to generate a token from ArcGIS Server; returns token.
:param adminUser: admin user
:param adminPass: admin password
:param server: AGS name, e.g. ceav456
:param port: server port
:param expiration: token timeout
:return:
"""
#))
# Function to start or stop a service on ArcGIS Server; returns JSON response.
##
def service_start_stop(server, port, svc, action, token):
"""
Function to start or stop a service on ArcGIS Server; returns JSON response.
:param server: AGS name, e.g. ceav456
:param port: server port
:param svc: service name, folder, and type
:param action: start or stop service
:param token: server token
:return: json response
"""
#())
def service_control(ags, action):
"""
Control server services
:param ags: AGS (ArcGIS Server)
:param action: start or stop
:return: result string
"""
# Local variables
# Authentication
adminUser = r"siteadmin"
adminPass = r"sit3mngr!"
# ArcGIS Server Machine
server = ags
port = "6080"
# Services ("FolderName/ServiceName.ServiceType")
svc = "Locators/CW_Composite.GeocodeServer"
# Get ArcGIS Server token
expiration = 60 ## Token timeout in minutes; default is 60 minutes.
token = get_token(adminUser, adminPass, server, port, expiration)
# Perform action on service
jsonOuput = service_start_stop(server, port, svc, action, token)
## Validate JSON object result
if jsonOuput['status'] == "success":
result = "{} {} successful on server {}".format(action.title(), str(svc), server)
else:
result = "Failed to {} {}".format(action, str(svc))
return result
raise Exception(jsonOuput)
return result
We have ArcGIS Web Adaptor configured on the server and use an .ags connection file pointed to the web adaptor on http. You should be able to do it all with https as long as your certificates are all valid.
Edit:
That is actually for just publishing a geocode service that overwrites the existing service so it doesn't directly relate to your question about starting and stopping services. Here are the basic steps:
not sure about scheduling a specific service but you can schedule the arcgis Server process to restart at a specific time | https://community.esri.com/thread/216589-how-to-chedule-a-map-service-to-restart-at-5-am-in-arcgis-server | CC-MAIN-2020-29 | refinedweb | 601 | 52.7 |
Offline installation for Machine Learning Server for Windows
Applies to: Machine Learning Server 9.2.1 | 9.3 | 9.4
By.
Before you start, review the following article for requirements and general information about setup: Install Machine Learning Server on Windows.
9.4.7 Downloads
On an internet-connected computer, download all of the following files.
Note
If you are performing offline installation using the Python script
Install-PyForMLS.ps1, then after you download
SPO_4.5.12.0_1033.cab, rename the file to
SPO_9.4.7.0_1033.cab. The installation script expects this filename.
9.3.0 Downloads
On an internet-connected computer, download all of the following files.
9.2.1 Downloads
If you require the previous version, use these links instead.
Transfer and place files
Use a tool or device to transfer the files to the offline server.
- Put the unzipped en_machine_learning_server_for_windows_x64_
.zipfile in a convenient folder.
- Right-click Extract All to unpack the file. You should see a folder named MLS93Win. This folder contains ServerSetup.exe.
- Put the CAB files in the setup user's temp folder: C:\Users<user-name>\AppData\Local\Temp.
Tip
On the offline server, run
ServerSetup.exe /offline from the command line to get links for the .cab files used during installation. The list of .cab files appears in the installation wizard, after you select which components to install.
Run setup
After files are placed, use the wizard or run setup from the command line:
Check log files
If there are errors during Setup, check the log files located in the system temp directory. An easy way to get there is typing
%temp% as a Run command or search operation in Windows. If you installed all components, your log file list looks similar to this screenshot:
Set environment variables
Create.
Connect and validate
Machine Learning Server executes on demand as R Server or as a Python application. As a verification step, connect to each application and run a script or function.
For R
R Server runs as a background process, as Microsoft ML Server Engine in Task Manager. Server startup occurs when a client application like Rgui.exe connects to the server.
- Go to C:\Program Files\Microsoft\ML Server\R_SERVER\bin\x64.
- Double-click Rgui.exe to start the R Console application.
- At the command line, type
search()to show preloaded objects, including the
RevoScaleRpackage.
- Type
print(Revo.version)to show the software version.
- Type
rxSummary(~., iris)to return summary statistics on the built-in iris sample dataset. The
rxSummaryfunction is from
RevoScaleR.
For Python
Python runs when you execute a .py script or run commands in a Python console window.
Go to C:\Program Files\Microsoft\ML Server\PYTHON_SERVER.
Double-click Python.exe.
At the command line, type
help()to open interactive help.
Type
revoscalepyat the help prompt, followed by
microsoftmlto print the function list for each module.
Paste in the following revoscalepy script to return summary statistics from the built-in AirlineDemo demo data:
import os import revoscalepy sample_data_path = revoscalepy.RxOptions.get_option("sampleDataDir") ds = revoscalepy.RxXdfData(os.path.join(sample_data_path, "AirlineDemoSmall.xdf")) summary = revoscalepy.rx_summary("ArrDelay+DayOfWeek", ds) print(summary)
Output from the sample dataset should look similar to the following:
Summary Statistics Results for: ArrDelay+DayOfWeek File name: /opt/microsoft/mlserver/9.4.0/libraries/PythonServer/revoscalepy/data/sample_data/AirlineDemoSmall.xdf Number of valid observations: 600000.0 Name Mean StdDev Min Max ValidObs MissingObs 0 ArrDelay 11.317935 40.688536 -86.0 1490.0 582628.0 17372.0 Category Counts for DayOfWeek Number of categories: 7 Counts DayOfWeek 1 97975.0 2 77725.0 3 78875.0 4 81304.0 5 82987.0 6 86159.0 7 94975.0
Verify CLI
Note
Before you continue, reboot the machine.
Open an Administrator command prompt.
Enter the following command to check availability of the CLI:
az ml admin --help. If you receive the following error:
az: error argument _command_package: invalid choice: ml, follow the instructions to re-add the extension to the CLI.
Next steps
We recommend starting with any Quickstart tutorial listed in the contents pane. | https://docs.microsoft.com/ja-jp/machine-learning-server/install/machine-learning-server-windows-offline | CC-MAIN-2020-45 | refinedweb | 677 | 52.87 |
Now suppose you also need a class for a motorcycle. A motorcycle also has a make, a model, a year, a speed, a maximum speed, a weight, a price, a number of passengers it can carry, two wheels and many other properties you can represent with fields. A class that represents a motorcycle might look like this:
public class Motorcycle { private String licensePlate; // e.g. "New York A456 324" private double speed; // kilometers per hour private double maxSpeed; // kilometers per hour private String make; // e.g. "Harley-Davidson" private String model; // e.g. "panhead" private int year; // e.g. 1997, 1998, 1999, 2000, 2001, etc. private int numberPassengers; // e.g. 4 private int numberWheels = 2; // all motorcycles have two wheels // constructors public Motorcycle(String licensePlate, double maxSpeed, String make, String model, int year, int numberOfPassengers) { this(licensePlate, maxSpeed, make, model, year, numberOfPassengers); } public Motorcycle(String licensePlate, double speed, double maxSpeed, String make, String model, int year, int numberOfPassengers) { this(licensePlate, speed, maxSpeed, make, model, year, numberOfPassengers); } public Motorcycle(String licensePlate, double speed, double maxSpeed, String make, String model, int year, int numberOfPassengers) { // I could add some more constraints like the // number of doors being positive but I won't // so that this example doesn't get too big. this.licensePlate = licensePlate; this.make = make; this.model = model; this.year = year; this.numberPassengers = numberOfPassengers; if (maxSpeed >= 0.0) { this.maxSpeed = maxSpeed; } else { maxSpeed = 0.0; } if (speed < 0.0) { speed = 0.0; } if (speed <= maxSpeed) { this.speed = speed; } else { this.speed = maxSpeed; } } // getter (accessor) methods public String getLicensePlate() { return this.licensePlate; } public String getMake() { return this.make; } public String getModel() { return this.model; } public int getYear() { return this.year; } public int getNumberOfPassengers() { return this.numberPassengers; } public int getNumberOfPassengers() { return this.numberWheels; } public double getMaxSpeed() { return this.maxSpeed; } public double getSpeed() { return this.speed; } // setter method for the license plate property public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } // accelerate to maximum speed // put the pedal to the metal public void floorIt() { this.speed = this.maxSpeed; } public void accelerate(double deltaV) { this.speed = this.speed + deltaV; if (this.speed > this.maxSpeed) { this.speed = this.maxSpeed; } if (this.speed < 0.0) { this.speed = 0.0; } } }
There's a lot of overlap between the class definitions for
Car and
Motorcycle. In fact the only things
that are different are the constructors and a few of the fields.
Inheritance takes advantage of the overlap. | http://www.cafeaulait.org/course/week4/05.html | CC-MAIN-2017-51 | refinedweb | 399 | 52.87 |
Interlocks¶
Until now, we assumed that a master can run builds at any slave whenever needed or desired. Some times, you want to enforce additional constraints on builds. For reasons like limited network bandwidth, old slave machines, or a self-willed data base server, you may want to limit the number of builds (or build steps) that can access a resource. (upto some fixed number) in counting mode, or they allow one build in exclusive mode.
Note
Access modes are specified when a lock is used. That is, it is possible to have a single lock that is used by several slaves in counting mode, and several slaves in exclusive mode. In fact, this is the strength of the modes: accessing a lock in exclusive mode will prevent all counting-mode accesses.
Count¶
Often, not all slaves are equal. To allow for this situation, Buildbot allows to have a separate upper limit on the count for each slave. In this way, you can have at most 3 concurrent builds at a fast slave, 2 at a slightly older slave, and 1 at all other slaves.
Scope¶
The final thing you can specify when you introduce a new lock is its scope. Some constraints are global -- they must be enforced over all slaves. Other constraints are local to each slave. A master lock is used for the global constraints. You can ensure for example that at most one build (of all builds running at all slaves) accesses the data base server. With a slave lock you can add a limit local to each slave. With such a lock, you can for example enforce an upper limit to the number of active builds at a slave, like above.
Examples¶
Time for a few examples. Below a master lock is defined to protect a data base, and a slave lock is created to limit the number of builds at each slave.
from buildbot import locks db_lock = locks.MasterLock("database") build_lock = locks.SlaveLock("slave_builds", maxCount = 1, maxCountForSlave = { 'fast': 3, 'new': 2 })
After importing locks from buildbot, db_lock is defined to be a master lock. The database string is used for uniquely identifying the lock. At the next line, a slave lock called build_lock is created. It is identified by the slave_builds string. Since the requirements of the lock are a bit more complicated, two optional arguments are also specified. The maxCount parameter sets the default limit for builds in counting mode to 1. For the slave called 'fast' however, we want to have at most three builds, and for the slave "shared".
A build or build step proceeds only when it has acquired all locks. If a build or step needs a lot of locks, it may be starved [3] by other builds that need fewer locks.
To illustrate use of locks, a few examples.
from buildbot import locks from buildbot.steps import source, shell from buildbot.process import factory db_lock = locks.MasterLock("database") build_lock = locks.SlaveLock("slave_builds", maxCount = 1, maxCountForSlave = { 'fast': 3, 'new': 2 }) f = factory.BuildFactory() f.addStep(source.SVN(svnurl="")) f.addStep(shell.ShellCommand(command="make all")) f.addStep(shell.ShellCommand(command="make test", locks=[db_lock.access('exclusive')])) b1 = {'name': 'full1', 'slavename': 'fast', 'builddir': 'f1', 'factory': f, 'locks': [build_lock.access('counting')] } b2 = {'name': 'full2', 'slavename': 'new', 'builddir': 'f2', 'factory': f, 'locks': [build_lock.access('counting')] } b3 = {'name': 'full3', 'slavename': 'old', 'builddir': 'f3', 'factory': f, 'locks': [build_lock.access('counting')] } b4 = {'name': 'full4', 'slavename': 'other', 'builddir': 'f4', 'factory': f, 'locks': [build_lock.access('counting')] } c['builders'] = [b1, b2, b3, b4]
Here we have four slaves b1, b2, b3, and b4. Each slave performs the same checkout, make, and test build step sequence. We want to enforce that at most one test step is executed between all slaves due to restrictions with the data base server. This is done by adding the locks= parameter with the third step. It takes a list of locks with their access mode. In this case only the db_lock is needed. The exclusive access mode is used to ensure there is at most one slave that executes the test step.
In addition to exclusive accessing the data base, we also want slaves to stay responsive even under the load of a large number of builds being triggered. For this purpose, the slave. | http://docs.buildbot.net/0.8.5/manual/cfg-interlocks.html | CC-MAIN-2017-43 | refinedweb | 711 | 75 |
Node.js: How even quick async functions can block the Event-Loop, starve I/O
Yet another article about the Node.js Event-Loop
Intro:
I recently stumbled upon a real event-loop blocking scenario here at Snyk. When I tried to fix the situation, I realized how little I actually knew about the event-loop behavior and gained some realizations that at first surprised me and some fellow developers I shared this with. I believe it’s important that as many Node developers will have this knowledge too — which led me to writing this article.
Plenty of valuable information already exists about the subject, but it took me time find the answers for the specific questions I wanted to ask. I’ll do my best to share the various questions I had, and share the answers I’ve found in various great articles, some fun experimentation and digging.
First, let’s block the Event-Loop!
Note:
- Examples below use Node 10.9.0 on an Ubuntu 18.04 VM with 4 cores, running on a MacBook Pro 2017
- You can play with the code bellow by cloning
So let’s start with a simple Express server:
const express = require('express'); const PID = process.pid; function log(msg) { console.log(`[${PID}]` ,new Date(), msg); } const app = express(); app.get('/healthcheck', function healthcheck(req, res) { log('they check my health'); res.send('all good!\n') }); const PORT = process.env.PORT || 1337; let server = app.listen(PORT, () => log('server listening on :' + PORT));
and now let’s add a nasty event-loop blocking endpoint:
const crypto = require('crypto'); function randomString() { return crypto.randomBytes(100).toString('hex'); } app.get('/compute-sync', function computeSync(req, res) { log('computing sync!'); const hash = crypto.createHash('sha256'); for (let i=0; i < 10e6; i++) { hash.update(randomString()) } res.send(hash.digest('hex') + '\n'); });
So we expect, that during the operation of the
/compute-sync endpoint, requests to
/healthcheck will stall. We can probe the
/healthcheck with this
bash one-liner:
while true; do date && curl -m 5 && echo; sleep 1; done
It will probe the
/healthcheck endpoint every second and timeout if it gets no response in 5 seconds.
Let’s try it:
The moment we called the
/compute-sync endpoint, the health-checks started to timeout and not a single one succeeded. Note that the
node process is working hard at ~100% CPU.
After 43.2 seconds the computation is over, 8 pending
/healthcheck requests go through and the server is responsive again.
This situation is pretty bad — one nasty request blocks the server completely. Given the “single thread event loop” knowledge, it’s obvious why the code in
/compute-sync blocked all other requests: before it completed it didn’t give the control back to the event-loop scheduler so there was no chance for the
/healthcheck handler to run.
Let’s unblock it!
Let’s add a new endpoint
/compute-async where we’ll partition the long blocking loop by yielding the control back to the event-loop after every computation step (too much context switching? maybe… we can optimize later and yield only once every X iterations, but let’s start simple):
app.get('/compute-async', async function computeAsync(req, res) { log('computing async!'); const hash = crypto.createHash('sha256'); const asyncUpdate = async () => hash.update(randomString()); for (let i = 0; i < 10e6; i++) { await asyncUpdate(); } res.send(hash.digest('hex') + '\n'); });
Let’s try:
🤔 hmm …. it still blocks the event-loop?
What’s going on here? Does Node.js optimizes-away our toy use of
async/await here? It took few more seconds to complete, so doesn’t seem so… Flame-graphs can give a hint if
asyncwas actually in-affect. We can use the cool project to generate flame-graphs easily:
First, the flame-graph captured while running
/compute-sync:
flame-graph captured while running /compute-sync
We can see that
/compute-sync stack includes the express handler stack, as it was 100% synchronous.
Now, the flame-graph captured while running
/compute-async:
flame-graph captured while running
/compute-async
The
/compute-async flame-graph on the other-hand looks very different, running in the context of V8’s
RunMicrotask &
AsyncFunctionAwaitResolveClosure functions. So no … doesn’t seem like the
async/await was “optimized away”.
Before digging deeper, let’s try one last desperate thing us developers sometimes do: add a sleep call!
app.get('/compute-with-set-timeout', async function computeWSetTimeout (req, res) { log('computing async with setTimeout!'); function setTimeoutPromise(delay) { return new Promise((resolve) => { setTimeout(() => resolve(), delay); }); } const hash = crypto.createHash('sha256'); for (let i = 0; i < 10e6; i++) { hash.update(randomString()); await setTimeoutPromise(0); } log('done ' + req.url); res.send(hash.digest('hex') + '\n'); });
Let’s run it:
Finally, the server remains responsive during the heavy computation 🎉 . Unfortunately, the cost of this solution is too high: we can see that the CPU is at about ~10%, so it seems it doesn’t work hard enough on the computation, which practically takes forever to complete (didn’t have enough patience to see it happen 😅). Only by reducing the number of iterations from 10⁷ to 10⁵, it completed after 2:23 minutes! (If you wonder, passing 1, instead of 0, as the delay parameter to
setTimeout makes no difference — more on this later)
This raises several questions:
- why was the
asynccode blocked without the
setTimeout()call?
- why did the
setTimeout()add such a massive performance cost?
- how can we unblock our computation without such a penalty?
Event-Loop Phases
When something similar happened to me, I turned to Google for answers. Looking for stuff like “node async block event loop” one of the first results is this official Node.js guide:. It really opened my eyes.
It explains that the event-loop is not the magic scheduler I imaged it to be, but a pretty straight-forward loop with several phases in it. Here is a nice ASCII diagram of the main phases, copied from the guide:
Diagram from
(later I’ve found that this loop is nicely implemented in
libuv with functions named as in the diagram:)
The guide explains about the different phases, and gives the following overview:
* timers: this phase executes callbacks scheduled by
setTimeout()and
setInterval().
* pending callbacks: executes I/O callbacks deferred to the next loop iteration.
* idle, prepare: only used internally.
* poll: retrieve new I/O events; execute I/O related callbacks.
* check:
setImmediate()callbacks are invoked here.
* close callbacks: some close callbacks, e.g.
socket.on('close', ...).
What starts to answer our question is this quote:
“generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase’s queue until the queue has been exhausted … Since any of these operations may schedule more operations …”.
This (vaguely) suggests that when a callback enqueues another callback that can be handled in the same phase, then it will be handled before moving to the next phase.
Only in the
poll phase Node.js checks the network socket for new requests. So does that mean that what we did in
/compute-async actually prevented the event-loop from leaving a certain phase, and thus never looping through the
poll phase to even receive the
/healthcheck request?
We’ll need to dig more to get better answers, but it is definitely clear now why
setTimeout() helped: Every time we enqueue a timer callback, and the queue of the current phase has been exhausted, the event-loop has to loop through all the phases to reach the “Timers” phase, passing through the
poll phase on the way, and handling the pending network requests.
👋 Micro-Tasks
The
async/await keywords we used in
/compute-async are known to be a syntactic sugar around
Promises, so what actually happens there is that in every loop iteration we create a
Promise (which is an asynchronous operation) to compute a hash, and when it’s resolved, our loop continues to the next iteration. The mentioned official guide doesn’t explain how
Promises are handled in the context of the event-loop phases, but our experiments suggest that both the
Promise callback and the
resolve callback were invoked without looping through the
poll phase.
With some more Google-ing, I’ve found a more detailed and very well written 5-article series about the event loop by Deepal Jayasekara, with information about Promises handling as well! 🙏:
It contains this useful diagram:
Diagram from
The boxes around the circle illustrate the queues of the different phases we seen before, and the two boxes in the middle illustrate two special queues that need to be exhausted before moving from one phase to the other. The “next tick queue” processes callbacks registered via
nextTick(), and the “Other Micro Tasks queue” is the answer to our question about Promises.
And as in our case, if a resolved Promise creates another Promise, will it be handled in the same phase before moving to the next one? The answer, as we saw, is yes! How this happens can be seen in V8’s source: . This link points to the implementation of
RunMicrotask() . Here is a snippet of the implementation with the relevant lines:
TF_BUILTIN(RunMicrotasks, InternalBuiltinsAssembler) { ... Label init_queue_loop(this); Goto(&init_queue_loop); BIND(&init_queue_loop); { TVARIABLE(IntPtrT, index, IntPtrConstant(0)); Label loop(this, &index), loop_next(this); TNode num_tasks = GetPendingMicrotaskCount(microtask_queue); ReturnIf(IntPtrEqual(num_tasks, IntPtrConstant(0)), UndefinedConstant()); ... Goto(&loop); BIND(&loop); { ... index = IntPtrAdd(index.value(), IntPtrConstant(1)); ... BIND(&is_callable); { ... Node* const result = CallJS(...); ... Goto(&loop_next); } BIND(&is_callback); { ... Node* const result = CallRuntime(Runtime::kRunMicrotaskCallback, ...); Goto(&loop_next); } BIND(&is_promise_resolve_thenable_job); { ... Node* const result = CallBuiltin(Builtins::kPromiseResolveThenableJob, ...); ... Goto(&loop_next); } BIND(&is_promise_fulfill_reaction_job); { ... Node* const result = CallBuiltin(Builtins::kPromiseFulfillReactionJob, ...); ... Goto(&loop_next); } BIND(&is_promise_reject_reaction_job); { ... Node* const result = CallBuiltin(Builtins::kPromiseRejectReactionJob, ...); ... Goto(&loop_next); } ... BIND(&loop_next); Branch(IntPtrLessThan(index.value(), num_tasks), &loop, &init_queue_loop); } } }
This C code looks weird and does loops via magic & low-level
Goto() and
Branch() functions/macros, because it’s written using V8’s “CodeStubAssembly” which is a “a custom, platform-agnostic assembler that provides low-level primitives as a thin abstraction over assembly” (explained in).
We can see in the gist that there is an outer loop labeled
init_queue_loop and an inner one labeled
loop. The outer loop checks the actual number of pending micro-tasks, then the inner loop handles all the tasks one by one, and once done, as seen on line 62 in the gist above, it iterates the outer loop, which checks again the actual number of pending micro-tasks, and only if nothing new was added the function returns.
If you want to see how the handling of micro-tasks happens at the end of every event-loop phase, I recommend you follow another great article by Deepal Jayasekara:
(b.t.w, remember the flame-graph we created for
/compute-async? If you’ll scroll up to look again, you will recognize the
RunMicrotasks() in the stack)
Also note, that Micro-Tasks is a V8 thing, so it’s relevant to Chrome as-well, where Promises are handled the same way — without spinning the browser event-loop.
nextTick() won’t tick
The Node.js guide says:
callbacks passed to
process.nextTick()will be resolved before the event loop continues. This can create some bad situations because it allows you to “starve” your I/O by making recursive
process.nextTick()calls
This time it’s pretty clear from the text so I’ll spare you another terminal screenshot, but you can play with it by doing
GET /compute-with-next-tick in.
The
nextTick queue is processed here:
function _tickCallback() { ... do { while (tock = queue.shift()) { ... Reflect.apply(callback, undefined, tock.args); ... } runMicrotasks(); } while (!queue.isEmpty() || emitPromiseRejectionWarnings()); ... }
It’s clear that if
callback calls another
process.nextTick(), the loop will process the next callback in the same loop, and break only once the
nextTick queue is empty.
setImmediate() to the rescue?
So, Promises are red, Timers are blue — what else can we do?
Looking at the diagrams above, both mention the
setImmediate() queue that is processed during the “check” phase, right after the “poll” phase. The official Node.js guide also says:
setImmediate()and
setTimeout()are similar, but behave in different ways depending on when they are called …
The main advantage to using
setImmediate()over
setTimeout()is
setImmediate()will always be executed before any timers if scheduled within an I/O cycle, independently of how many timers are present.
Sounds good, but the most promising quote from there is:
If the poll phase becomes idle and scripts have been queued with
setImmediate(), the event loop may continue to the check phase rather than waiting.
Do you remember that when we used
setTimeout(), the process was mostly idle (i.e. waiting), using ~10% CPU? let’s see if
setImmediate() will solve this:
app.get('/compute-with-set-immediate', async function computeWSetImmediate(req, res) { log('computing async with setImmidiate!'); function setImmediatePromise() { return new Promise((resolve) => { setImmediate(() => resolve()); }); } const hash = crypto.createHash('sha256'); for (let i = 0; i < 10e6; i++) { hash.update(randomString()); await setImmediatePromise() } res.send(hash.digest('hex') + '\n'); });
Yay! It doesn’t block the server and the CPU is at 100% 🎉! Let’s see how much time it takes to complete:
Well, nice. it completed in 1:07 minutes, about 50% longer then
/compute-sync and 34% longer than
/compute-async — but it’s usable, unlike
/compute-with-set-timeout. Given the fact it’s a toy example, where we used
setImmediate() in every one of the 10⁷ tiny iterations, which probably resulted in 10⁷ full event-loop spins, this slowdown is quite understandable. So scheduling a
setImmediate() from a
setImmediate() callback doesn’t cause it to remain in the same phase? Yep, the Node.js documentation clearly says in:
If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration
When comparing
setImmediate() to
process.nextTick(), the Node.js guide says:
We recommend developers use
setImmediate()in all cases…
You’ve been spoiled already with code references, so to not disappoint, I believe this is the actual code that executes the
setImmediate() callbacks: b.t.w: a nice fact mentioned in Part 3 of Deepal’s series (), is that the
Bluebird, a popular non-native-
Promise library uses
setImmediate() to schedule Promise callbacks.
Closing thoughts
(Almost, as a bonus section about
setTimeout() follows) So,
setImmediate() seems to be a working solution for partitioning long-running synchronous code. But it’s not always easy to do and do right. There is obviously an overhead in each yield to
setImmediate() , and the more requests are pending, the longer it will take to the long-running task to complete — so partitioning your code too much is problematic, and doing it too little can block for too long. In some cases the blocking code is not a simple loop like in our example, but rather a recursion that traverses a complex structure and it becomes more tricky to find the right place and condition to yield. A possible idea for some cases it to keep track of how much time is spent blocking before yielding to
setImmediate(). This snippet will yield only if at-least 10ms passed since last yielding:
... let blockingSince = Date.now() async function crazyRecursion() { ... if (blockingSince + 10 > Date.now()) { await setImmediatePromise(); blockingSince = Date.now(); } ... }
In other cases a 3rd-party code you have less control over might block — even builtin functions like
JSON.parse() can block.
A more extreme solution is to offload potentially blocking code to a different (non Node.js) service, or to sub-processes (via packages like tiny-worker) or actual threads via packages like webworker-threads or the (still experimental) built-in. In many cases, this is the right solution, but all these offloading solutions come also with the hurdle of passing serialized data back and forth as the offloaded code can’t access the context of the main (and only) JS thread.
A common challenge with all these solutions is that the responsibility to avoid blocking is in the hands of every developer, rather than being the responsibility of the OS, like in most threaded languages or the responsibility of the run-time VM, like in Erlang. Not only it’s hard to make sure all developers are always aware of this, many times it’s also not optimal to yield explicitly via the code, which lacks the context and visibility of what happens with other pending routines and IO.
The high-throughput that Node.js enables, if used not carefully, can cause many pending requests waiting in-line due to a single blocking operation. To signal the load-balancer as quickly as possible that a server has a long list of lagging requests, and make it route requests to different nodes, you can try using packages such as toobusy-js in your health-check endpoints (this won’t help during the actual blocking…). It’s also important to monitor the event-loop in run-time via packages like blocked-at or solutions like N|Solid and New-Relic.
Bonus: Why the 0 in setTimeout(0) is not really 0
I was really curious why
setTimeout(0) had made the process 90% idle instead of crunching our computation. Idle CPU probably means that
node‘s main thread invoked a system-call that caused it to suspend it’s execution (i.e. sleep) for long enough before being scheduled by the kernel to continue, which hints at our
setTimeout().
Reading
libuv‘s source around handling of timers, it seems that the actual “sleep” happens in
uv__io_poll(), as part of
poll() syscall via it’s
timeout parameter:.
poll()‘s man-page says:
The
timeoutargument specifies the number of milliseconds that poll() should block waiting for a file descriptor to become ready… specifying a negative value
in
timeoutmeans an infinite timeout. specifying a
timeoutof zero causes poll() to return immediately.
So, unless the timeout is exactly 0, the process will sleep. We suspect that despite passing 0 to
setTimeout() the actual timeout passed to
poll() is higher. We can try to validate that by debugging
node itself via
gdb.
We can trace all calls to
uv__io_poll() by using
gdb‘s
dprintf command:
dprintf uv__io_poll, "uv__io_poll(timeout=%d)\n", timeout
let’s also print the current time every trace:
dprintf uv__io_poll, "%d: uv__io_poll(timeout=%d)\n", loop->time, timeout
When our server starts,
uv__io_poll() is called with a timeout of
-1, which means “infinite timeout” — as it has nothing to do except waiting for an HTTP request. Now let’s
GET the
/compute-with-set-timeout endpoint:
As we can see, the timeout is sometimes 1, and also when it’s 0, usually at-least 1 ms passes between two consecutive calls. Debugging the same way while
GET-ing
/compute-with-set-immediate will always show
timeout=0.
For a CPU, 1 millisecond is quite a long time. The tight loop at
/compute-sync completed 10⁷ iterations in 43 seconds, which means it did ~233 random hash computations every millisecond. Waiting for 1ms on every iteration means waiting 10,000 seconds = 2:45 hours!
Lets’s try to understand why the timeout that is passed to
uv__io_poll() isn’t 0. The timeout is computed in
uv_backend_timeout() an then passed to
uv__io_poll() as can be seen in the main
libuv loop:. For some cases (such as pending active handles or requests)
uv_backend_timeout() returns 0, otherwise it returns the result of
uv__next_timeout() which picks the nearest timeout from the “timer heap” and returns the remaining time to it’s expiry.
The function that is used to add the “timeouts” to the “timer heap” is
uv_timer_start(). This function is called in many places, so we can try to set a breakpoint on it to better locate the caller that passes a non-zero value in our case. Running the
info stack command in GDB at the breakpoint gives:
#0 uv_timer_start (handle=0x2504cb0, cb=0x97c610 <node::(anonymous namespace)::TimerWrap::OnTimeout(uv_timer_s*)>, timeout=0x1, repeat=0x0) at ../deps/uv/src/timer.c:77 #1 0x000000000097c540 in node::(anonymous namespace)::TimerWrap::Start(v8::FunctionCallbackInfo<v8::Value> const&) () #2 0x0000000000b5996f in) () #3 0x0000000000b5a4d9 in v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) () #4 0x00003cc0e2fdc01d in ?? () #5 0x00003cc0e3005ada in ?? () #6 0x00003cc0e2fdbf81 in ?? () #7 0x00007fffffff8140 in ?? () #8 0x0000000000000006 in ?? () ... (more nonsense addresses)
TimerWrap::Start is just a thin wrapper around
uv_timer_start() and the unrecognizable addresses up the stack indicate that the actual code we look for is probably implemented in JavaScript. By either looking for uses of
TimerWrap:Start in Node’s source or by simply “stepping into” the implementation of
setTimeout() from the JS side via a JS debugger, we can quickly locate the
Timeout constructor at:
function Timeout(callback, after, args, isRepeat, isUnrefed) { after *= 1; // coalesce to number or NaN if (!(after >= 1 && after <= TIMEOUT_MAX)) { if (after > TIMEOUT_MAX) { process.emitWarning(`${after} does not fit into a 32-bit signed integer. Timeout duration was set to 1.', 'TimeoutOverflowWarning'`); } after = 1; // schedule on next tick, follows browser behavior } ... }
Finally, here☝️ we see that a timeout of 0 is coalesced to 1 🙀.
Hope you found this article useful. Thanks for reading.
References:
-
- (5 article series)
-
-
- (also vendored in nodejs/node)
- (also vendored in nodejs/node)
More reading on the subject:
-
-
-
-
-
-
-
-
- — browsers
-
-
-
-
-
- | https://snyk.io/blog/nodejs-how-even-quick-async-functions-can-block-the-event-loop-starve-io/ | CC-MAIN-2020-10 | refinedweb | 3,540 | 53.81 |
Add this to your package's pubspec.yaml file:
dependencies: tw_saved_search_angular: "^0.0.1"
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:tw_saved_search_angular/tw_saved_search_angular.dart';
We analyzed this package, and provided a score, details, and suggestions below.
Detected platforms: unsure
Error(s) prevent platform classification.
Fix dependencies in
pubspec.yaml.
Running
pub upgradefailed with the following output:
ERR: Could not resolve URL "".
Fix platform conflicts.
Make sure none of the libraries use mutually exclusive dependendencies.
Maintain
README.md.
Readme should inform others about your project, what it does, and how they can use it._saved_search_angular.dart. | https://pub.dartlang.org/packages/tw_saved_search_angular | CC-MAIN-2018-09 | refinedweb | 126 | 53.37 |
Scale Python GPU code to distributed systems and your laptop.
High-Performance Python – Distributed Python
As the last few articles have pointed out, Python is becoming an important language in HPC and is arguably the most important language in data science. The previous three articles have covered tools for improving the performance of Python with C, Fortran, and GPUs on a single node.
In this article, I present tools for scaling Python GPU code to distributed systems. Some of the tools are Python variations of classic HPC tools, such as MPI for Python (mpi4py), a Python binding to the Message Passing Interface (MPI). Tools such as Dask focus on keeping code Pythonic, and other tools support the best performance possible.
MPI for Python
The HPC world has been using MPI since the early 1990s. In the beginning, it was used almost exclusively with C/C++ and Fortran. Over time, versions of MPI or MPI bindings were released for other languages such as Java, C#, Matlab, OCaml, R, and, of course, Python. MPI was used because it is the standard in the HPC world for exchanging data between processes on shared or distributed architectures. Python is arguably the number one language for Deep Learning and is very popular in Machine Learning and HPC. Combining the two seemed like a natural step toward improving Python performance, while making code writing for science and engineering similar to the current language and tools already in use.
MPI for Python (mpi4py) was developed for Python by using the C++ bindings on the MPI-2 standard. It has been designed to be fairly Pythonic, so if you know Python and understand the basic concepts of MPI, mpi4py shouldn't be a problem. I am a self-admitted Fortran coder and using mpi4py, even though it is based on the C++ MPI bindings, is no more difficult than with Fortran. In fact, I think it's a bit easier, because Python has data structures that can be used to create complex data structures and objects. To pass these structures between MPI ranks, Python serializes the data structures using pickle, with both ASCII and binary formats supported. Python can also use the marshal module to serialize built-in objects into a binary format specific to Python.
Mpi4py takes advantage of Python features to maximize the performance of serializing and de-serializing objects as part of data transmission. These efforts have been taken to the point that the mpi4py documentation claims these features enable "… the implementation of many algorithms involving multidimensional numeric arrays (e.g., image processing, Fast Fourier Transforms, finite difference schemes on structured Cartesian grids) directly in Python, with negligible overhead, and almost as fast as compiled Fortran, C, or C++ codes."
Mpi4py has all of the communications and functions that you expect from MPI:
- Blocking and non-blocking send/receive
- Collective communications
- Scatter/gather
- Dynamic process management (MPI-2 standard)
- One-sided communications
- Parallel input/output: (MPI.File class)
- Initialization
- Timers
- Error handling
All of these are accomplished very Pythonically but, at the heart, are still MPI.
mpi4py Example
Running mpi4py code is about the same as running classic C/Fortran code with MPI. For example, using Open MPI, the command for running MPI code would be,
$ mpiexec -n 4 python script.py
where script.py is the Python code. Depending on how Python is installed or built on your system, you might have to define the fully qualified path to the Python executable itself, the script, or both. Here is a quick example of a Hello World mpi4py code.
from __future__ import print_function from mpi4py import MPI comm = MPI.COMM_WORLD print("Hello! I'm rank %d from %d running in total..." % (comm.rank, comm.size)) comm.Barrier() # wait for everybody to synchronize _here_
It looks like a classic MPI program that has been "pythonized." A second example from an mpi4py tutorial illustrates how to communicative NumPy arrays using MPI:)
Don't forget that mpi4py will serialize the data when passing it to other ranks, but the good news is that it works very hard to make this as efficient as possible. The third and last example is a simple broadcast (bcast) of a Python dictionary:
from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0: data = {'key1' : [7, 2.72, 2+3j], 'key2' : ( 'abc', 'xyz')} else: data = None #endif data = comm.bcast(data, root=0)
I threw in my Fortran habit of putting in a comment to mark the end of an if/then/else statement or loop (sometimes the indentation gets a little crazy).
UCX
HPC developers, which can include MPI developers and HPC system vendors, seem to create communication frameworks (communication middleware) for new concepts, which limits interoperability and means users have to "port" their applications to the frameworks if they switch software stacks. To reduce this problem, Unified Communication X (UCX) was created by a multivendor consortium. UCX is an "… open-source, product grade, communication framework focusing on data-centric and high performance applications." The goal of UCX is to provide the functionality needed for efficient high-performance communication, eliminating the need to "roll your own" and reducing the porting time when different software stacks are involved.
UCX has a set of interfaces to various libraries that support networks such as InfiniBand and NVLink. Many tools can be built on top of UCX taking advantage of the commonality of UCX as well as the performance and portability. For example, UCX is currently a framework used within Open MPI. You can also create bindings on top of UCX to provide fast, low-latency data communications for various networks. UCX has three parts to its framework: (1) UC-P for Protocols, (2) UC-T for Transport, and (3) UC-S for Services. UC-P is a high-level API that uses the UCT transport layer framework to construct common protocols and is useful for things such as multirail support, device selection, tag-matching, and so on. UC-T for Transport is a low-level API that exposes basic network operations used by the network hardware. Finally, UC-S for Services provides the infrastructure for component-based programming, memory management, and other services and is primarily used for platform abstractions, data structures, and so on. These APIs are used within UCX to achieve the goals of portability, high bandwidth, and low latency. | https://www.admin-magazine.com/HPC/Articles/High-Performance-Python-4/(tagID)/124 | CC-MAIN-2020-16 | refinedweb | 1,060 | 51.38 |
Introduction to Pandas Filter Rows
Pandas filter rows can be utilized as dataframe.isin() work. isin() function restores a dataframe of a boolean which when utilized with the first dataframe, channels pushes that comply with the channel measures. You can likewise utilize DataFrame.query() to sift through the lines that fulfill a given boolean articulation. Investigating information requires a great deal of sifting tasks. Pandas give numerous techniques to channel a Data casing and Dataframe.query() is one of them. query() technique possibly works if the segment name does not have any vacant spaces. So prior to applying the strategy, spaces in segment names are supplanted with ‘_’
Syntax and Parameters:
Dataframe.query(inplace=False, expr, **kwargs)
Where,
- Inplace represents the changes in the dataframe if it is true and hence by default it is false.
- Expression represents the string expression to filter data.
- It finally returns the filtered rows of the dataframe.
How to Filter Rows in Pandas?
Now we see various examples of how to filter rows in the Pandas dataframe.
Example #1: Filtering the rows in the dataframe by utilizing Dataframe.isin()
Code:
import pandas as pd
df = pd.DataFrame({'s': [1, 3, 7, 4], 'p': [4, 1, 8, 6]})
out = df['s'].isin(range(4,7))
filtered_df = df[out] print('Original DataFrame\n-------------------\n',df)
print('\nFiltered DataFrame\n-------------------\n',filtered_df)
Output:
In the above program, we first import the pandas library, and then we create the dataframe. After creating the dataframe, we assign values to the rows and columns and then utilize the isin() function to produce the filtered output of the dataframe. Finally, the rows of the dataframe are filtered and the output is as shown in the above snapshot.
Example #2: Filtering the rows of the Pandas dataframe by utilizing Dataframe.query()
Code:
import pandas as pd
df = pd.DataFrame({'s': [1, 3, 7, 4], 'p': [4, 1, 8, 6]})
filtered_df = df.query('p>7')
print('First DataFrame\n-------------------\n',df)
print('\nFiltered DataFrame\n-------------------\n',filtered_df)
Output:
Here, we first as seen previously we import the pandas library as pd and then define the dataframe. After creating the dataframe, we assign values to it and later we utilize the dataframe.query() function to produce the filtered dataframe. Thus, the program is implemented and the output is as shown in the above snapshot.
To start, I make a Python rundown of Booleans. I at that point compose a for circle which repeats over the Pandas Series (a Series is a solitary segment of the DataFrame). The Pandas Series, Species_name_blast_hit is an iterable item, much the same as a rundown. I at that point utilize a fundamental regex articulation in a contingent proclamation and attach either True if ‘bacterium’ was not in the Series esteem, or False if ‘bacterium’ was available. At the point when I print the initial 5 passages of my Boolean records, all the outcomes are True.
Perhaps the greatest bit of leeway of having the information as a Pandas Dataframe is that Pandas permits us to cut up the information in numerous manners. One approach to a channel by lines in Pandas is to utilize boolean articulation. We initially make a boolean variable by taking the segment of interest and checking if it’s worth equivalents to the particular worth that we need to choose/keep. We would then be able to utilize this boolean variable to channel the dataframe. Subsequent to subsetting we can see that the new dataframe is a lot more modest in size. In any case, we do not generally need to make another boolean variable and spare it to do the separating. All things considered, we can legitimately give the boolean articulation to subset the dataframe by section esteem.
We can likewise utilize Pandas binding activity, to get to a dataframe’s section and to choose lines like past model. Pandas tying makes it simple to join one Pandas order with another Pandas order or client characterized capacities. Now and then, you may need toddler to keep lines of an information outline dependent on estimations of a section that does not approach something. Pandas dataframe’s isin() work permits us to choose columns utilizing a rundown or any iterable. In the event that we use isin() with a solitary segment, it will just bring about a boolean variable with True if the worth matches and False in the event that it does not.
Conclusion
Hence, I would like to conclude by saying that it is a prerequisite to filter plain information dependent on section esteem. We might be given a Table and need to perform custom sifting activities. Luckily, we can utilize Pandas for this activity. Pandas is an open-source Python library for information investigation. It enables Python to work with accounting pages like information empowering quick document stacking and control among different capacities. Frequently, you may need to subset a pandas dataframe dependent on at least one estimations of a particular segment. Basically, we might want to choose lines dependent on one worth or different qualities present in a section.
Recommended Articles
This is a guide to Pandas Filter Rows. Here we also discuss the Introduction, syntax, parameters, and How to Filter Rows in Pandas? with example. You may also have a look at the following articles to learn more – | https://www.educba.com/pandas-filter-rows/?source=leftnav | CC-MAIN-2021-25 | refinedweb | 887 | 64.1 |
From: Nicola Musatti (nmusatti_at_[hidden])
Date: 2003-02-25 02:34:43
Beman Dawes wrote:> At 07:32 PM 2/24/2003,)
> >
>
> Go ahead and make the change, unless someone voices an objection.
I don't have a strong opinion in either direction, but I do feel that it
is important that this is thought over. Overloading checked_delete() on
purpose in a user defined namespace might be considered a way to provide
a smart pointer with a custom deleter. Is this really something bad?
Cheers,
Nicola Musatti
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/2003/02/44913.php | CC-MAIN-2021-10 | refinedweb | 109 | 76.42 |
"Size" field in "Details" tab should show KiB units
Bug Description
the "Installed-Size" field is measured in KiB, but the gdebi-gtk GUI presents it as an unadorned number.
(congratulations on having the correct behavior when the field is missing from the package, though. apt-get incorrectly claims the package is 0 KiB in that case, despite having the package available!)
Thanks for your bugreport and your patch.
I applied the patch to my bzr repository and it will be part of the next upload.
apt/Synaptic and the Installed-Size parameter of .deb files all measure in decimal (1000s of bytes), so "KiB" would be wrong. "KB" is also wrong, though. It should be "kB".
http://
patch:
=== modified file 'GDebi/GDebi.py'
--- GDebi/GDebi.py 2008-08-05 14:24:05 +0000
+++ GDebi/GDebi.py 2008-09-03 02:00:11 +0000
@@ -221,7 +221,7 @@
-.DetailsSiz
+ self.DetailsSiz
# set filelist
buf = self.IncFilesEdit
if that's true, the right fix isn't to pass APT's broken units on to the
user: the right fix is to convert kB into KiB, and display KiB. (the kB
figure's only approximate anyway. if they cared about accuracy, they'd
have given us B.)
something like this?
def kB_to_KiB(kB):
return '%i KB' % round(float(
--elliott
On Tue, September 2, 2008 19:07, Endolith wrote:
> apt/Synaptic and the Installed-Size parameter of .deb files all measure in
> decimal (1000s of bytes), so "KiB" would be wrong. "KB" is also wrong,
> though. It should be "kB".
>
> http://
> -Installed-Size
>
>
> patch:
>
>
>
> === modified file 'GDebi/GDebi.py'
> --- GDebi/GDebi.py 2008-08-05 14:24:05 +0000
> +++ GDebi/GDebi.py 2008-09-03 02:00:11 +0000
> @@ -221,7 +221,7 @@
> self.label_
> self.label_
> self.label_
>.DetailsMai
> self.DetailsPri
> self.DetailsSec
> self.DetailsSiz
> self.DetailsSiz
>
> # set filelist
> buf = self.IncFilesEdit
>
>
> ** Changed in: gdebi
> Status: Fix Released => Confirmed
>
>
> --
> "Size" field in "Details" tab should show KiB units
> https:/
> You received this bug notification because you are a direct subscriber
> of the bug.
>
--
Elliott Hughes, http://
"if that's true, the right fix isn't to pass APT's broken units on to the user"
No, apt's units are correct. .deb file units are correct too, and consistent with apt and derivatives, except that the symbol in GDebi should use lowercase k.
"the right fix is to convert kB into KiB, and display KiB."
No, KiB isn't appropriate for file sizes. Users expect to see thousands in this context. KiB is for things like memory and disk sectors that are inherently powers of two.
The Installed-Size value is in KiB, not in 1000s of bytes. Look at the source of dpkg-gencontrol. It uses du -k, which produces output in KiB. At the time that Debian Policy was originally written, "kilobyte" nearly universally meant kibibyte.
It should probably be changed to 1000s then, to match Apt, Synaptic, and the rest. If you download a package that Apt/Synaptic lists as "12.4 kB" download size, the actual .deb is 12.4 kB = 12.1 KiB. Synaptic then reports the installed size as "77.8 kB", while GDebi reports the installed size as "76 KB" (76 KiB = 77.8 kB).
5.6.20 Installed-Size
This field appears in the control files of binary packages, and in the Packages files. It gives the total amount of disk space required to install the named package.
The disk space is represented in kilobytes as a simple decimal number.
http://
It seems this number rarely matches the actual installed size, though. If you look at the total size of the installed files, it's often wildly off. Am I misunderstanding what it's for?
> At the time that Debian Policy was originally written, "kilobyte" nearly universally meant kibibyte.
I doubt that's true. Both the 1000 and 1024 meanings have been in common use for decades.
here's a patch:
--- /usr/lib/
python2. 3/site- packages/ GDebi/GDebi. py.orig 2006-05-11 17:19:56.000000000 -0700 python2. 3/site- packages/ GDebi/GDebi. py 2006-05-11 17:21:40.000000000 -0700
self. label_maintaine r.set_text( self._deb[ "Maintainer" ])
self. label_priority. set_text( self._deb[ "Priority" ])
self. label_section. set_text( self._deb[ "Section" ]) size.set_ text(self. _deb["Installed -Size"] ) size.set_ text(self. _deb["Installed -Size"] + " KB")
+++ /usr/lib/
@@ -184,7 +184,7 @@
- self.label_
+ self.label_
# set filelist
filelist. get_buffer( )
buf = self.textview_
i've used "KB" like Nautilus, rather than the "KiB" recommended by "man units".
--elliott | https://bugs.launchpad.net/gdebi/+bug/44286 | CC-MAIN-2016-18 | refinedweb | 756 | 70.19 |
Created on 2006-10-19 19:06 by djmitche, last changed 2007-10-18 03:17 by facundobatista.
I'm building an interface to Amazon's S3, using httplib. It uses a
single object for multiple transactions. What's happening is this:
HTTP > PUT /unitest-temp-1161039691 HTTP/1.1
HTTP > Date: Mon, 16 Oct 2006 23:01:32 GMT
HTTP > Authorization: AWS <<cough>>:KiTWRuq/
6aay0bI2J5DkE2TAWD0=
HTTP > (end headers)
HTTP < HTTP/1.1 200 OK
HTTP < content-length: 0
HTTP < x-amz-id-2: 40uQn0OCpTiFcX+LqjMuzG6NnufdUk/..
HTTP < server: AmazonS3
HTTP < x-amz-request-id: FF504E8FD1B86F8C
HTTP < location: /unitest-temp-1161039691
HTTP < date: Mon, 16 Oct 2006 23:01:33 GMT
HTTPConnection.__state before response.read: Idle
HTTPConnection.__response: closed? False length: 0
reading response
HTTPConnection.__state after response.read: Idle
HTTPConnection.__response: closed? False length: 0
..later in the same connection..
HTTPConnection.__state before putrequest: Idle
HTTPConnection.__response: closed? False length: 0
HTTP > DELETE /unitest-temp-1161039691 HTTP/1.1
HTTP > Date: Mon, 16 Oct 2006 23:01:33 GMT
HTTP > Authorization: AWS <<cough>>:
a5OizuLNwwV7eBUhha0B6rEJ+CQ=
HTTP > (end headers)
HTTPConnection.__state before getresponse: Request-sent
HTTPConnection.__response: closed? False length: 0
File "/usr/lib64/python2.4/httplib.py", line 856, in getresponse
raise ResponseNotReady()
If the first request does not precede it, the second request is fine.
To avoid excessive memory use, I'm calling request.read(16384)
repeatedly, instead of just calling request.read(). This seems to be
key to the problem -- if I omit the 'amt' argument to read(), then the
last line of the first request reads
HTTPConnection.__response: closed? True length: 0
and the later call to getresponse() doesn't raise ResponseNotReady.
Looking at the source for httplib.HTTPResponse.read, self.close() gets
called in the latter (working) case, but not in the former
(non-working). It would seem sensible to add 'if self.length == 0:
self.close()' to the end of that function (and, in fact, this change makes
the whole thing work), but this comment makes me hesitant:
# we do not use _safe_read() here because this may be a .will_close
# connection, and the user is reading more bytes than will be provided
# (for example, reading in 1k chunks)
I suspect that either (a) this is a bug or (b) the client is supposed to
either call read() with no arguments or calculate the proper inputs to
read(amt) based on the Content-Length header. If (b), I would think
the docs should be updated to reflect that?
Thanks for any assistance.
Logged In: YES
user_id=14198
The correct answer is indeed (b) - but note that httplib
will itself do the content-length magic for you, including
the correct handling of 'chunked' encoding. If the .length
attribute is not None, then that is exactly how many bytes
you should read. If .length is None, then either chunked
encoding is used (in which case you can call read() with a
fixed size until it returns an empty string), or no
content-length was supplied (which can be treated the same
as chunked, but the connection will close at the end.
Checking ob.will_close can give you some insight into that.
Its not reasonable to add 'if self.length==0: self.close()'
- it is perfectly valid to have a zero byte response within
a keep-alive connection - we don't want to force a new
(expensive) connection to the server just because a zero
byte response was requested.
The HTTP semantics are hard to get your head around, but I
believe httplib gets it right, and a ResponseNotReady
exception in particular points at an error in the code
attempting to use the library. Working with connections
that keep alive is tricky - you just jump through hoops to
ensure you maintain the state of the httplib object
correctly - in general, that means you must *always* consume
the entire response (even if it is zero bytes) before
attempting to begin a new request. This requirement doesn't
exists for connections that close - if you fail to read the
entire response it can be thrown away as the next request
will happen on a new connection.
Logged In: YES
user_id=7446
Excellent -- the first paragraph, where you talk about the .length attribute, makes things quite clear, so I agree that (b) is the correct solution: include the content of that
paragraph in the documentation. Thanks!
I disagree with mhammond. Mark is correct that closing the connection would be wrong, but self.close() in the function in question does *not* close the connection. Client code is not expected to explicitly call HTTPResponse.read() with an explicit amt argument even when persistent connections are involved. All that's required is (of course) that you have to read to the end of the current response before you get to read the next response on that connection.
I think Dustin is more or less right in his diagnosis, but I haven't written a patch yet...
with facundo we were tracking this bug down. mhammond is right about
that read() should allow 0 size responses, but the bug is that the
response is "not closed". HTTPResponse.read() says:
if amt is None:
# unbounded read
if self.length is None:
s = self.fp.read()
else:
s = self._safe_read(self.length)
self.length = 0
self.close() # we read everything
return s
see that if self.close()s, which really closes the fp created with
makefile() in the constructor. this does not closes the underlying
socket, as you can see trying this short example:
import httplib
c= httplib.HTTPConnection ('', 80)
c.request ('GET', '/index.html')
a1= c.getresponse ()
data1= a1.read()
c.request ('GET', '/404.html')
a2= c.getresponse ()
data2= a2.read()
and run it under strace -e network,file.
if the last part of read is changed to this, read(n) works just like
read() does:
#)
if len(s)==0:
self.close ()
return s
Mark is ok, zero length responses are ok. But that has nothing to do
with self.length.
self.lenght reaching zero means that everything that needed to be read
is already read. If the read() method is called without an argument, it
reads everything until it reaches self.lenght, and then it closes self.
So, when is called with an argument, is ok to close self if after
reading something self.length reaches zero (note that this actually
means that something was read, and self.length was lowered down...)
If self is closed also in this instance (see the patch), all tests pass
ok, and how you use HTTPConnection reading small pieces and not the
whole thing, is actually simplified...
Fixed in rev 58530 (also added a test case) | http://bugs.python.org/issue1580738 | crawl-002 | refinedweb | 1,107 | 75.4 |
This tutorial is a result of me growing tired of the privacynightmare that Google has become over the years. So, apart from rooting my lovely new Nokia 1 and deleting my Gmail account, I also wanted to get rid of googlemaps as a provider for the graphical illustrations of my biketravels.
If you google search on duckduckgo for "how to show gpx track on OSM", you will eventually end up at the openlayers website. There is an alternative that seems a bit more userfriendly called Leafletjs. But openlayers is totally into Node.js and I've been unthreaded-curious since I first heard about Node.js. So after ages of PHP-development I decided to seize the opportunity to get acquainted with Node for this map-gpx-project.
For this website I need a "slippy map" (a draggable map with zoomoptions) to show my GPX-tracks using different mapproviders. There's a tutorial at the openlayers site that assumes you do your developing on a linuxbox. I have one of those (as a filebackup/musicplayer) but for sentimental reasons I prefer my hacktool UltraEdit on windows 7 for development. There's a FreeBSD-testserver running on my homenetwork, so that's where I installed node and npm, the Node PackageManager, from the portscollection. The Libuv library is needed as a dependency and that's in the ports as well.
Stuff here was made with node v11.10.1, npm v6.8.0 and openlayers (OL) v5.3.0. I also assume you have something resembling a linuxbox at home and that you are a bit savvy concerning things *nix related.
I started out with this tutorial and followed up with the examples on openlayers.org. There have been some less- or undocumented pitfalls during this project, so I hope this may help other people on track leaving the alphabet holding.
On a *nix machine you need to create a directory with the name of your project. I used /home/osmgpx/public_html. When the source was built all files get prefixed with "public_html_", so you basically should mkdir /home/yourprojectname and cd to that directory and run all npm-commands from there to get a more sensible prefix.
When you run
npm init in this directory you get a load of questions. Fill out some sensible values and just hit enter when asked for the test-script. Next run
npm install ol to get the openlayer stuff and
npm install --save-dev parcel-bundler to get the parcel-bundler to automagically install dependencies needed when developing. If you're not running all this as root you should sudo every here and there.
Edit
package.json in your workingdirectory and make sure the scripts section looks like
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "parcel index.html", "build": "parcel build --public-url . index.html" },
Mind the comma after the
exit 1" -bit and at the end!
You also need an index.html and index.js in this directory. Here's the sourcecode for index.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Tutorial GPX on OSM using OpenLayers</title> <style> #map { width: 400px; height: 250px; } </style> </head> <body> <div id="map"></div> <script src="./index.js"></script> </body> </html>
For now an empty index.js is okay.
Next run
npm start from the prompt in the directory. Npm starts a webserver running at localhost on port 1234. Localhost is a definition for the machine that the browser is running on. If you're on Windows you can trick FiFo (but not Chrome) into thinking that localhost is running on some other server by editing the hosts file which typically sits at C:\Windows\System32\drivers\etc\hosts.
To refresh the lot after editing the index-files I did a Ctrl-C and a
npm start to restart the server to see the changes in the browser with F5. Npm is able to detect detects changes in the code by itself, but in my setup this did not work flawless. Npm checks for syntax errors when started, so check at the prompt when nothing is showing up in your browser.
When things go astray, there's clues in the console log of your browser (F12), but you probably knew that already.
In your index.html there's basically just a div with id=map and a link to the js-stuff. Not a lot is showing when you open, but in the sourcecode should be npm's index.html. The JS-file has a different name with the dirname as prefix in the source, but the (currently non-existemt) contents are read from index.js.
So let's do something about that. Open index.js in your favorite editor and add:
import 'ol/ol.css'; import {Map, View} from 'ol'; import OSM from 'ol/source/OSM.js'; import XYZ from 'ol/source/XYZ.js'; import GPX from 'ol/format/GPX.js'; import {defaults as defaultControls, FullScreen} from 'ol/control.js'; import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js'; import VectorSource from 'ol/source/Vector.js'; import {Stroke, Style} from 'ol/style.js';
These declarations tell which modules we'll be using in this project. We'll encounter them along the way. Note that at the prompt bundler.js is doing stuff if you save index.js.
The map instance goes next into index.js:
const map = new Map({ controls: defaultControls().extend([ new FullScreen() ]), target: 'map', layers: [], view: new View({ center: [0, 0], zoom: 0 }) });
There's some mapattributes here.
The default mapcontrols (zoom-in, zoom-out and information buttons) are extended by adding an icon to view the map in fullscreen, which is a really awesome feature (though not working properly in IE).
"Target" states de id of the div you want to show your map in.
"Layers" is an array that will be filled later.
The "view" sets the initial center and zoomlevel of the map. These values will be changed dynamically after loading the GPX file so the defaults will do. The total map of choice will be shown using these settings, until the trackdata has fully loaded. I didn't bother to change them.
If you change the centercoordinates, keep in mind that you may need the fromLonLat functionality (currently not imported at the top of this file) to transform the coordinates to prevent the map from centering at the coast of west Africa instead of Switzerland.
Zoomlevel 0 means totally zoomed out: you get a world map.
Next the layers need to be filled. There's 2 layers needed: one for the tiles of the map and another for the track. We start with some instances for the tiled maps:
var tileSource_oSTREETm = new OSM(); var tileSource_ArcGIS = new XYZ({//==>; esri sat attributions: '© <a href="">ArcGIS</a>', url: '{z}/{y}/{x}' });
There're two maps involved in our project, now stored in the vars
tileSource_oSTREETm and
tileSource_ArcGIS. OpenStreetMap is easy to get: just an instance of OSM.
Satellite-tiles from ArcGIS need the X, Y(- coordinates) and Z(oom) properties in the URL to return the appropriate piece of the puzzle, so that makes it an instance of XYZ. The url info states the location where the tiles originate from.
The attributions-option states the copyrights that are shown on the right lower corner of the map when the I-icon is clicked.
There is a ton of possible maps; have a look at the nice overview here. Just adjust the mentioned Leafletcodes to the OL format as demonstrated here with ArcGIS to use them. Thunderforest has some real nice maps, but you need a (free) apikey to show them in your hobbyproject.
That said and/or done we need to load this tile-data into the first map-layer:
map.addLayer(new TileLayer({ //==>; osm = default source: tileSource_oSTREETm }));
Save your index.js. If you restart the webserver with Ctrl-C and a
npm run. At the commandprompt npm imports all the necessary modules. Ignore the
Cannot read property 'type' of undefined warning and do an F5 in your browser and you should see the OSM worldmap at.
If not: reread or repeat the above steps!
When the map shows, it's time to add the GPX-track. Add this to index.js
var vectorSource = new VectorSource({ url: '', format: new GPX() });
to get the GPX data transformed into a vectorsource.
There's a caveat here. I put my gpx-file in the working directory with the index-files. In the examples at openlayers.org there's relative links in the url, so mine read
url: 'test.gpx'. That didn't work, and nor does ./test.gpx. So I put my GPX-track on the productionserver.
Then the next problem showed up. Loading external files in JS gives you a warning in the console (F12 in your browser): . It points to this page about Cross-Origin requests. To allow external files being read into JS applications elsewhere you need to adjust the .htaccess file on the productionserver by adding
Header set Access-Control-Allow-Origin "*". This basically tells that it's okay to send my tutorial GPX-file to JS-scripts hosted elsewhere requesting it.
Once the mapcode is on your productionserver, you can use relative url's again.
Apart from a URL there is also a style attached to the track. It has a name (Stroke),a color (RGB/HexDec/Named), a width (in pixels) and an opacity (float). We need two instances to pimp the maptrack: of Style and Stroke.
var vectorStyle = new Style({ stroke: new Stroke({ color: 'red', width: 3, opacity: 0.5 }) });
Next we have to add the source and style of the track to the layers:
map.addLayer(new VectorLayer({ source: vectorSource, style: vectorStyle }));
That's all we need to get the track on the map.
Save index.js and do a Ctrl-C and a
npm run at the command prompt and F5 your browser. You should see a worldmap with a tiny red blob somewhere in the Netherlands. Zoom in to find out where me, my bike and some other individuals (and their bikes) were on a sunday afternoon in 2014.
Next we like to scale the map to the gpx-vectorstroke. OL can do the calculating for you, but only after the track is loaded. I started out with a 3 Mb track that took some time to load. OL vectorsource has a method called getExtent(), but it returns some awkward values when called when the GPX-data is not or not yet present.
To get a fool-proof map, we're gonna check if the layers are alive and kicking. To find out we need this in index.js:
var layers = map.getLayers().getArray();
OL has a method
once, which basically listens for a certain type of event. We use "change" to find the state of the vectorSource.
Since we have all layers in an array we also check if layer[1] is actually filled.
Then we can call the getExtent-method to fit the trackpart of the map into the div:
vectorSource.once('change',function(e){ if(vectorSource.getState() === 'ready') { if(layers[1].getSource().getFeatures().length > 0) { map.getView().fit(vectorSource.getExtent()); } } });
Save your index.js file and do a Ctrl-C and a
npm run at the command prompt and a F5 in your browser. You should see this:
Since google has a satellite-option we wanna have one too! Add the following selectbox to index.html below the map-div and above the scriptsource:
<select name="tilesource" id="tilesource"> <option value='oSTREETm' selected="selected">OpenStreetMap</option> <option value='ArcGIS'>Satellite</option> </select>
Then we need to tell index.js to listen to what happens in the html-file. So let's get the element and add an event-listener. In between is the onChange-method that replaces the mapsource in layer[0] when another map gets chosen. Add this to your index.js:
var select = document.getElementById('tilesource'); function onChange() { var newMap = select.value; if(newMap) { var tileSource ='tileSource_' + newMap; var mapSource = eval(tileSource); var mapLayer0 = layers[0]; mapLayer0.setSource(mapSource); } } select.addEventListener('change', onChange);
Save your index.js file and do a Ctrl-C and a
npm run at the command prompt and a F5 in your browser and try the ArcGIS satellite-source. Things should look like this:
If they don't: you've left something out. Or forgot to put something in.
I checked; this should work!
If things look okay you can build a production bundle of your application by running
npm run build.
Npm creates a /dist directory with an index.html. Check to which css- and js file it links. You can change the name of those linked files to yourprojectname.js and yourprojectname.css and just change the links in index.html.
If you move just those three files (index.html. yourprojectname.js and yourprojectname.css) to your old-fashioned regular threaded webserver, you should have a working setup. The other files in the /dist dir are not needed.
Since <link>-tags are preferred in the <head>-section, but are tolerated elsewhere according to the HTML-specs, it's possible to just insert the necessary code in the body of another webpage. This means that there's no longer any need to use iframes showing complete html-pages as I used to do with Googlemaps.
Well. You've got the basics. I turned this into a module for use in my CMS by providing the tracksettings (url, size, color) for the JS in the html-bit. You'll probably be able to figure that part out for yourself.
Just one final remark: if the zoomout- and fullscreen-icon are garbled, your webserver is not serving UTF-8. Check your php.ini (there was a legacy charset settting on 1 of my servers).
I sincerely hope this page saves some time for other privacy-aware googledeniers, opensource-enthousiasts, cyclists and developers and especially those few readers who fit in all those categories. :-)
Zipped source is here. Demo here. | https://biketory.nl/content/51/tutorial_how_to_create_a_slippy_map_on_openstreetmap_osm_with_a_gpx_track_using_openlayers_node_js_npm_with_example_and_source.html | CC-MAIN-2019-39 | refinedweb | 2,341 | 66.74 |
Combining Datasets: Merge and Join.
For convenience, we will start by redefining the
display() functionality from the previous section:
import pandas as pd import numpy as np)
Relational Algebra¶
The behavior implemented in
pd.merge() is a subset of what is known as relational algebra, which is a formal set of rules for manipulating relational data, and forms the conceptual foundation of operations available in most databases.
The strength of the relational algebra approach is that it proposes several primitive operations, which become the building blocks of more complicated operations on any dataset.
With this lexicon of fundamental operations implemented efficiently in a database or other program, a wide range of fairly complicated composite operations can be performed.
Pandas implements several of these fundamental building-blocks in the
pd.merge() function and the related
join() method of
Series and
Dataframes.
As we will see, these let you efficiently link data from different sources.
Categories of Joins¶
The
pd.merge() function implements a number of types of joins: the one-to-one, many-to-one, and many-to-many joins.
All three types of joins are accessed via an identical call to the
pd.merge() interface; the type of join performed depends on the form of the input data.
Here we will show simple examples of the three types of merges, and discuss detailed options further below.
One-to-one joins¶
Perhaps the simplest type of merge expresion is the one-to-one join, which is in many ways very similar to the column-wise concatenation seen in Combining Datasets: Concat & Append.
As a concrete example, consider the following two
DataFrames which contain information on several employees in a company:
df1 = pd.DataFrame({'employee': ['Bob', 'Jake', 'Lisa', 'Sue'], 'group': ['Accounting', 'Engineering', 'Engineering', 'HR']}) df2 = pd.DataFrame({'employee': ['Lisa', 'Bob', 'Jake', 'Sue'], 'hire_date': [2004, 2008, 2012, 2014]}) display('df1', 'df2')
df1
df2
To combine this information into a single
DataFrame, we can use the
pd.merge() function:
df3 = pd.merge(df1, df2) df3
The
pd.merge() function recognizes that each
DataFrame has an "employee" column, and automatically joins using this column as a key.
The result of the merge is a new
DataFrame that combines the information from the two inputs.
Notice that the order of entries in each column is not necessarily maintained: in this case, the order of the "employee" column differs between
df1 and
df2, and the
pd.merge() function correctly accounts for this.
Additionally, keep in mind that the merge in general discards the index, except in the special case of merges by index (see the
left_index and
right_index keywords, discussed momentarily).
Many-to-one joins are joins in which one of the two key columns contains duplicate entries.
For the many-to-one case, the resulting
DataFrame will preserve those duplicate entries as appropriate.
Consider the following example of a many-to-one join:
df4 = pd.DataFrame({'group': ['Accounting', 'Engineering', 'HR'], 'supervisor': ['Carly', 'Guido', 'Steve']}) display('df3', 'df4', 'pd.merge(df3, df4)')
df3
df4
pd.merge(df3, df4)
The resulting
DataFrame has an aditional column with the "supervisor" information, where the information is repeated in one or more locations as required by the inputs.
Many-to-many joins are a bit confusing conceptually, but are nevertheless well defined.
If the key column in both the left and right array contains duplicates, then the result is a many-to-many merge.
This will be perhaps most clear with a concrete example.
Consider the following, where we have a
DataFrame showing one or more skills associated with a particular group.
By performing a many-to-many join, we can recover the skills associated with any individual person:
df5 = pd.DataFrame({'group': ['Accounting', 'Accounting', 'Engineering', 'Engineering', 'HR', 'HR'], 'skills': ['math', 'spreadsheets', 'coding', 'linux', 'spreadsheets', 'organization']}) display('df1', 'df5', "pd.merge(df1, df5)")
df1
df5
pd.merge(df1, df5)
These three types of joins can be used with other Pandas tools to implement a wide array of functionality.
But in practice, datasets are rarely as clean as the one we're working with here.
In the following section we'll consider some of the options provided by
pd.merge() that enable you to tune how the join operations work.
We've already seen the default behavior of
pd.merge(): it looks for one or more matching column names between the two inputs, and uses this as the key.
However, often the column names will not match so nicely, and
pd.merge() provides a variety of options for handling this.
display('df1', 'df2', "pd.merge(df1, df2, on='employee')")
df1
df2
pd.merge(df1, df2, on='employee')
This option works only if both the left and right
DataFrames have the specified column name.
The
left_on and
right_on keywords¶
At times you may wish to merge two datasets with different column names; for example, we may have a dataset in which the employee name is labeled as "name" rather than "employee".
In this case, we can use the
left_on and
right_on keywords to specify the two column names:
df3 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'], 'salary': [70000, 80000, 120000, 90000]}) display('df1', 'df3', 'pd.merge(df1, df3, left_on="employee", right_on="name")')
df1
df3
pd.merge(df1, df3, left_on="employee", right_on="name")
The result has a redundant column that we can drop if desired–for example, by using the
drop() method of
DataFrames:
pd.merge(df1, df3, left_on="employee", right_on="name").drop('name', axis=1)
df1a = df1.set_index('employee') df2a = df2.set_index('employee') display('df1a', 'df2a')
df1a
df2a
You can use the index as the key for merging by specifying the
left_index and/or
right_index flags in
pd.merge():
display('df1a', 'df2a', "pd.merge(df1a, df2a, left_index=True, right_index=True)")
df1a
df2a
pd.merge(df1a, df2a, left_index=True, right_index=True)
For convenience,
DataFrames implement the
join() method, which performs a merge that defaults to joining on indices:
display('df1a', 'df2a', 'df1a.join(df2a)')
df1a
df2a
df1a.join(df2a)
If you'd like to mix indices and columns, you can combine
left_index with
right_on or
left_on with
right_index to get the desired behavior:
display('df1a', 'df3', "pd.merge(df1a, df3, left_index=True, right_on='name')")
df1a
df3
pd.merge(df1a, df3, left_index=True, right_on='name')
All of these options also work with multiple indices and/or multiple columns; the interface for this behavior is very intuitive. For more information on this, see the "Merge, Join, and Concatenate" section of the Pandas documentation.
In all the preceding examples we have glossed over one important consideration in performing a join: the type of set arithmetic used in the join. This comes up when a value appears in one key column but not the other. Consider this example:
df6 = pd.DataFrame({'name': ['Peter', 'Paul', 'Mary'], 'food': ['fish', 'beans', 'bread']}, columns=['name', 'food']) df7 = pd.DataFrame({'name': ['Mary', 'Joseph'], 'drink': ['wine', 'beer']}, columns=['name', 'drink']) display('df6', 'df7', 'pd.merge(df6, df7)')
df6
df7
pd.merge(df6, df7)
Here we have merged two datasets that have only a single "name" entry in common: Mary.
By default, the result contains the intersection of the two sets of inputs; this is what is known as an inner join.
We can specify this explicitly using the
how keyword, which defaults to
"inner":
pd.merge(df6, df7, how='inner')
Other options for the
how keyword are
'outer',
'left', and
'right'.
An outer join returns a join over the union of the input columns, and fills in all missing values with NAs:
display('df6', 'df7', "pd.merge(df6, df7, how='outer')")
df6
df7
pd.merge(df6, df7, how='outer')
The left join and right join return joins over the left entries and right entries, respectively. For example:
display('df6', 'df7', "pd.merge(df6, df7, how='left')")
df6
df7
pd.merge(df6, df7, how='left')
The output rows now correspond to the entries in the left input. Using
how='right' works in a similar manner.
All of these options can be applied straightforwardly to any of the preceding join types.
Finally, you may end up in a case where your two input
DataFrames have conflicting column names.
Consider this example:
df8 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'], 'rank': [1, 2, 3, 4]}) df9 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'], 'rank': [3, 1, 4, 2]}) display('df8', 'df9', 'pd.merge(df8, df9, on="name")')
df8
df9
pd.merge(df8, df9, on="name")
Because the output would have two conflicting column names, the merge function automatically appends a suffix
_x or
_y to make the output columns unique.
If these defaults are inappropriate, it is possible to specify a custom suffix using the
suffixes keyword:
display('df8', 'df9', 'pd.merge(df8, df9, on="name", suffixes=["_L", "_R"])')
df8
df9
pd.merge(df8, df9, on="name", suffixes=["_L", "_R"])
These suffixes work in any of the possible join patterns, and work also if there are multiple overlapping columns.
For more information on these patterns, see Aggregation and Grouping where we dive a bit deeper into relational algebra. Also see the Pandas "Merge, Join and Concatenate" documentation for further discussion of these topics.
Example: US States Data¶
Merge and join operations come up most often when combining data from different sources. Here we will consider an example of some data about US states and their populations. The data files can be found at:
# Following are shell commands to download the data # !curl -O # !curl -O # !curl -O
Let's take a look at the three datasets, using the Pandas
read_csv() function:
pop = pd.read_csv('data/state-population.csv') areas = pd.read_csv('data/state-areas.csv') abbrevs = pd.read_csv('data/state-abbrevs.csv') display('pop.head()', 'areas.head()', 'abbrevs.head()')
pop.head()
areas.head()
abbrevs.head()
Given this information, say we want to compute a relatively straightforward result: rank US states and territories by their 2010 population density. We clearly have the data here to find this result, but we'll have to combine the datasets to find the result.
We'll start with a many-to-one merge that will give us the full state name within the population
DataFrame.
We want to merge based on the
state/region column of
pop, and the
abbreviation column of
abbrevs.
We'll use
how='outer' to make sure no data is thrown away due to mismatched labels.
merged = pd.merge(pop, abbrevs, how='outer', left_on='state/region', right_on='abbreviation') merged = merged.drop('abbreviation', 1) # drop duplicate info merged.head()
Let's double-check whether there were any mismatches here, which we can do by looking for rows with nulls:
merged.isnull().any()
state/region False ages False year False population True state True dtype: bool
Some of the
population info is null; let's figure out which these are!
merged[merged['population'].isnull()].head()
It appears that all the null population values are from Puerto Rico prior to the year 2000; this is likely due to this data not being available from the original source.
More importantly, we see also that some of the new
state entries are also null, which means that there was no corresponding entry in the
abbrevs key!
Let's figure out which regions lack this match:
merged.loc[merged['state'].isnull(), 'state/region'].unique()
array(['PR', 'USA'], dtype=object)
We can quickly infer the issue: our population data includes entries for Puerto Rico (PR) and the United States as a whole (USA), while these entries do not appear in the state abbreviation key. We can fix these quickly by filling in appropriate entries:
merged.loc[merged['state/region'] == 'PR', 'state'] = 'Puerto Rico' merged.loc[merged['state/region'] == 'USA', 'state'] = 'United States' merged.isnull().any()
state/region False ages False year False population True state False dtype: bool
No more nulls in the
state column: we're all set!
Now we can merge the result with the area data using a similar procedure.
Examining our results, we will want to join on the
state column in both:
final = pd.merge(merged, areas, on='state', how='left') final.head()
Again, let's check for nulls to see if there were any mismatches:
final.isnull().any()
state/region False ages False year False population True state False area (sq. mi) True dtype: bool
There are nulls in the
area column; we can take a look to see which regions were ignored here:
final['state'][final['area (sq. mi)'].isnull()].unique()
array(['United States'], dtype=object)
We see that our
areas
DataFrame does not contain the area of the United States as a whole.
We could insert the appropriate value (using the sum of all state areas, for instance), but in this case we'll just drop the null values because the population density of the entire United States is not relevant to our current discussion:
final.dropna(inplace=True) final.head()
Now we have all the data we need. To answer the question of interest, let's first select the portion of the data corresponding with the year 2000, and the total population.
We'll use the
query() function to do this quickly (this requires the
numexpr package to be installed; see High-Performance Pandas:
eval() and
query()):
data2010 = final.query("year == 2010 & ages == 'total'") data2010.head()
Now let's compute the population density and display it in order. We'll start by re-indexing our data on the state, and then compute the result:
data2010.set_index('state', inplace=True) density = data2010['population'] / data2010['area (sq. mi)']
density.sort_values(ascending=False, inplace=True) density.head()
state District of Columbia 8898.897059 Puerto Rico 1058.665149 New Jersey 1009.253268 Rhode Island 681.339159 Connecticut 645.600649 dtype: float64
The result is a ranking of US states plus Washington, DC, and Puerto Rico in order of their 2010 population density, in residents per square mile. We can see that by far the densest region in this dataset is Washington, DC (i.e., the District of Columbia); among states, the densest is New Jersey.
We can also check the end of the list:
density.tail()
state South Dakota 10.583512 North Dakota 9.537565 Montana 6.736171 Wyoming 5.768079 Alaska 1.087509 dtype: float64
We see that the least dense state, by far, is Alaska, averaging slightly over one resident per square mile.
This type of messy data merging is a common task when trying to answer questions using real-world data sources. I hope that this example has given you an idea of the ways you can combine tools we've covered in order to gain insight from your data! | https://jakevdp.github.io/PythonDataScienceHandbook/03.07-merge-and-join.html | CC-MAIN-2019-18 | refinedweb | 2,413 | 57.06 |
Quick Contact
The comments refer to the explanation or description of a particular line in the source code. It helps the programmer or coder to understand the logic of a particular code or program. The comments can also improve the readability of the program. It also ignored by the compiler at the run-time.
C language comments
The comments can make a code easier to find the error, and it is the most important part of any code documentation of particular software. The comment also works like annotation in the program or code.
There are two types of comments in the C programming language, which are given below:
Multi-line comment
The multi-line comment starts with forwarding slash and asterisk and ends with the asterisk forward slash in the program. This comment can apply with more than one line in a particular code to describe the meaning of those lines of code.
Syntax:
/* ------ text as comment -------- */
Example:
#include < stdio.h> int main(void) { /* initialization of the main function With multiline comment */ printf ("Ram is Good Boy"); return 0; }
Output:
Ram is a Good Boy
Single line comment
The single-line comment permits the user to comment only one line at a time in the code or program. This type of comment starts with the // (double slash) in a particular program to describe the meaning of the individual line.
Format specifier in C programming language
Format specifier defines the type of printed information or data on the standard output. These specifiers can also use during the input and output process. The compiler can understand the type of data in the input and output operation with the help of a format specifier. Some important types of specifiers are as follows:
- The minus sign (-) is a format specifier that tells the left alignment in a particular code procedure.
- The percentile symbol (%) defines the minimum field width after the number. When the particular string is less than the width, then the width will be filled with the spaces via using this format specifier.
There are some necessary format specifiers given below in the list which are used in the coding for several purposes.
Example:
Use of %c format specifier
#include < stdio.h> int main () { char info = 'Z'; printf ("%c\n", info); return 0; }
Output: Z
Another way to use %c format specifier
#include < stdio.h> int main () { int data = 90; printf ("%c\n", data); return 0; } | https://tutorials.ducatindia.com/c-programming/comments-and-format-specifier-in-c/ | CC-MAIN-2021-39 | refinedweb | 403 | 52.49 |
python-amazon-product-api 0.2.5
A Python wrapper for the Amazon.
Changelog
0.2.5 (2011-09-19) “Buttercup”
- Support for XSLT requests.
- Support for Associate tags thanks to Kilian Valkhof.
- New API versions 2010-12-01, 2010-11-01, 2010-10-01, 2010-09-01 and 2010-08-06 added.
- Fixed #16: Cannot install module under Python 2.4 without pycrypto being installed first.
- tox (and hudson) are now used for testing all supported Python versions (which includes Python 2.7 now, too).
- Test server is replaced with pytest-localserver.
- Fixed #18: Throttling no longer block CPU (Thanks to Benoit C).
- Added response-caching API (in amazonproduct.contrib.caching) to ease development (Thanks to Dmitry Chaplinsky for the idea).
- API explicitly warns about deprecated operations.
Important
The following operations are deprecated since 15 July 2010 and are now answered with a ‘410 Gone’ (and a DeprecatedOperation exception):
- CustomerContentLookup
- CustomerContentSearch
- ListLookup
- ListSearch
- TagLookup
- TransactionLookup
- VehiclePartLookup
- VehiclePartSearch
- VehicleSearch
- Added new exceptions InvalidClientTokenId and MissingClientTokenId.
- REQUESTS_PER_SECONDS can now be floats as well (e.g. 2500/3600.0).
- Added test options options --api-version, --locale and --refetch.
0.2.4.1 (2010-06-23)
Bugfix release! High time I get some continuous integration set up!
- Fixed #13: The module did not run under Python 2.4. Ooops!
0.2.4 (2010-06-13)
Locale parameter is now required at initialisation.
# before you could write api = API(AWS_KEY, SECRET_KEY) # now you have to specify your locale api = API(AWS_KEY, SECRET_KEY, 'de')
Custom test server (tests.server.TestServer) added. It runs on localhost and mimicks the Amazon webservice by replaying local XML files.
Testing now supports multiple locales. Please not that you have to run python setup.py test to run the unittests.
ResultPaginator now also works with XPath expressions for attributes (Bug reported Giacomo Lacava).
Custom lookup for XML elements (during parsing) ensures that <ItemId/> and <ASIN> are now always objectify.StringElement (Bug reported by Brian Browning).
Fixed #11: Module can now be installed library without lxml being installed first.
Regular expressions for parsing error messages can now deal with the Japanese version.
Warning
The support for the Japanese locale (jp) is still very experimental! A few error messages have still to be translated and the functionality has to be confirmed. If you know Japanese, get in touch!
0.2.3 (2010-03-20)
Tests run now for all API versions. Test cases can now be told which versions to use (class attribute api_versions set to i.e. ['2009-10-01']).
A custom AWS response processor can now be defined. For instance, here is one using xml.minidom instead of lxml:
def minidom_response_parser(fp): root = parse(fp) # parse errors for error in root.getElementsByTagName('Error'): code = error.getElementsByTagName('Code')[0].firstChild.nodeValue msg = error.getElementsByTagName('Message')[0].firstChild.nodeValue raise AWSError(code, msg) return root api = API(AWS_KEY, SECRET_KEY, processor=minidom_response_parser) root = api.item_lookup('0718155157') print root.toprettyxml() # ...
Fixed #3: Support for API Version 2009-11-01.
Fixed #4: When using a bad parameter combination, an InvalidParameterCombination exception is raised.
Fixed #5: InvalidSearchIndex is raised when unknown SearchIndex is specified.
Fixed #7: Specifying API versions works now for more than just one test per test case.
The setup.py command has been empowered a bit with the following additional options: test, build_sphinx, upload_sphinx.
ResultPaginator attributes _get_current_page_numer, _get_total_results and _get_total_page_numer are now private.
0.2.2 (2010-01-30)
- browse_node_lookup operation added.
- help operation added.
- list_lookup and list_search operations added.
- Default timeout for API calls is set to 5 sec.
- Test cases for correct parsing of XML responses added. Local XML files are used for testing (if available) stored in separate directories according to API version. These can be overwritten when config value OVERWRITE_TESTS is set to True.
- InvalidItemId exception is replaced by more general InvalidParameterValue exception.
0.2.1 (2009-11-20)
- Support for Python 2.4 added.
- Fixed #2: ResultPaginator now returns None if the XPath expression doesn’t find the node it’s looking for.
0.2.0 (2009-11-07) “Westley”
This is the first public release. We’re now available via the Cheeseshop!
- The module is no longer a package. Please use import amazonproduct (instead of import amazon.product) now.
- SimilarityLookup is now supported.
- Updated to support version 2009-10-01.
- Documentation added (made with).
- New artwork.
0.1 (2009-09-30) “Fezzik”
Initial release.
- Downloads (All Versions):
- 58 downloads in the last day
- 664 downloads in the last week
- 2553 downloads in the last month
- Author: Sebastian Rahlf
- Documentation: python-amazon-product-api package documentation
- Bug Tracker:
- Keywords: amazon product advertising api wrapper signed requests
- License: bsd
- Categories
- Development Status :: 3 - Alpha
-.5.xml | https://pypi.python.org/pypi/python-amazon-product-api/0.2.5 | CC-MAIN-2015-40 | refinedweb | 777 | 52.76 |
[prabbit22m] has written an instructable on how to build a radio controlled sphere. The mechanism is fairly simple, with one drive motor, one servo and a gyro for stability. To turn, the servo shifts the center of gravity off to one side. You can see that the system works pretty well in the video above. If it didn’t have that gyro, it would be insane, believe us, we’ve done our own experimenting. If you like this, but want more features, check out this one that has a camera and takes pictures wherever it goes. We can’t forget Swarm either. The autonomous swarm of robot spheres. Of coarse [prabbit22m] might have the best idea of all. Dress it up as a regular ball to mess with people.
Radio controlled sphere
By 18 Comments
Anyone else reminded of this? :P
Yeah, I was just going to say that. It does remind me of that comic ^_^
“too bad we can’t give it a soul”
“sure we can ‘import soul'”
“oh right, python”
I was thinking of that “kids” toy from the 1980’s… it was a toy hampster that ran in a hampster ball… this is the closest thing I can find.
dont get me wrong I’d be uber excited if this radio controlled shpere were my hack..
Of coarse
@dan p
@ryan
i was going to say that, too.
That’s the first time I’ve seen that xkcd. Maybe my favorite python joke ever. Or at least the first.
This post is full of grammar mishaps.
import antigravity
now that is exactly the thing i designed in like 7th grade the security cam robot from pop sci was close and the xkcd had an interesting way of putting on the camera but finally some one used there brains and put in a gyro. when i thought of it though i had intended to use it as a battle bot with a much larger well… everything that way i could maybe idk crush it? im not sure but i still have the plans i drew up years ago looks almost exactly like that (though much bigger)
Get a camcorder, set it loose on the parking lot of homeland security, post online :x
all ideas are non-binding! :)
homeland security has a parking garage and theres a gate with a gaurd, would not be too easy
Sammich Gravity Stabilizer FTW?
Reminds me of Death Wish V when he kills a guy with an R/C soccer ball with a bomb inside O_o
I’m sure your local homeland security place has an outside parking place too, and/or a front entrance, you will always have people doing short visits, and besides, you want to be some distance away and let the ball do the approaching, also you should cover it in kevlar probably.
dan your right in my mind XD
It would be great to be able to make it jump!
Excellent idea djodjo.
Is anyone else here thinking real life marble madness…possibly with hamsters in balls as obstacles…
Didn’t marble madness move the surface rather than the ball? Actuators on the planet axis? | http://hackaday.com/2009/02/05/radio-controlled-sphere/ | CC-MAIN-2014-42 | refinedweb | 529 | 78.18 |
Sending a message to an objectdata plugin
On 26/09/2017 at 15:08, xxxxxxxx wrote:
Is it possible to send a message to a object data plugin?
I am using this little script to trigger an object data plugin.
def main() : plugin_2_obj = c4d.plugins.FindPlugin(plugin_id) MY_CUSTOM_MSG_ID = 4 python_object_to_send = [1,2,3,4,4] plugin_2_obj.Message(MY_CUSTOM_MSG_ID, python_object_to_send ) if __name__=='__main__': main()
In the object data plugin I have following:
def Message(self, node, type, data) : if (type == 4) : print "type: ", type return True
On 27/09/2017 at 01:19, xxxxxxxx wrote:
Hello,
a NodeData base plugin can only receive the data of special, hardcoded messages. So if you want to sent data to that plugin you must use a registered message type/ID.
There is a message c4d.MSG_BASECONTAINER which allows to send a BaseContainer. It seems that it can be used to send arbitrary data.
bc = c4d.BaseContainer() bc.SetInt32(0, 100) bc.SetInt32(1, 200) op.Message(c4d.MSG_BASECONTAINER, bc)
def Message(self, node, type, data) : if type == c4d.MSG_BASECONTAINER: print("Data:") for value in data: print(value)
But please test carefully if this has any side effects.
BTW why are you using FindPlugin()? This is not used to access an instance of an ObjectData plugin in a document.
best wishes,
Sebastian
On 27/09/2017 at 01:47, xxxxxxxx wrote:
Another solution could be to use CoreMessage.
So it's the time for asking what the difference beetwen Message and Core Message?
As I understand Message are only send to one object using node.Message()
While CoreMessage are propagate throught all nodes
On 27/09/2017 at 02:13, xxxxxxxx wrote:
Hello,
core messages do NOT propagate through all nodes. Please read the Core Messages Manual carefully.
best wishes,
Sebastian
On 27/09/2017 at 02:59, xxxxxxxx wrote:
Thanks for correct me, was not sure about that!
So what's the difference beetween both? (I speak in term of implementation)
On 27/09/2017 at 03:13, xxxxxxxx wrote:
"BTW why are you using FindPlugin()? This is **not **used to access an instance of an ObjectData plugin in a document."
I need to send a message to the plugin. So I need the plugin object and FindPlugin() gives me the object (I thought).
On 27/09/2017 at 03:45, xxxxxxxx wrote:
An ObjectData return an object, so basicly you do
obj = doc.GetFirstObject() if not obj.CheckType(YOUR_PLUGIN_ID) : return bc = c4d.BaseContainer() bc.SetInt32(0, 100) bc.SetInt32(1, 200) obj.Message(c4d.MSG_BASECONTAINER, bc)
FindPlugin only give you a BasePlugin which is not an instance of your ObjectData object
c4d.plugins.BasePlugin :
Represents a registered Cinema 4D plugin. Cannot be instantiated.
On 27/09/2017 at 05:32, xxxxxxxx wrote:
Ok, clear.
Thanks, Pim | https://plugincafe.maxon.net/topic/10321/13813_sending-a-message-to-an-objectdata-plugin | CC-MAIN-2020-16 | refinedweb | 463 | 59.9 |
:
- Part 1: Introducing JudoScript, a functional scripting language
- Part 2: Programming and Java scripting in JudoScript
Introduction to programming in JudoScript.
LinkedLists behave the same as arrays, except the underlying implementation uses linked lists.
Another similar datastructure is the
Set object. It can also be created in two ways:
a = LinkedList[]; a = LinkedList[ 1, 'xyz', Date() ]; a = new LinkedList; a = new LinkedList( 1, 'xyz', Date() ); a = Set[]; a = Set[ 1, 'xyz', Date() ]; a = new Set; a = Set( 1, 'xyz', Date() );
Sets do not support access by index.
The for..in statement
The
for..in statement iterates many JudoScript and Java datastructures, including arrays, linked lists, sets, Java arrays, and instances of these Java classes/interfaces:
java.util.Iterator,
java.util.Enumeration,
java.util.Collection,
java.util.List, and
java.util.Map. All JudoScript loops support an intrinsic function,
loopIndex(), which can prove useful at times. The following example prints an array's elements as a CSV (character-separated value):
a = [ 1, 'xyz', Date() ]; for x in a { if loopIndex() > 0 { print '\t'; } print x; } println;
Arrays (including
LinkedList) have practical methods. You can sort, filter, and convert an array flexibly, with user-defined comparison, filtering, and transformation function objects.
The Object object
Object is compatible with the name-sake JavaScript object and is the parent of any user-defined class. It is a map that stores name-value pairs. An
Object can be created in two ways:
a = {}; a = { city='San Jose', state='CA' }; a = new Object; a = new Object( city='San Jose', state='CA' );
Values can be accessed via names or expressions:
a = new Object; a.city = 'San Jose'; a.state = 'CA'; println 'City: ', a.city; x = 'state'; println 'State: ', a.(x);
Object has many methods, some of which are quite powerful, such as
keys(),
keysSorted(),
keysSortedByValues(),
keysFiltered(), and
keysFilteredByValues().
The TableData object and the printTable statement
A
TableData object is a 2D array with a title. The title is an array of strings. A row number references each row; within a row, the value can be referenced by either the column index or the column name. You can sort or filter the rows based on a specific column or columns, and, of course, you can get or set individual cells.
TableData has a special print statement,
printTable.
The example of the
tableDesc() function presented in Part 1 demonstrates the use of
printTable well; the code is repeated here:
function tableDesc tableName, dbcon { if dbcon == null { dbcon = $$con; } executeQuery qry use dbcon: SELECT * FROM (* tableName *) WHERE 0 > 1 ; println [[* ---------------------------------------------------------------------- Name Type Display Precision Scale Nullable Class Name Size Name ---------------------------------------------------------------------- *]]; printTable qry.getColumnAttributes() for column('name') :<16, column('type') :<10, column('displaySize') :>8, column('precision') :>11, column('scale') :>8, column('nullable').fmtBool() :>9, ' ', column('className'), nl; // Newline } // Try it out connect to dbUrl, dbUser, dbPassword; tableDesc 'emp'; disconnect();
The
qry.getColumnAttributes() call returns a
TableData, which has columns like name, type, and scale. The
column() expression in that statement denotes a value for this column. The
:<16 is a print alignment expression (meaning left-aligned, width of 16).
As you can see, JudoScript uses the JavaScript syntax and programming model, but is much more powerful than JavaScript. If you deem algorithmic programming as a domain, then JudoScript also supplies rich domain support for programming just like JDBC scripting and other functional domain support. There are many interesting topics and details I can't afford to go into in this article; please refer to the language reference and other resources to learn more. Next I tackle another important programming topic, Java scripting.
Java scripting
JudoScript can create and use Java objects, arrays, and class objects. Java objects and arrays are created with the same
new operator but in a special namespace called
java. To access a Java class, use the
java:: operator:
a = new java::java.awt.Dimension(20,30); a = new java::int[4]; a = new java::int[] { 1, 2, 3, 4 }; c = java::java.sql.Types; println c.BOOLEAN; (java::System).out.println('aaa');
JudoScript supports the same Java
import statement for easier resolution of Java class names. The
java.lang.*,
java.io.*, and
java.util.* packages are implicitly imported. Thus, we could use
System and
Class directly in the previous example.
Java arrays and
java.util.List instances share operations with JudoScript arrays:
a = new java::int[] { 1, 2, 3, 4 }; for x in a { println 'a[', loopIndex(), '] = ', x; } a = new java::Vector; a[0] = 'A'; a[9] = 'J'; for x in a { println 'a[', loopIndex(), '] = ', x; }
JudoScript also supports extending Java classes and implementing Java interfaces. The following is an example:
class MySetIterator extends java::HashSet, Iterator { Iterator iter; constructor a, b, c { super(); iter = null; if c != null { add(c); } if b != null { add(b); } if a != null { add(a); } } // Iterator methods boolean hasNext() { if iter == null { iter = iterator(); // of HashSet. } return iter.hasNext(); } Object next() { return (iter==null) ? null : iter.next(); } } o = new MySetIterator('Hi!', 9); o.add('abc'); o.add(Date(2004,7,4)); for x in o { println x; }
This class looks a bit odd: it is somewhat like a Java class and somewhat like a JudoScript class. In fact, this is a dynamically generated Java class with fields (e.g.,
iter) and methods (e.g.,
hasNext() and
next()). Fields and methods in such classes are always public. The constructor and the method bodies are JudoScript code, and the
new operator creates new instances. More rules govern such classes; please refer to Resources to learn more.
Useful mechanisms for data processing
Now let's look at some of the JudoScript mechanisms that will help you process data.
The print statements
JudoScript has
println,
flush statements. All three can take any number of parameters and print to
System.out,
System.err, or text files.
println automatically flushes. The following simple menu system illustrates the
println and
flush statements:
println <err> [[* 0) Clobber All 1) Build All 2) Generate Parser 3) Build Base 4) Build Extension 5) Create Shipment 6) Archive All x) Exit *]]; flush <err> 'Enter your choice: '; // Don't use print! opt = readLine(); switch opt { case 0: clobberAll(); break; case 1: buildAll(); break; case 2: genParser(); break; case 3: buildBase(); break; case 4: buildExt(); break; case 5: shipIt(); break; case 6: archive(); break; default: exit 0; }
JDBC scripting frequently prints reports. The print statements' formatting facility is easy and effective:
x = 100; println x :<10;
The
:<10 expression tells the print statement to print the value aligned to the left, with a width of 10. Similarly, you can write
:>10 for a right-aligned value. For floating-point numbers, you can align numbers along the decimal point:
dollars = [ 0.10, 1000.981, 40.496 ]; for d in dollars { println d :*8.2; }
The result is:
0.1 1000.98 40.5
And you can repeat a string by specifying the repeating factor in
{} following the item:
x = 'Underline This'; println x, nl, '-' {x.length};
nl is a literal for newline. The result is:
Underline This --------------
Working with spreadsheets (CSVs)
Spreadsheets can be easily exported into CSVs for processing. The string type has a
csv() method that parses a CSV into an array. Text files can be easily read in via the
do..as lines statement. The following example has two functions; one loads a CSV into a table, the other downloads table data into a CSV:
// Load data into a database table function loadEmp csvFile { prepare upd: INSERT INTO emp(emp_no,first_name,last_name,birth_date,salary) VALUES(?,?,?,?,?) ; do csvFile as lines { cols = $_.csv(); executeUpd upd with @1 = cols[0], @2 = cols[1], @3 = cols[2], @4:date = cols[3].parseDate('yyyy-MM-dd'), @5:number = cols[4]; } } // Export data from a database table into a CSV function exportEmp csvFile { file = openTextFile(csvFile, 'w'); executeQuery qry: SELECT emp_no,first_name,last_name,birth_date,salary FROM emp ; while qry.next() { println <file> qry[1], ',', qry[2], ',', qry[3], ',', qry[4].fmtDate('yyyy-MM-dd'), ',', qry[5]; } file.close(); }
SAX and SGML scripting
JudoScript has a handy XML scripting statement,
do..as xml. Suppose we have an XML file,
data.xml:
<order> <number>0004357</number> <date>2002-9-23 23:12:1</date> <name>James Huang</name> <email>jhuang@nospam.nospam</email> </order>
We want to print the order data in a flat file:
fout = openTextFile('orderinfo.txt', 'w'); do 'data.xml' as xml { <order>: println <fout> '======================='; </order>: println <fout> '-----------------------', nl; TEXT<number>: println <fout> 'Order number: ', $_; TEXT<date>: println <fout> 'Order date: ', $_; TEXT<name>: println <fout> 'Customer Name: ', $_; TEXT<email>: println <fout> 'Customer EMail: ', $_; } fout.close();
The
do..as xml statement should be intuitive: when the XML parser encounters a tag, say,
<order>, that tag's handler code (stored in variable
$_) executes, which is SAX (Simple API for XML)-style processing. JudoScript goes one step further by providing the
TEXT<tag> syntax, which captures the text enclosed by an open and close tag.
JudoScript also has a similar statement,
do..as sgml, for SGML/HTML scraping. The following example,
html_table_check.judo, is a utility that prints the HTML table structures. It takes a command-line parameter (in
#args[0]) as the HTML filename:
// Takes a HTML file and prints out all HTML table tags indent = 0; do #args[0] as html { // Or as sgml <tbody>: printTag $_, indent; <table>,<tr>,<td>,<th>: printTag $_, indent; ++indent; </table>,</tr>,</td>,</th>: --indent; printTag $_, indent; } function printTag tag, indent { println ' ' {indent}, tag, ' @ ', tag.getRow(), ',', tag.getColumn(); }
We have seen many useful features for data processing, many of which are used in the following case study. Before finishing with JudoScript programming, let's see what other functional areas JudoScript supports.
A perusal of other major functional features
JudoScript has other functional features worth noting in addition to JDBC scripting, XML scripting, and SGML scripting.
Send mail
The
sendMail statement mimics an email client. It is used in the case study.
Execute native executables
The
exec statement supports a sophisticated command line that mimics OS shells; you can specify the starting directory and environment variables, and can feed input and receive output simultaneously.
File and archive operations
copy is a versatile command that can copy files between directories and zip, jar, tar, and gzip archives (GNU zip). There are other commands, such as
list,
move,
chmod,
chgrp, and
chown.
Schedule
The
schedule statement can launch tasks in numerous ways, one of which is used in the case study.
Windows ActiveX scripting
ActiveX objects are obtained via the
createActiveXComponent() function. Then, the objects' properties and methods can be accessed and invoked like any other object.
Java GUI scripting
You can easily assemble Java AWT (Abstract Window Toolkit) or Swing applications.
Internet and system scripting
Many system functions can make these tasks easy.
A J2EE case study
For our case study, we are going to write an offline batch order processing job for an e-commerce site, Crescent Online Shopping. The e-commerce system works asynchronously—when a customer places an order, the system stores the event in a queue (which is a simple database table). An offline batch job picks up orders in that queue and invokes an external Web service to finish the credit card transaction. The customer is notified of the final order status by email.
We have two challenges: First, The e-commerce system was built on top of a "commerce server" J2EE framework. That framework stores key entities (such as order, order line, and inventory) as Java objects in the database; i.e., Java objects are serialized in a proprietary way and stored in the database as BLOBs (binary large objects). Business information can be accessed only through the J2EE application. SQL is completely defeated—database administrators can't manipulate data in any way, and reporting tools can only report on a simple count.
The second challenge is the event queue. Instead of storing major event information in table columns, the information is encoded as XML and stored in a single column. Again, this defeats SQL.
Though odd, this architecture is based on real-world cases. This case demonstrates the power of JudoScript, which you can apply to other situations. Here is the pseudo-code for this offline job:
for all unprocessed order events in the queue decode the XML message; locate the order information through the J2EE application; call the credit card processing web service to do the transaction; set the processing result to the order; update the event queue; send notification to customer; end for;
I next explain the solutions for all pieces, and eventually put them together in a single script.
Get and decode the event
The event queue table is simple:
CREATE TABLE event( queue_id INTEGER PRIMARY KEY, message VARCHAR(1000) NOT NULL, status INTEGER NOT NULL, create_time TIMESTAMP NOT NULL, process_time TIMESTAMP );
The
status column indicates this event's status. A 0 value means new order, 1 means order processed successfully, and values of 2 and greater indicate failures. The
message column holds XML data like this:
<order> <number>0004357</number> <date>2002-9-23 23:12:1</date> <name>James Huang</name> <email>jhuang@nospam.nospam</email> </order>
The outer loop in the pseudo-code and the XML message-decoding look like this:
executeQuery qry: SELECT message FROM event WHERE status = 0; while qry.next() { // Get the order info by parsing XML order_num = null; order_date = null; do qry.message.getReader() as xml { TEXT<number>: order_num = $_; TEXT<date>: order_date = parseDate($_, 'yyyy-MM-dd hh:mm:mm'); } // Process it ...... }
In the
do..as xml statement,
getReader() is a string method that returns the string content; without the
getReader() call,
qry.message is a string and would be interpreted as a filename. We grabbed the text strings between the two tags and turned them into order number and date.
Invoke the J2EE application
The J2EE application runs on a WebLogic server. JudoScript has an
initialContext() system function and numerous helper functions for popular J2EE application servers, such as WebLogic:
ctx = weblogicContext('t3://localhost:7301', 'weblogic', 'system32'); orderMgrName = 'crescent.ejb.order.OrderManagerHome'; orderMgr = ctx.lookup(orderMgrName).cast(orderMgrName).create(); order = orderMgr.findByPK(pk);
The first line uses JNDI (Java Naming and Directory Interface) to get a context object, which is used to look up the EJB (Enterprise JavaBean) manager home interface on the third line.
cast() is a method for any Java object in JudoScript. Usually it is not needed, but in the case of EJB, the object returned by
lookup() is a stub that may or may not be public, therefore an explicit casting is needed.
Invoke the credit card processor Web service
The credit-card-processing service provider supplies a Java API that wraps the underlying Web service. We built a Java class that wraps that service to cater to our specific needs. So we only need to instantiate our own wrapper and call its methods:
ccp = new java::crescent.CreditCardProcessor('','credit','card');
Putting it together
Now that we have all the pieces, let's finish the job. We add another twist, making it a scheduled job that repeats itself every 24 hours; it can be run in the background or as a Windows service. Here is the complete source code:
startTime = Date(); startTime.hour = 2; startTime.minute = 0; startTime.second = 0; // Start at 2:00 AM everyday schedule starting startTime repeat 24*3600000 { // -- Prepare connections and other resources -- connectMailServer 'my.mail.server'; ctx = weblogicContext('t3://localhost:7301','weblogic','system32'); orderMgrName = 'crescent.ejb.order.OrderManagerHome'; orderMgr = ctx.lookup(orderMgrName).cast(orderMgrName).create(); ccp = new java::crescent.CreditCardProcessor('','credit','card'); connect to 'jdbc:oracle:thin:@dbserver:1521:dbname', 'dbuser', 'dbpass'; prepare upd: UPDATE event SET status=?, process_time=? WHERE queue_id=?; // -- Find and process unprocessed orders in the queue -- executeQuery qry: SELECT queue_id, message FROM event WHERE status = 0; while qry.next() { // Get the order info by parsing XML order_num = null; order_date = null; cust_name = null; cust_email = null; do qry.message.getReader() as xml { TEXT<number>: order_num = $_; TEXT<date>: order_date = $_.parseDate('yyyy-MM-dd hh:mm:ss'); TEXT<name>: cust_name = $_; TEXT<email>: cust_email = $_; } // Find the order and process it order = orderMgr.findByPK(order_num); status = ccp.handleOrder(order); // status = 1 for success, > 1 for failure // Update the queue for the processing result executeUpdate upd with @1 = status, @2:timestamp = Date(), @3 = qry.queue_id; commit(); // Notify the customer sendMail from: 'customer_support@crescent.cum' to: cust_email subject: 'Your Crescent order #' + order_num + ' is completed. Thank you!' htmlBody: [[* <p>Dear (* cust_name *):</p> <p>You order # (* order_num *) (* status==1 ? 'is completed' : 'has failed' *). Thanks for shopping with <em>Crescent</em>!</p> <p>Sincerely,<br>Crescent Customer Support</p> *]] ; } // End of while qry.next(). // -- Clean up -- catch: println <err> $_; // print the exception finally: { disconnect(); catch: ; } { disconnectMailServer(); catch: ; } } // End of schedule.
Lessons learned from this case study
Our fictitious system is based on real-world scenarios, involving many contemporary technologies. With JudoScript's highly abstract functional features, a terse script like the last listing can accomplish so much. We have used JDBC scripting along with Java scripting, JNDI, EJB, SAX scripting,
sendMail, and
schedule. The script is intuitive and all about business. This means great productivity, flexibility, and maintainability. Life is not perfect; difficult situations do exist for one reason or another. JudoScript can be a panacea for most issues and can make your life much easier.
JudoScript and other languages
Programming languages are roughly categorized as system languages and scripting languages. System languages, such as C, C++, and Java, are usually strongly and statically typed, compiled, and highly orthogonal. Orthogonal means having a limited set of rules to cover all possibilities. System languages are designed to create flexible software systems that are less likely to contain obvious bugs.
Scripting languages loosen the constraints on all these fronts to create an easier programming environment. They tend to use less strongly and dynamically typed systems, are usually interpreted, and break "orthogonality" by introducing so-called syntactic sugar, so in certain situations, the code becomes extremely handy and nifty.
JudoScript, being a functional scripting language, goes one step further than syntactic sugar for programming. JudoScript incorporates abstract, high-level domain support for today's common computing tasks. Therefore, its code is more intuitive, productive, and elegant. Let's compare JudoScript to other languages.
The "signal/noise ratio"
JudoScript code tends to be shorter and more germane to problems than code in other programming languages. I have converted a day-to-day utility written in Java into JudoScript. Both are well formatted and documented. The numbers are illustrated in Table 1.
Table 1. Size comparison for a utility
If we cut off the documentation, JudoScript is 50 percent the size and line numbers of the Java-based utility. What does this mean? If JudoScript code were all about business, then 50 percent of the corresponding Java code would be totally useless. The productivity and maintainability would be worse than 50 percent off, because the true logic is submerged in an ocean of noise. The signal/noise ratio reflects how well one can recognize useful information in the received signal. In the context of program source code, a higher signal/noise ratio equates to better readability and understandability.
Table 2 illustrates the remarkable difference between JudoScript code and Java code.
Table 2. Signal/noise ratio comparison for utility
By no means am I criticizing Java! I am just pointing out that Java is not right for this job. Also, the numbers are based on a particular case and are only demonstrative. The key is to find the right solution and tools based on your own situation. That solution may be another language or something you are already familiar with, but you should be aware of what is available and what you may be missing.
Express yourself directly and coherently
JudoScript's functional statements generally allow you to specify, or declare, what you want to do. In contrast, all other programming languages, including other scripting languages, allow you to program (or assemble) software. Such is the difference between 4GLs (fourth-generation languages) and 3GLs (third-generation languages). Table 3 compares two code snippets in JudoScript and Perl.
Table 3. 4GL vs. 3GL
Another classic example is
sendMail versus Java code using
javax.mail.*. To send an email using the
javax.mail API, you must create many objects to represent addresses and various parts of the message, assemble them appropriately, and find a right transport method to deliver. In JudoScript, the
sendMail statement makes this a no-brainer, as demonstrated in the case study.
The key difference: 4GLs let you directly focus on the business, while 3GLs let you focus on coding software, and the software in turn does business. An analogy is starting a car. With 3GLs, you pull levers and flip switches in a designated sequence to start the ignition and move the vehicle. You can pull levers and flip switches in different ways, which proves more flexible; but that approach is cumbersome, requires much knowledge unrelated to your intention—moving the car—and is error prone. With 4GLs, you're driving an automatic-shift: you insert and turn the key, change the gear to forward, and push the gas pedal. Every move is germane to your purpose, and a layman like me can drive a truck as long as it is automatic-shift!
JudoScript, being a 4GL atop a general-purpose Java scripting language, provides the best of both 3GLs and 4GLs. If you truly hate to send mail that easily (with
sendMail), you can call the
javax.mail API in JudoScript with no limitations whatsoever. You may want to do this to practice using new Java APIs, or prototype a Java package, or for any other reason.
Code in context
Suppose you know nothing about SAX programming; look at the following code snippets in JudoScript and Java.
Table 4. SAX Programming in JudoScript and Java
If you don't understand SAX and its framework, you may not have a clue looking at the Java code. If you look at the JudoScript code on the left in Table 4, you can probably figure out what it does immediately, because everything is right in your face. The code is exactly in the context, or your mindset, of processing an XML document.
General programming
JudoScript's general programming is simple and powerful. It does not reinvent the wheel; it simply uses a JavaScript-like syntax and programming model, but has more powerful datastructures and supports genuine object-oriented programming. For instance, the
Object type has more useful methods than its JavaScript counterpart; it has a
TableData type for in-memory 2D data processing. JudoScript treats all objects equally. You can script Java objects, arrays, and class objects as well as Windows ActiveX objects in the same way.
Conclusions
The synergy of functional support and programming power makes JudoScript a perfect tool for data processing and other computing tasks. Built on top of Java, JudoScript exposes the usability of the Java platform in a familiar and intuitive manner. It provides a convenient, unified, and unlimitedly extensible way to handle today's rich information formats and varied operations at the OS, application server, application, and distributed infrastructure levels.
Functional languages tell computers what to do, where programming languages tell computers how to do something. Functional support, or domain support, historically materialized in 4GLs. (3GLs are high-level programming languages, including Fortran, C, C++, Java, C#, Visual Basic, Perl, Python, etc.; 2GLs are assembly languages; and 1GLs are machine languages. The higher the G, the more abstract the L.) Traditionally, 4GLs are domain-specific, that is, languages have syntax and constructs to support specific domain knowledge. JudoScript is likely the first general- and multi-purpose 4GL, built atop a powerful 3GL engine and the Java runtime.
JudoScript's functional support goes one step further than syntactic sugar in normal scripting languages. This may raise concerns that the language is too hard to learn because of many nonorthogonal syntactic rules. If you understand the benefits of these functional features, then that is a small price to pay. The syntactic rules for functional support are simple, intuitive, and easy to memorize. The learning curve is not an issue.
Traditional scripting languages start with Perl and, frankly, none has substantially surpassed Perl. If you think in terms of a language's domain support, Perl supports two domains: general programming and text processing. Both are rather low-level but represent a big stride over system languages and provides greater productivity.
Today, many Java scripting languages are available and new ones keep popping up, which is not surprising because Java is a perfect platform for designing scripting languages. Using the domain-support analysis again, all Java scripting languages support at least two domains: general programming and Java object/class scripting. These two domains are low-level; the cool thing is Java scripting languages can use Java software as their native libraries.
JudoScript supports not only low-level domains such as general programming, Java scripting, and text processing, but also high-level, abstract, and functional domains, such as SQL, XML, SGML, email, filesystem and operating system operations, and schedules. To my knowledge, JudoScript is the only language that blends 4GL and 3GL features coherently and covers most of today's popular computing tasks in today's Internet era. JudoScript is in its own category of functional scripting languages. It is a language for use by any computer programmer, and Java developers can reap the most from it.
JudoScript is a product of our time. Today, many modern computing technologies are becoming norms; these norms deserve to be supported natively in functional scripting languages, and JudoScript pays the respect. It is this native support for popular technologies, big and small, that sets JudoScript apart from the rest of the crowd. After all, the reason why we script is to easily and naturally instruct computers to do what we need. Perl tried that 20 years ago; now, JudoScript tries again.
Learn more about this topic
- Download the source code that accompanies this article
- "JDBC Scripting," James Jianbo Huang (JavaWorld):
- Download the JudoScript language software
- JudoScript whitepaper
- JudoScript documentation
- JudoScript articles and book
- JudoScript example library
- Definitions of scripting language on the Web
- Also by James Jianbo Huang"Learn to Speak Jamaican" (JavaWorld, May 2004)
- For more articles on JDBC programming, browse the Java Database Connectivity (JDBC) section of JavaWorld's Topical Index
- For more Java development tools, search the Development Tools section of JavaWorld's Topical Index | http://www.javaworld.com/article/2072825/data-storage/jdbc-scripting--part-2.html | CC-MAIN-2014-52 | refinedweb | 4,398 | 55.34 |
Set your add-on product type and product ID
An add-on must be associated with an app that you've created in the dashboard already (even if you haven't submitted it yet). You can find the button to Create a new add-on on your app's Overview page or on its Add-ons page.
After you select Create a new add-on, you'll be prompted to specify a product type and assign a product ID for your add-on.
Product type
First, you'll need to indicate which type of add-on you are offering. This selection refers to how the customer can use your add-on.
Note
You won't be able to change the product type after you save this page to create the add-on. If you choose the wrong product type, you can always delete your in-progress add-on submission and start over by creating a new add-on.
Durable
Select Durable as your product type if your add-on is typically purchased only once. These add-ons are often used to unlock additional functionality in an app.
The default Product lifetime for a durable add-on is Forever, which means the add-on never expires. You have the option to set the Product lifetime to a different duration in the Properties step of the add-on submission process. If you do so, the add-on will expire after the duration you specify (with options from 1-365 days), in which case a customer could purchase it again after it expires.
Consumable
If the add-on can be purchased, used (consumed), and then purchased again, you'll want to select one of the consumable product types. Consumable add-ons are often used for things like in-game currency (gold, coins, etc.) which can be purchased in set amounts and then used up by the customer. For more info, see Enable consumable add-on purchases.
There are two types of consumable add-ons:
- Developer-managed consumable: Balance and fulfillment must be managed within your app. Supported on all OS versions.
- Store-managed consumable: Balance will be tracked by Microsoft across all of the customer’s devices running Windows 10, version 1607 or later; not supported on any earlier OS versions. To use this option, the parent product must be compiled using Windows 10 SDK version 14393 or later. Also note that you can't submit a Store-managed consumable add-on to the Store until the parent product has been published (though you can create the submission in your dashboard and begin working on it at any time). You'll need to enter the quantity for your Store-managed consumable add-on in the Properties step of your submission.
Subscription
If your want to charge customers on a recurring basis for your add-on, choose Subscription.
After a subscription add-on is initially acquired by a customer, they will continue to be charged at recurring intervals in order to keep using the add-on. The customer can cancel the subscription at any time to avoid further charges. You'll need to specify the subscription period, and whether or not to offer a free trial, in the Properties step of your submission.
Subscription add-ons are only supported for customers running Windows 10, version 1607 or later. The parent app must be compiled using Windows 10 SDK version 14393 or later and it must use the in-app purchase API in the Windows.Services.Store namespace instead of the Windows.ApplicationModel.Store namespace. For more info, see Enable subscription add-ons for your app.
You must submit the parent product before you can publish subscription add-ons to the Store (though you can create the submission in your dashboard and begin working on it at any time).
Product ID
Regardless of the product type you choose, you will need to enter a unique product ID for your add-on. This name will be used to identify your add-on in the dashboard, and you can use this identifier to refer to the add-on in your code.
Here are a few things to keep in mind when choosing a product ID:
- Customers won't see this product ID. (Later, you can enter a title and description to be displayed to customers.)
- You can’t change or delete an add-on's product ID after it's been published.
- A product ID can't be more than 100 characters in length.
- A product ID cannot include any of the following characters: < > * % & : \ ? + ,
- To offer your add-on in all OS versions, you must only use alphanumeric characters, periods, and/or underscores. If you use any other types of characters, the add-on will not be available for purchase to customers running Windows Phone 8.1 or earlier.
- A product ID doesn't have to be unique within the Microsoft Store, but it must be unique to your developer account. | https://docs.microsoft.com/en-us/windows/uwp/publish/set-your-add-on-product-id | CC-MAIN-2018-22 | refinedweb | 824 | 61.67 |
The py.std object allows lazy access to standard library modules. For example, to get to the print-exception functionality of the standard library you can write:
py.std.traceback.print_exc()
without having to do anything else than the usual import py at the beginning. You can access any other top-level standard library module this way. This means that you will only trigger imports of modules that are actually needed. Note that no attempt is made to import submodules.
Currently, the py lib offers two ways to interact with system executables. py.process.cmdexec() invokes the shell in order to execute a string. The other one, py.path.local's 'sysexec()' method lets you directly execute a binary.
Both approaches will raise an exception in case of a return- code other than 0 and otherwise return the stdout-output of the child process.
You can execute a command via your system shell by doing something like:
out = py.process.cmdexec('ls -v')
However, the cmdexec approach has a few shortcomings:
In order to synchronously execute an executable file you can use sysexec:
binsvn.sysexec('ls', '')
where binsvn is a path that points to the svn commandline binary. Note that this function does not offer any shell-escaping so you have to pass in already separated arguments.
Finding an executable is quite different on multiple platforms. Currently, the PATH environment variable based search on unix platforms is supported:
py.path.local.sysfind('svn')
which returns the first path whose basename matches svn. In principle, sysfind deploys platform specific algorithms to perform the search. On Windows, for example, it may look at the registry (XXX).
To make the story complete, we allow to pass in a second checker argument that is called for each found executable. For example, if you have multiple binaries available you may want to select the right version:
def mysvn(p): """ check that the given svn binary has version 1.1. """ line = p.execute('--version'').readlines()[0] if line.find('version 1.1'): return p binsvn = py.path.local.sysfind('svn', checker=mysvn)
sources:
- py/compat/
- py/builtin/
The compat and builtin namespaces help to write code using newer python features on older python interpreters.
py.compat provides fixed versions (currently taken from Python 2.4.4) of a few selected modules to be able to use them across python versions. Currently these are:
- doctest
- optparse
- subprocess
- textwrap
Note that for example import doctest and from py.compat import doctest result into two different module objects no matter what Python version you are using. So you should only use exactly one of these to avoid confusion in your program.
py.builtin provides builtin functions/types that were added in later Python versions. If the used Python version used does not provide these builtins the py lib provides some reimplementations. These currently are:
- enumerate
- reversed
- sorted
- BaseException
- set and frozenset (using either the builtin, if available, or the sets module)
py.builtin.BaseException is just Exception before Python 2.5. | http://codespeak.net/py/dist/misc.html | crawl-002 | refinedweb | 502 | 57.87 |
Implementing a CompressedTextField for Django
Driving to my office today I had the idea to implement a field type in Django, which allows me to transparently save data in a compressed state to the database.
A standard Lorem Ipsum paragraph (as follows) takes 446 Bytes as ASCII
and using my
CompressedTextField only takes 282 Bytes in the Database
this is roughly 60% of the space. I think for longer texts it might even get a
better Code
The idea to implement this behaviour in Django is to subclass a built-in field and extend it a bit. The only change on your model should be to use the custom field instead of a built-in field. The way of getting and setting the data should be handled in the custom field's code.
The following code can be written in your
models.py file, or (maybe better)
in some external file, but for simplicity I have coded it into the
models.py
file where the model lives, that should use this field.
First let's get the functions, which we need to compress and uncompress the data. Compression is already done, because the gzip-middleware is using it. I decided to write a function to reverse the compression as uncompress_string. (Linebreaks marked with , code also available at djangosnippets.org.)
from django.db import models from django.utils.text import compress_string from django.db.models import signals from django.dispatch import dispatcher def uncompress_string(s): '''helper function to reverse django.utils.text.compress_string''' import cStringIO, gzip try: zbuf = cStringIO.StringIO(s) zfile = gzip.GzipFile(fileobj=zbuf) ret = zfile.read() zfile.close() except: ret = s return ret
Next we need to define an model field, which should extend an already provided field, in this case the TextField field.
class CompressedTextField(models.TextField): ''' transparently compress data before hitting the db and uncompress after fetching ''' def get_db_prep_save(self, value): if value is not None: value = compress_string(value) return models.TextField.get_db_prep_save(self, value) def _get_val_from_obj(self, obj): if obj: return uncompress_string(getattr(obj, self.attname)) else: return self.get_default() def post_init(self, instance=None): value = self._get_val_from_obj(instance) if value: setattr(instance, self.attname, value) def contribute_to_class(self, cls, name): super(CompressedTextField, self).contribute_to_class(cls, name) dispatcher.connect(self.post_init, signal=signals.post_init, sender=cls) def get_internal_type(self): return "TextField" def db_type(self): from django.conf import settings if settings.DATABASE_ENGINE == 'mysql': return 'longblob' else: raise Exception, '%s currently works only with MySQL'\ % self.__class__.__name__
A few explanations: The method
get_prep_save() ist the one, that handles
data compression while saving to the database. It is pretty easy in django to
modify data before writing to the db, so this is everything we need to code.
The other way, modifing data while fetching from the db is a bit more
complicated. The way that works for me(TM) is to override the
_get_val_from_obj() method to do the uncompression and then use
contribute_to_class() to attach the
post_init() method to the model
class, to be executed after initializing the model. Essentially this means,
when you create a model instance, which has a
CompressedTextField field,
Django will create the model instance, fetch the data from the database, emit
the
post_init signal and at this point my
post_init() method kicks
in and decompresses the data. While working with the instance we always deal
with the decompressed data, and only right before saving to the database
get_db_prep_save() will compress it again.
The
db_type() method is used by the svn version of django to create
fields in the database with a custom type. If you are using Django 0.96 you
have to manually alter your database field to a blog or longblob version.
It's only provided as an starting point and only implements mysql as a
database engine. In fact it's even untested, because I use Django 0.96, so YMMV.
The last step is to include this field in your model, this is simple, here's an example:
class Item(models.Model): title = models.CharField(maxlength=200) summary = CompressedTextField(blank=True)
Drawbacks
Of course using the
CompressedTextField has drawbacks. The first I can
think of is, that using
filter() on this field will not work, because
the data in the database is not what Django expects. The same goes for
order_by(), but who orders by a text field at SQL level might have other
problems as well. I don't think this is a big problem, most people will not
use filters on text fields.
The second drawback is a decreased performance due to the overhead added by compressing and uncompressing. This should be measured, but at this point it's not important for my application so I havn't done any tests.
Benefits
One benefit of using the
CompressedTextField is the saved space at the
database level. This might be a good point if your data gets really big,
you have to decide for yourself if you need the compression because of this point.
The other and in my opinion more interessting point is the following: Using
a
CompressedTextField hides senstive data from the admin's eye. Imagine
implementing a private message system, where searching for the message content
is not an requirement. Saving the messages in a compressed state is not only
good because you save space but because your db-admin will not be able to
read the messages, while looking into the database for whatever reasons.
It's not an improvement in security, because the data can easily be
decompressed, but this way it's easier for your (not evil) db-admin to
respect the privacy of the data, accidential disclosure is no longer an option.
Conclusion
This works for me, but is not thoroughly tested. Maybe it's total crap. But I would really like to get some feedback on this piece of code. The Code is also available at djangosnippets.org.
Hi,
I needed a compressed text snippet, so I have updated it in to use Django 1.0+
Geschrieben von Bradley Whittington 1 Jahr, 8 Monate nach Veröffentlichung des Blog-Eintrags am 7. Mai 2009, 16:40. Antworten
Great snippet. Congrats!
Geschrieben von Carlo Pires 1 Jahr, 10 Monate nach Veröffentlichung des Blog-Eintrags am 11. Juli 2009, 22:52. Antworten
hi
you see the snippet who uses base64.encodestring?
it can be can add on yours or it's the same thing, just another option to compress?
this is the snippet I tell...
thanks
Geschrieben von Samuel 3 Jahre, 7 Monate nach Veröffentlichung des Blog-Eintrags am 2. April 2011, 02:28. Antworten | http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html | CC-MAIN-2017-17 | refinedweb | 1,095 | 65.62 |
After taking some time to recover, the gang rehashes all the greatest talks and favorite moments from this year's GopherCon. Much love to the Go community and all the souls who worked tirelessly to make this conference
Transcript
Alright everybody, welcome back to another episode of GoTime. Today's episode is number 53. On the show today we have myself, Erik St. Martin, Carlisia Pinto is also on the show...
Hi, everybody.
And Brian Ketelsen...
Hello.
And it seems like something big just happened a couple weeks ago that we should spend this episode talking on...
I know what it is - I dyed my head purple. [laughter]
Do you think we could fit a whole hour to talk about that? I think we could talk about that for at least three or four...
I think we could talk about it for quite a while; it's amazing just how much feedback I've gotten on it, from random strangers, high fives in airports... I'm serious, it's crazy. Most of them are thinking "That guy is too old to have purple hair, so let's high five him and make him feel better", but hey, whatever...
Are you getting selfie pictures, too?
I suppose we could talk about that...
We were outside next to the bear, and some kid walks up with purple hair and he goes "Is it okay if my mom takes a picture with you and me together?" I was like, "Heck yeah!"
I love it, by the way.
I think it's fun.
I think so, too.
So for anybody who's not aware, as we're recording this today on the 3rd of August, so this is about two weeks ago, GopherCon occurred, which is a very large conference for the Go programming language, in case you're not already familiar; that happens in July every year. We spent three days there, four if you include workshop days.
Anybody want to talk about overall thoughts and just kind of feelings walking away, excitement?
Man, we need to be more precise, because I don't know where to begin...
Yeah, the energy level was insane. It was just constant high energy, and everybody came up and told me specifically that they just felt like the energy this year was higher than any other year and it just felt like such a fun happening, happy place to be.
I can't gauge it anymore because it's my third one, and every year I go, I meet more people, so every year it's more comfortable, and I don't know "Okay, is it better because I know more people, which I like? Or is it better because the conference is better?", but I think this year it was apparently both - the conference was at a higher level; the band was amazing... A bunch of Go developers who are also musicians and singers got together and rehearsed and played at the opening party, and I felt like I was on drugs; I felt so happy...
It's Denver, are you sure you weren't on drugs?
[00:03:52.19] Yeah, I don't think I was... I was just drinking; I'm pretty sure, but I don't know, because it's Denver. But I felt like it! And it made me feel so happy looking at other Go developers who were also happy, and dancing, and having the greatest time... So thank you so much for everybody who played in that band and people who had the idea to put it together and approved the whole thing, because it was awesome.
Yeah, there were so many great people doing that... So if you weren't at GopherCon or you skipped the welcome party, what Carlisia is talking about is at the welcome party at the Punch Bowl Social, we had a full fair-level stage with lighting and stuff set up, and there was a local band there that kind of filled the air with music, but later a group of community members actually got up and sang and played instruments. I wonder if I can name everybody off without missing anybody.
It's gonna be tough, there were a lot of people.
Yeah, and Brian was also in the band...
Mark Bates... [laughs]
Yeah, Mark Bates, Cassandra Salisbury,Vanessa, Kris Nova... Who else? Brian Downs...
Yeah, JBD...
And it was really awesome though, because everybody kind of got up there and performed, and the band that was there kind of backfilled positions that we didn't have community members for. That was actually Brian's idea to do the band thing.
Kyle... Wasn't Kyle in the band as well? I forgot his last name. From Denver... No, I don't know.
No, no.
It was really great, and one of the things I loved about that, and I was telling -- it might have been Adam, when they were doing the little Changelog interviews I was talking about that one of the things I love the most about that is we often admire people for their technical abilities and everything, but we also forget that everybody kind of has hobbies and hidden talents, and it's really great to see a bunch of people share theirs with us.
Let me also say that I'm a really bad introvert, and I had that realization after this GopherCon... So this is what a good introvert looks like, and I know this because I've seen one - Katrina Owen, sometimes you see her at a conference and she'll be walking out in the middle of the day and you're like "Where are you going?" and she's like "I'm going to my hotel and I'm gonna rest." That's a good introvert.
A bad introvert like me just keeps on going... That's what I do every time I go to a conference, I just keep going, morning, day and night, and I don't ever say no to meeting somebody or having dinner or having drinks. Man, I was so exhausted when I came back, I couldn't even function. So next time I need to take at least a couple days off afterwards.
I'm in that camp too, the bad introvert camp, where I overwhelm myself a whole week, and then I go home and it's like "Nobody talk to me."
Yeah, "I'm in my cave."
I need to recharge...
It's hard though, when you get that much interaction, that much social pressure, condensed, and then you're done... It's just like "Okay, I'm done. I don't wanna talk to people, I don't wanna talk to nobody. No, no, no. Just leave me alone. I'll be in my cave." I don't know if there's a better way to deal with it, but it's certainly difficult for me.
One thing too that I wanted to point out from the earlier point that Carlisia made is this was kind of like the biggest one yet, but I felt a lot more -- I don't wanna say any of the prior years didn't have that tight-knit community feeling, because they really did... But I feel like it's getting even tighter. A lot of people I think felt like it'd get lost with the growth; that's one of the things they loved so much about the first year. But I think that a lot of the stuff has really kind of come back, and so many people socializing and collaborating on stuff, especially community day. Community day was awesome.
[00:08:23.06] All of it was, everything about it was just fantastic.
My most memorable day -- I mean, this has nothing to do with the conference, it's more about me... It is about me now - I had dinner twice. [laughter]
In one night?
In one night. I had the Women Who Go dinner, which I couldn't miss, of course, and then I had another dinner that I also didn't wanna miss. I'm like "Okay, so I eat two salads in one", and then I went and had a regular dinner afterwards.
That's funny.
Yeah, life is tough when you go to GopherCon.
I had a never-ending dinner one night... Was it the first night? I think it was workshop day, so the night most people came in traveling. We were in the -- what's the name of the restaurant downstairs?
The Buffalo burger place? Stout Street Social.
Stout Street Social, which is directly across the street from the Convention Center, and downstairs from where a lot of us were staying... And we met a group of people that were there; Brian, I think you were part of the initial group, or maybe you weren't... But there were like 10-15 people there, at this long table, and we were there for hours... And it was like a group would get up, and a new group would join. They rotated out at least 8-9 times throughout the night. I don't even know how many checks came, but it was kind of funny, because we were just there basically all night. It was constantly new people, I didn't have to go anywhere.
I came and went three times during the course of that... Like six hours.
You did, you did come back... [laughs]
So yes, I agree, that was the longest dinner ever. Every time I was surprised to see you there. [laughter]
Like, "You haven't bailed yet?"
So I mentioned the Women Who Go dinner, and that reminds me to talk about this - we're definitely gonna get to the talks and other things, but I wanna mention about the diversity efforts and how many women were there. I think it's safe to say that we had about 60 women (you guys can correct me) at the conference.
This year was the first year that it was noticeable that there were women at the conference. And there was such a big effort to increase the number of people from diverse backgrounds with the scholarships that we had, and I also realized some people who didn't go, who could have applied, didn't know about it, so heads up for next year; this is probably gonna be a thing every year. We have the conference, and other organizations have funds to send people who wouldn't otherwise be able to go. So make sure you keep an eye on that and apply.
So from those applications we got a bunch of people, and the Women Who Go dinner was packed. I think there were 50 women there. We got a nice gift from Azure, the power charger thing, a portable charger... Which is not a flask, Joshua, it's an actual charger... [laughter]
No alcohol involved...?
It's not that kind of charger, although that would have been welcome for me, too. Now that I think about it, I think I'm gonna fix that problem, because I don't have a flask, anyway.
And we had also the buddy system that was before, and people who have gone to the conference can sign up to be a guide, and people who had never been to the conference can sign up to be a buddy, and we had a nice breakfast. Andy Walker lead that effort, and he did such a great job. We got beautiful pins...
[00:12:08.18] So we had a breakfast, and I got to meet a bunch of people who I'd never heard of before, and some who I'd heard of online but never met in person. It was beautiful, and it was great to see those people mingling in the conference as well. What else...?
You know, international travel, too. Each year we know there's a large number of countries represented... I wanna say this year it was like 33, or something like that. So I know the number of countries, but at the beginning when Brian and I were doing the welcome notes, and I asked everybody to sit down based on location, and we got to the international people, I was not expecting that many people to still be standing.
Yeah, I was blown away by the international travel.
That's a long flight, to Denver...
Yeah, we had a lot of international scholarship recipients. We had people from Brazil, from India... It was really cool.
Oh, Nathan Youngman in the Slack channel brought up a good point, too - at the very end of the conference we always have leftover swag and stuff and we usually donate it... This year we decided to sell it just for pre-funding next year's diversity initiatives. Now I wish I had written down that figure exactly...
It was over 12k...
Yeah, it was 12k and some change that we raised already... So that's awesome.
It is. That's a really good seat for next year's diversity. So amazing... Thank you, everyone.
Speaking of Nathan Youngman, one of my most memorable moments of the conference was on the workshop day, when I walked around the corner and I saw some really skinny, Alton Brown-looking guy standing at the water cooler, and I did a full-on cartoon double take... And a moment later I said "Is that you, Nathan?" He has lost so much weight, he looks fantastic; I think we all need to give him a big round of applause for kicking ass and taking names and getting healthy. Nobody recognized him. It was completely amazing. Good job getting healthy, Nathan. It actually inspired me - since GopherCon I've lost 21 pounds because you inspired me.
Yes. And you know what? I had the same reaction, I had to do a double take with Nathan; I was like "Oh..." Because I had seen his pictures on Twitter, I knew he lost weight, so I was prepared to see that, but I still had to do a double take. And I mentioned on Twitter, and I've been very loose about it - I think we should get together, people who want to have a health goal for next GopherCon... To lose 10 pounds, or 20 pounds, or reach like "I wanna lift this amount of weights", or anything. We should get together and just motivate each other. I don't know what to do to get the people around this effort. I don't necessarily have the time to lead and come up with a plan, but if someone wants to do it... I definitely have a health goal for next year, and I'd be willing to do it. So there... [laughs]
That's good. I think it's a great idea.
Yeah, developers getting healthier, definitely.
Yeah, every year I see the runners... There's generally groups of people who go off and run in the city, in the morning, bright and early...
That's not me.
This year sadly missing Brad Fitzpatrick, though... All of our best to you, Brad. I know they're moments away from baby delivery, so if you're listening or if you do listen later, we hope that everything goes well with your delivery.
[00:16:01.28] Yeah, definitely.
Babies rock, and Gopher babies rock more.
Right? Does the doctor give a "Looks good to me" thumb, too?
Yeah. It has to go through Jerod.
[laughs] So we can either talk a bit about community day, or we can talk about talks first, and do them chronologically, in the order they occurred at the conference...
No... That's way too structured for us. We can make that plan now, but we'll get sidetracked so fast that we'll feel like we didn't have a plan to begin with. I think that's a poor choice for us. I think we should just continue to free-form. Otherwise we look disorganized.
Free-form away, Brian! Lead us into the free-forming world!
Erik brings up community day, and I think the standout awesome from community day was the Contributor Room that the Go team put together. That was so amazing... I don't remember the final count of people ( I wanna say it was like 150 people), but lots and lots of people went in and had mentors that helped them get through the a little bit onerous process of setting up an environment to contribute to the Go project.
I wanna say that there were, on that day alone, 40 contributions accepted and a lot more made, and I'm sure since then, many of those that were submitted have been accepted, too. So just a huge, huge shoutout to Steve Francia and others who set up that room, and the mentors who helped enable it, because it was truly awesome seeing all those people contributing to Go.
They had a little dashboard going for points for types of contributions.
I wanna say something about that, because I was there as a participant. It was amazing. I so loved that they did that, and I hope they do it every year. Actually, I talked to Steve, and I mentioned to him - and I wasn't the only one to mention this - that we should have that twice a year or maybe four times a year, and get the Go meetups together to do that as a team, as a group, around the world. Maybe we can have it in different time zones.
But anyway, so there were two separate things we were doing in that room. One was going through the process -- they had something like a fake repo, and we were going through the process of submitting to Go, except that we weren't submitting to the Go repo, we were submitting to this fake repo. But the point was to get you to go through the process, and having someone there to comment on your submission and maybe ask you to make a change, or correct a submission, make a correction and submit again, until you went through the whole process and got your submission completed. Then your change was pushed to that repo.
That was to get you through the process, and I don't wanna say it was simple, because you know, simple is very relative. I had done that before, I'm very familiar with Git, which helps, but I wanna say that there were so many people there to help. I actually got help - somebody was teaching me how to interpret, because I was reading the instruction on how to add an example, and I was having a hard time understanding the shortcuts the documentation was using... And this guy explained it to me, and I was like "Oh, that's what it means...! Thank you."
So that was one thing... And like Erik was saying, they had this dashboard, and there were like a thousand submissions, I think, just in one session. There were two sessions - one in the morning, one in the afternoon. So I highly recommend people who haven't gone through the process to go to this workshop (it's free) if they are at GopherCon in the future.
[00:20:03.09] And the other thing was like "Okay, you went through this process. How about now you go and make a submission to the Go repo?" and that's where the 40 submissions come from. A lot of people submitted code, or an example, or documentation, and they became Go contributors.
One of the things that I thought was really fantastic about it was the Phoenix users group, I think. They took that same material and brought it home for their Go meetup. Was that you, Brian Downs? I'm pretty sure it was. He did a contributor workshop right after GopherCon and spread it even further. So my callout to the meetup organizers out there is to find that material and push it out, spread the love; let's get more people contributing to Go, because that was a really great idea.
Yeah, it really is easy to follow -- the workshop format is easy to follow, it's easy to replicate... The reason why I said I would like the Go team to do it more purposefully is that I would wish somebody from the Go team (a couple people) would be there to approve the submissions and give immediate feedback, until people went through the process and they got the submission pushed through. That's the only difference...
Going through the process and making a first initial submission is really -- I hate saying "simple", but it's pretty straightforward.
No, but it's intimidating. The idea of getting all set up is intimidating, to me. I remember -- it's been years since I did my first, but I remember spending a lot of time staring at the documents and thinking "How in the world...?" because it's not just a PR; it's not even close to just a PR.
Yeah, I meant for organizers who would be teaching people... Because what makes it simple for attendees is to have people there to help them. Once people explain it to you, they keep explaining however much you need, then in the end you'll hopefully be like "Oh yeah, okay, I get it now." At some point you're going to get it.
Yeah, I agree. That was the magic that made it all work well - having so many mentors there.
I think that there's also a degree of motivation there, too.... Because there's kind of the process of getting your -- what do they call it? Where you've gotta get added to be able to submit...
The CLA?
Yeah. Did they make everybody there submit a CLA?
I'm sure they did, yeah.
So that ends up being a barrier to entry, and a lot of people feel like "Oh, well..." and Ashley McNamara mentioned this in her talk, too - you don't have to be a wizard or a genius to contribute, but a lot of people feel that way, and then when there's this additional barrier to entry, I think that that's even more "Should I go through this process? Are my contributions really wanted? I'm not (insert name of big Go person here)." So I think having that room dedicated to "anybody/everybody show up"... We wanna help get you set up and get you submitting, and all contributions are welcome. I think there is a motivational aspect to that, that "Okay, well maybe I should try this out."
It was a good initiative, so Steve Francia, Jess Frazelle, Russ Cox, all the people who made that happen behind the scenes - our biggest congratulations for pulling off such an awesome show. It was a good deal.
And Brad Fitzpatrick, who even though he wasn't able to make it, he was there reviewing everybody's stuff...
And he had a concurrency of Gophers next to him helping out, with this "Looks good to me" shirt on. It was awesome.
You know, "concurrency" is the collective noun for a group of Gophers, right? A concurrency of Gophers. [laughter]
That is true, right?
I'm sure it is.
[00:24:03.08] Yeah, it is true now.
If not, we've declared it so, right Carlisia?
Absolutely.
Another room that takes place there every year is the GoBot room, put on by the Hybrid Group. That room is always packed, and it's really cool. That also had a lot of people contributing back to the GoBot project to support new hardware.
Yeah, that room was really cool this year. I went by -- I didn't hang out in the room a lot, but I went by five or six times and every single time I went, I saw kids from the family day activities, in the room, on the floor, controlling Spheros, or something like that. It was amazing to me that Ron was able to engage all of the adults, but he's just such a good guy, he always had something for the kids, too. He's something special.
Yeah, there was -- I'm trying to remember all of the activities there. There was a data science room, there was a container technologies room, lightning talks... Lightning talk quality was off the hook this year; there was a lot of good talks. I've heard and seen a lot of people tweeting about some of the lightning talks. So if you're the type of person that only watches the normal event videos, all the lightning talks are also on YouTube. You should definitely watch some of those as well. The round tables - that actually was a lot more popular this year...
For anybody who didn't go to community day or didn't go to GopherCon at all, on community day, which is the day after the talks, we basically have these rooms set up (that we were just describing) - that contributor room, GoBot room... All of these things where you can collaborate with people, but there's also kind of like a big, open area with round tables, and you can write the project you're working on or topic you're discussing in the table that you're at, and people can kind of go through the list and join up with people doing similar things. That room was also packed all day.
It was crazy.
I'm really pleased with the number of people who are kind of seeing community day. We had way more people the first year stay than I think we anticipated. It started off as just sort of a "We know most people are probably flying out the day after the talks, and everybody flies out at different times... Maybe we should just rent some space in the hotel that we're at at the time", and people can hang out and chat and collaborate on stuff until they have to leave for their flight. Bring your bags, all that good stuff. And a lot of people stayed for that, and each year it's grown bigger and bigger, where now it's like a day that most people stay for the whole day. So if you have never been to the community day, you should definitely stay for that. It's probably one of my favorite days.
I saw at least two, maybe three really big projects that got a lot of lift on community day. The first one was Dep. I know Sam Boyer had at least three tables worth of people, all contributing. I think he started the day hoping that he would get two or three issues closed on GitHub, and he ended up stretching his goals beyond his wildest dreams and got a bunch of stuff done that he wasn't expecting to even finish this year. So it's really cool that so many people jumped in on the Dep project and got so much work done.
I know Kris Nova had a Kubicorn table, and I swear to God she looked like a cult leader over there, because they were all just watching her with rapt attention. I'm not sure what kind of things she was telling them, but I know Kubicorn had a pretty nice release, too. So the cult leader is taking over. That was pretty cool.
[00:28:03.23] So how about favorite talks? Or at least ones that you heard good feedback on that maybe you didn't catch yourself. I know that I often don't get to watch many of the talks (if any) until the video is released, and depending on my work schedule is how fast I consume them.
I can start off... One that seemed to get a very, very good reception - and I actually happened to watch this on YouTube - was just recently a guest of our show, which was Kavya Joshi, who did the Understanding Channels. If you haven't seen that talk - you weren't there for it or weren't at GopherCon - it's on YouTube. All of the talks from the conference are there.
She walks through the implementation of channels. This isn't "How do you use them?" but "How do they work under the hood?" and there is a bit of how the runtime works too, with regard to scheduling goroutines that have blocking sends and receives on them.
Yeah, it was a super geeky talk, and it was low-level enough that I think everybody learned something. My favorite part of the talk was at the end, when everybody mobbed her at the stage from the Go Team. [laughter] I turned around to Erik and I said "Somebody's getting a job offer soon..." [laughter] So yeah, that was a really good talk.
I like Edward Muller's talk on Go Anti-Patterns; that was a really good talk. He hit the nail on the head on a ton of different things that I've been teaching for the last couple years and taught me several that I've been abusing for the last couple years. That was a really good talk, if you haven't caught that one...
That room was busting out the seams.
It was, it was really busy.
It's one I haven't caught yet. I haven't been able to watch that video yet, but it definitely seemed like a really popular talk.
Yeah, everybody should watch that talk, especially beginners... Especially! Please do.
And I don't think that we could leave out Russ Cox talking about the future of Go, where I think people about dropped dead when he mentioned that it's time to start thinking about Go 2.
Yeah, but -- alright, so I love the Go team and I love Russ, but man, that was the biggest cop-out talk ever. Complete cop-out. So you put on the schedule "The Future of Go", and start letting rumors slide, "We're gonna talk about Go 2.0. This is amazing." Yeah, we're gonna talk about talking about talking about Go 2.0.
I don't know that I agree.
No, no, don't even try to defend him. Don't do it.
Okay, explain yourself better, I'm not getting -- I don't wanna interpret what you're saying; just spit it out.
I'm just teasing Russ. I really have nothing bad to say about it at all, but I was just saying that we were teased by the idea that Go 2.0 was coming, and really it was just a talk about how we're go about talking about Go 2.0.
I think that the Go team and everything has been very much "We're gonna focus on implementation and bettering that and improving compile times and speed and all that stuff, and we're not gonna work on changing the language." So I think that it still is a very exciting thing that collectively they are ready to move on. We as a community have written enough Go code that maybe it's time to start thinking about that and what that might look like.
But I also think that one of the big takeaways from that talk was soliciting for experience reports, because he walks through kind of the history of how they solve problems and things like that, and they want to see concrete examples of where these things are problems. An example was generics - sometimes they don't have enough information to help make a meaningful decision as far as how that should impact the language without kind of seeing concrete examples of how people intend to use these things, or how it's currently failing them.
[00:32:16.02] I think that that was probably the biggest takeaway - if you want to help shape what Go 2.0 ultimately becomes, you should make it a point to contribute that feedback.
I was going to say the same thing Erik just said, just not as articulate. But I do wanna re-emphasize that even though it was a talk about "Let's talk about talking about Go 2.0", I think it was very valuable... Because people communicate -- I mean, it's just normal... We're not very effective and sometimes we're in a hurry, but that talk was basically -- I mean, there were other things too, but the main takeaway for me was, like Erik said, Go 2.0 is going to happen, and if you have a problem that is not being solved now that you do want to be solved, submit what your problem is, because we need to understand what kind of problem it is. Don't submit a feature request. Don't jump ahead and say "Oh, I have a problem, and I think it will be solved if Go had this... So therefore I am requesting that you add this to Go."
He was very specifically saying, "Submit your problem. Submit a use case for your problem." I was reading Reddit, and there were so many people saying, after that talk -- I don't know if they watched it or not, or read about it or not, because there was also a blog post that goes with it... But people were saying "Yeah, we'd love it if Go had this", and some people pointing out too, "You need to submit your problem, not a feature request." It's not about submitting feature requests.
If they had named the talk -- I'm sorry, I didn't mean to cut you off. Please finish.
No, I was just gonna repeat myself; thank you for cutting me off.
[laughs] If he had named the talk "How To Communicate Or Build Consensus On The Forward Movement Of A Project", then I would give it 12 out of 10. But he named it The Future Of Go, so I say it's a 5 out of 10, because we didn't talk about Go's future, we talked about communicating and building scientific evidence about why we need to change things in Go.
We talked about how we will influence the future of Go, and that there will be a future of Go.
Exactly, which again, is an incredibly valuable talk, but we totally got click baited on the title. "Ten people got together in a room and built Go 2.0. Click here to see what happens next!"
So one cool fact that -- I'm gonna totally ignore Brian right now... [laughs]
This is new?
One cool fact that came out of that though was -- I forget where the stat came from, but I know that they had estimated somewhere between 500,000 and a million Go programmers in the world, which seems astronomical at this point.
I can't remember where the stats came from either, but you're ignoring me, so I won't answer anyway.
[laughs] So other talks...
Yes....
A Go Programmer's Guide To Syscalls. That was so cool. Great talk.
She basically started the talk out talking about how in prior talks she mentioned system calls and she wanted to kind of make sure she knew what she was referring to when talking about them, so... She wrote a talk explaining how system calls work to people, and that's actually really great if you're not familiar with how system calls work. And a little bit of Linux Assembly too kind of really helps solidify that too; it talks about as far as resetting registers, and things like that.
[00:36:14.26] Yeah, Brian Downs in Slack said he could listen to Liz talk about anything, and I totally agree... This is maybe the third time I've seen her talk, and she just has such a fantastic delivery, she's so eloquent, and she knows the materials so well. Between her and Jess Frazelle, I have 100% impostor syndrome when it comes to deep kernel-level knowledge of anything. Just "No, go ask them, because I don't know."
I was gonna say the same thing... I was going to say I haven't seen her talk, but I don't even care what it was about, because I've seen her talks before -- the talk that she gave at Golang UK last year... She's so great, I will watch anything she talks about.
She did it live. It was very badass.
It was super cool, and I love that it makes the containers seem less magic. Because I think a lot of people see them as just kind of this -- it's kind of like a virtual machine; you don't implement your own virtual machine, or virtualization software... But it kind of really breaks it down and you can kind of see the primitives of how cgroups and namespaces play into it, and how it's really just a highly configured process.
Also on the deep technical end was Keith Randall; he came back and talked about SSA.
Oh, the SSA talk... That was a good one.
Yeah, which also, if you love Assembly...
Yeah, which, to be honest, I still don't understand, but it was a great talk.
I was gonna say exactly the same thing... [laugh]
Hand wavy magic, something, something, compiler... Look!
Yeah, it's one of those things, like -- you don't understand, but it makes sense. It's amazing! It was a great talk.
It was a "temporary made sense", though... As I was listening, I was like "Yeah, this makes sense", but then an hour later it's all gone.
Yeah, don't ask me to explain it to you.
That's okay. It was a great talk.
Any other favorites from the group?
Ashley McNamara's talk... There wasn't a single dry eye in the house... It was so good.
Oh, my god... I cried, and then --
Nobody succeeds alone.
The guy on my left - I was sitting between two guys - wasn't crying, but the guy on my right was like lifting his glasses and wiping his tears. I'm like "Okay, I'm not the only one."
Yeah, it just underscores to me how much the community matters in any project, in any enterprise, in any effort, and I think the Go community is really kickass. We have a great community that cares about each other, willing to do things to help, and Ashley's talk really underscored how much that help can make a difference in your personal success and the success of your peers, and the success of the project itself. It was a touchy-feely, feel-good movie of the year. Good stuff.
Did anybody get to see Kris Nova's talk?
I was going to say that... Oh my gosh, I'm saying this all the time. I was tied up with something and I missed her talk, and I haven't had a chance to watch the video yet. That was on the top of my list of talks to watch.
Yeah, that one's on my list as well. I felt bad, because I really wanted to try to sneak into that one, and then I can't remember what happened and I realized I looked at my watch and I'm like "It was an hour ago."
[00:39:51.18] One of the things that's kind of amusing about that talk is that in conversations with random people over the last week or two, that talks specifically has come up several times. It was like, "You know, in Kris's talk, blah-blah-blah-blah...", so I think that one's making its way around the internet much faster than usual. It's kind of funny to hear them come back.
I'm trying to remember what other ones I saw... I did see a good portion of Mitchell Hashimoto's talk on advanced testing, and I think there are some really good examples...
Oh, that talk was great.
Yeah, lots of good takeaways in that one.
I was really excited that -- afterwards I talked to my co-workers and they were also excited about the fact that Vault has a test thing that you can use... As opposed to spinning up a Vault to test your stuff against, you can just have a virtual Vault; we learned that on that talk. But then it didn't really work out well, because when you call it, you have to import a package, they import a bunch of other packages, and if you don't mind that, it's okay, but... They said that's how it is, basically, so we chose not to use it. But it's very cool. In any case, there are a bunch of gems in that talk, for sure.
And then Sam Boyer did a talk on The New Era Of Go Package Management. He was talking about the new Dep, a bit of the history, direction, and guessing -- not guessing; guessing is the wrong word... But kind of like where they would like to see it go, as far as what it might look like if it were implemented into the Go tool.
Any other favorites anybody was able to make it to?
Joe Tsai's talk about Forward Compatible Go Code. I learned a lot from that talk, because there are things that you can take away from the Go 1 guarantee that all of your code will be forward-compatible, and there are things that you should really deeply learn about it. I think his talk was probably one of the more deeply educational for me, because I learned so much about how implementations can change underneath and bite you in subtle ways, in a way that's completely compatible with the Go 1 guarantee. Sometimes a guarantee isn't a guarantee, and that was a really good talk.
Can I apologize to the speakers that hear this show and don't hear their names mentioned? To be clear, Brian and Erik - they run the conference and they don't have a chance to watch most of the talks... And I was planning to watch all the talks I could, but I got tied up doing a little thing and I missed most of the talks I wanted to watch, so that's why we don't have a bigger list to mention. But in any case, you can't possibly watch all the talks.
Now I wanna mention that the talks are listed on the GopherCon repo - a repo called 2007 talks, and I wanted to say thank you to Daniela Petruzalek from Brazil. She was the scholarship recipient and she put together a readme with the links to everything you could possibly wish for: the room the talk was in, the speaker, the SlideDeck, the video, and if there was a source code, she puts a link to that, too. She has a listing for the main talks, and a different listing for all the Lightning Talks.
I'm sure it took a lot of time to put this together. It seems like a little thing, but it's so handy. I'm on this page daily.
[00:43:54.06] Yeah, couldn't agree more. She put way more effort into putting the talks into a nice, organized table, with links to everybody and all the things than I certainly would have so and one of the things that she mentioned in Slack was that Ashley's talk inspired her to do that. This is a way that she had time to give back, and I am very grateful for it, for sure.
That reminded me of something else I wanted to say in today's episode... People ask me, "So how did you get involved with these things?" because they look at me like, "I'm not nobody, but I'm doing a podcast, and I'm doing this, and I'm doing that..." - that's exactly how you get to be in a position of doing something more relevant. You just start saying yes, you just start seeing something -- you have to be looking, first of all, and then you see something that needs to be done and you do it. Then the next time you turn around, people ask you to do something and you say yes, and pretty soon you're taking leadership initiatives. That's how people get involved and start doing more relevant things in the community.
Start looking for opportunities to contribute and when people ask you to do something, say yes.
Yeah, just sort of take a chance. Before we end up wrapping up the two or moving on too far, I wanna mirror Carlisia's statement, too. Specific talks mentioned on the episode today are in no manner scoring higher than others; they happen to be ones that we were able to attend or happen to be able to watch since we got home. A lot of the times -- I actually don't think I caught much of any talks well at the conference, only slipping in videos here or there.
Everybody did an outstanding job, all the talks were great, so definitely make your way through the whole list. We did a survey too, and all of the talks got amazing feedback, so you won't be disappointed with any of them.
Well spoken.
Yeah.
So before we wrap up, I wanted to call out some other conferences too, in case you didn't get your fix at GopherCon, or it wasn't a big enough fix and you need more Go conferences...
More!
I am closing out the show, burning the place down!
[laughs] And then GothamGo is in October. They've announced their keynote speakers - Steve Francia, Alan Donovan, Carmen Andoh, Jon Bodner and Jessie Frazelle. I don't think they've announced any of the other speakers, but I think the CFP might be over for that already.
DotGo in Paris is in November. It announced six of their speakers. Brian is also speaking there.
Burning that one down, too.
Francesc and JBD and Sameer are also some of the speakers they announced. Then GopherCon Brazil is in November, and the CFP is open for that, so if you'd like to speak at a conference, I'm sure they would love to see your proposal.
Yeah, and I know Steve Francia is going to be at that conference in Brazil. Jess Frazelle is also going to be there, I'm pretty sure. I think I saw that.
Oh, nice.
Yeah, it's the second one. Last year it was really -- from all the accounts I've heard, it was really well done. And it's in Brazil, come on!
Yeah, it's Brazil.
Talking about Brazil, are we done with the conference listing?
Sure. He could talk about it for hours, so anytime you wanna end, it's great.
[00:47:57.24] I just want a quick shoutout to [unintelligible 00:47:58.18] from Brazil who was at the conference and gave us all a very fancy bottle of wine. By no means I wanna encourage people to give us gifts (please don't), I'm just saying because he did it, so I feel very compelled to say thank you on the air. He was thanking us for such a good show, but people, don't do that. Seriously.
Yeah, don't bring us gifts!
I think that adds to the impostor syndrome.
Yeah, I can't possibly be worthy of somebody bringing a bottle of wine 10,000 miles.
Yeah, he did four, because Adam also got one. Now I feel like I need to do better. It's such a pressure! People, don't give us gifts. [laughs]
It's all about pressure. Alright, I have to sign out; I've got a hard stop here in two minutes, because I am working for a company now... So thanks everybody for another show, and feel free to continue without me. GopherCon was amazing this year, and I just can't say thank you enough to all the people who participated, all the people who came... So many people helped in small and big ways; all of my love. Thank you.
Bye, Brian.
Bye, Brian. I wanna thank everybody, too. Scott Mansfield is asking about open source shoutouts. I think today really is about the community. I think that everybody contributing and everybody in the Go contributors room helping people contribute, and everybody who contributes even outside of the conference itself - I think we can all collectively agree that today we shout out to the community... Unless Carlisia has a fun one to add.
No, absolutely I second what you said.
So I think with that I think we can wrap this show up. Hopefully, coming here in the future we'll talk a little bit about some of these other conferences. Are you going to any of the other conferences? I know you go to Brazil, right?
I'd love to go to Brazil, that's still up in the air. I don't know, my work is really heavy now, and I don't know if I can take the time off. We'll see. And also, I don't what I would -- I mean, I'd have to talk, because that's how Fastly would pay me to go, and I have nothing to talk about... Not that I know of. I can't come up with anything.
That's always the hard part, getting a content. Well, I can't say that's the hard part... Getting up in front of a bunch of strangers and talking is probably the hard part, but first you have to get past coming up with what you're going to talk about.
Yeah, for me that's the hardest part, coming up with something to talk about.
I struggle with that, too. I'd like to speak again at another conference, but I need to come up with some material that I wanna talk about... Preferably something I'm super passionate about; it makes it easier that way.
[00:51:00.10] But if any of us make it to some of these conferences - I know Brian's gonna at least be at the two - we will chat a bit about our experiences there.
I guess that's a wrap. Thanks, Carlisia... Brian's already gone, so we can't thank him. Thanks everybody for listening and everybody who made it to GopherCon. And even if you didn't attend, all the companies contributing towards the diversity initiatives. This year was so amazing, and we're so grateful to be a part of this community.
Yeah, it made a huge difference, thank you.
You can always go to General, and at the top, the invite is right there.
No, I mean, for where it invites to sign you up, or you can sign yourself up. There's the auto sign-up.
Yeah, invite.slack.golangbridge.org - that's what I mean. If you wanna get that link, go to the general channel, and right at the top is one of the links to that.
Okay, so invite.slack.golangbridge.org to join the Slack. There's also the Changelog Slack which links with it if you wanna chat with us, and especially in real time. With that, thanks everybody! We'll see you next week!
Bye, thank you!
[00:52:38.16] to [00:53:24.16]
Our transcripts are open source on GitHub. Improvements are welcome. 💚 | https://changelog.com/gotime/53 | CC-MAIN-2018-39 | refinedweb | 8,691 | 80.72 |
Now, I'm going to go see if there are other pages in my application with similar behavior that can be improved with master pages.
1 protected bool HasUniqueConstraintError( Action databaseAction )
2 {
3 try
4 {
5 databaseAction();
6 return false;
7 }
8 catch( OracleException ex )
9 {
10 //Return true if exception is a Unique Constraint error
11 if( ex.Code == 1 )
12 return true;
13 else
14 throw;
15 }
16 }
1 [Test]
2 public void TestHasUniqueConstraintError()
3 {
4 SoapFormatter formatter = new SoapFormatter();
5 Assembly asm = Assembly.GetExecutingAssembly();
6 using( Stream stream = asm.GetManifestResourceStream( "XCIS.Data.Nunit.OracleUniqueConstraintException.txt" ) )
7 {
8 OracleException testException = (OracleException)formatter.Deserialize( stream );
9 Assert.That( HasUniqueConstraintError( () => { throw testException; } ) );
10 }
11 }
12
13 [Test, ExpectedException( ExceptionType = typeof( OracleException ) )]
14 public void TestHasSomeOtherOracleError()
15 {
16 SoapFormatter formatter = new SoapFormatter();
17 Assembly asm = Assembly.GetExecutingAssembly();
18 using( Stream stream = asm.GetManifestResourceStream( "XCIS.Data.Nunit.OracleTNSException.txt" ) )
19 {
20 OracleException testException = (OracleException)formatter.Deserialize( stream );
21 HasUniqueConstraintError( () => { throw testException; } );
22 }
23 }
1 public abstract class MyBaseController<T> where T : IMyBaseView
3 protected IMyDataContext _dataContext;
4 protected T _view;
5
6 public virtual void Observe( T view, IMyDataContext dataContext )
8 _view = view;
9 _dataContext = dataContext;
10
11 if( !_view.IsPostBack )
12 {
13 PreInitializeView();
14 InvalidateCache();
15 InitializeView();
16 }
17 else
18 {
19 UpdateView();
20 }
21 AttachEvents();
23 ...
24 }
1 public interface IMyConcreteView : IMyBaseView
3 event EventHandler Added;
4 event EventHandler Edited;
5 event EventHandler Deleted;
6 }
7
8 public class MyConcreteController : MyBaseController<IMyConcreteView>
9 {
10 protected override void AttachEvents()
11 {
12 base.AttachEvents();
13 _view.Edited += new EventHandler( _view_InvalidationEvent );
14 _view.Added += new EventHandler( _view_InvalidationEvent );
15 _view.Deleted += new EventHandler( _view_InvalidationEvent );
16 }
17 ...
18 }
Sure, I could have introduced a local "view" property that casts the base view to my concrete view, but do I really want to do that for all of my controllers. I'm thankful that generics can do the work for me.
Despite "The Cost of Premature Optimization", it's useful to know how things work so you can do basic things to avoid bad performance. In the end, the example below is trivial and doesn't have a significant effect on performance (at least as it applies in my application). However, knowledge of IEnumerable and yield can come in handy when it really counts. As I was writing a bit of code, I wondered if order matters when it comes to query expressions. Specifically, I have an enumerable that I was applying a Where and OrderBy to. Ultimately, I was selecting the first item from the result. I came back to the code later and decided to write an experiment. What would happen if I changed the order of the Where and OrderBy?
1: [Test]
2: public void TestExperiment()
3: {
4: IEnumerable<int> numbers = new[] { 3, 16, 2, 19, 14, 5, 20, 8, 11, 7, 13, 6, 12, 9, 4, 15, 10, 18, 1, 17 };
5: var composite = from number in numbers
6: select new { Number = number, Date = DateTime.Today.AddMonths( number ) };
7: int whereCount;
8: int orderByCount;
9: Console.WriteLine( "IEnumerable<Anonymous> : Comparing Anonymous.Date" );
10: Console.WriteLine();
11: Console.WriteLine( "Compare <= " );
12: Console.WriteLine( "Where then OrderBy" );
13: whereCount = 0;
14: orderByCount = 0;
15: composite
16: .Where( test =>
17: {
18: whereCount++;
19: return test.Date <= DateTime.Today.AddMonths( 5 );
20: } )
21: .OrderBy( test =>
22: {
23: orderByCount++;
24: return test.Date;
25: } )
26: .First();
27: Console.WriteLine( " Where:" + whereCount );
28: Console.WriteLine( " OrderBy:" + orderByCount );
29: Console.WriteLine( "OrderBy then Where" );
30: whereCount = 0;
31: orderByCount = 0;
32: composite
33: .OrderBy( test =>
34: {
35: orderByCount++;
36: return test.Date;
37: } )
38: .Where( test =>
39: {
40: whereCount++;
41: return test.Date <= DateTime.Today.AddMonths( 5 );
42: } )
43: .First();
44: Console.WriteLine( " Where:" + whereCount );
45: Console.WriteLine( " OrderBy:" + orderByCount );
46: Console.WriteLine();
47: Console.WriteLine( "Compare >= " );
48: Console.WriteLine( "Where then OrderBy" );
49: whereCount = 0;
50: orderByCount = 0;
51: composite
52: .Where( test =>
53: {
54: whereCount++;
55: return test.Date >= DateTime.Today.AddMonths( 5 );
56: } )
57: .OrderBy( test =>
58: {
59: orderByCount++;
60: return test.Date;
61: } )
62: .First();
63: Console.WriteLine( " Where:" + whereCount );
64: Console.WriteLine( " OrderBy:" + orderByCount );
65: Console.WriteLine( "OrderBy then Where" );
66: whereCount = 0;
67: orderByCount = 0;
68: composite
69: .OrderBy( test =>
70: {
71: orderByCount++;
72: return test.Date;
73: } )
74: .Where( test =>
75: {
76: whereCount++;
77: return test.Date >= DateTime.Today.AddMonths( 5 );
78: } )
79: .First();
80: Console.WriteLine( " Where:" + whereCount );
81: Console.WriteLine( " OrderBy:" + orderByCount );
82: }
Here are the results:
IEnumerable<Anonymous> : Comparing Anonymous.DateCompare <= Where then OrderBy Where:20 OrderBy:5OrderBy then Where Where:1 OrderBy:20Compare >= Where then OrderBy Where:20 OrderBy:16OrderBy then Where Where:5 OrderBy:20
What causes this phenomenon? The use of IEnumerable and yield expressions.
A few things to consider when building query expressions:
I received quite a bit of feedback regarding my Join extension to IEnumerable that generates a comma separated list. The purpose was to emulate string.Join(), but to add more flexibility as to what is "joined". I took some time aside to investigate some of the suggestions and alternatives to my implementation. I should note, that I would not normally do this. I try to avoid premature optimization. However, there are certain practices that can be learned that improve performance in general (like using a StringBuilder). With these in your toolbelt, you can build better performing applications the first time, and at little or no cost. It takes no more effort to use a StringBuilder than to concatenate strings in a loop (at least once you become familiar with StringBuilder). Regardless, the intent of this post is not to try to sell you on StringBuilder. Consider the fact that many optimizations involve tricks or algorithms that could make the intent of the method less obvious. Unless you really need that optimization, are you really willing to pay the price? Most of us do not work on applications that require lightning fast code. In my career, the only times that I have had to address performance in my C# code was when I was working with bulk import and export of data. In those cases, I was dealing with hundreds of thousands if not millions of iterations of my code. In this case, a millisecond here or there can make a big difference. On the other hand, saving a couple of milliseconds to pull up an ASP.Net page is hardly worth the effort. The bottom line is, your customers will feel the effects of broken code before they recognize a couple of milliseconds added to their page load times. In other words, don't sacrifice readability and maintainability for run-time optimization (unless you absolutely have to - even then, get a second opinion).
In response to a comment on one of my previous posts (Safely Overriding Equals), I've decided to post some comments about Extension methods in general. A friend asked me what I gained out of extending string to convert to an enum. He asked, "is it just 'syntactic sugar'?" The simple answer is, "Yes." In fact, this is true of many extensions. Clearly, the major advantage of extensions is changing the syntax of how they are called. In fact, I have written a few extensions that support chaining and make my code more readable (at least in my mind)
1: OracleCommand command = GetProcedureCommand( "fas_closing_pkg.GetClosingDealLegs" )
2: .WithInputParameter( "pClosingMonth", closingMonth )
3: .WithInputParameter( "pDealId", dealId )
4: .WithOutputCursor( "oDealLegs" );
So what are extensions? Well, they are just static utility methods with an extra keyword. You can even call the extensions as if they are static methods if you really want to.
For Example:
1: left.SafeEquals( right, test => left.Key == test.Key );
2: GeneralExtensions.SafeEquals( left, right, test => left.Key == test.Key );
The second line is no different than what you might have written in .Net 2.0. You may have even written many of these static utilties before and are now enabling them as extensions.
What this means, is that extensions are just static methods behind the scenes. They are not instance methods. One implication of this fact is that you must consider that the extended object could be null. And, if it is null, you will not get an object reference exception when the extension is called. You could get an exception within the scope of the extension method depending on your implementation.
For example, this is totally legal (generating no runtime errors)
1: TestClass left = null;
2: TestClass right = new TestClass( "right" );
3: Assert.IsFalse( left.SafeEquals<TestClass>( right, test => left.Key == test.Key ) );
Where SafeEquals is implemented as follows:
1: public static bool SafeEquals<T>( this T left, object right, Predicate<T> test )
2: {
3: if( left != null && right != null && right.GetType().Equals( left.GetType() ) )
4: {
5: return test( (T)right );
6: }
7: return false;
8: }
So, when writing extensions, take a little extra time considering what would happen if the target object is null. | http://geekswithblogs.net/WillSmith/archive/2008/07.aspx | CC-MAIN-2018-43 | refinedweb | 1,477 | 50.84 |
tmp_dir = '.tmp'
import os, sys, shutil
tex_file = sys.argv[-1]
f, ext = os.path.splitext(tex_file)
assert ext[1:] == 'tex'
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
os.system('pdflatex --shell-escape --output-directory=%s %s' % (tmp_dir, f))
shutil.move('%s%s%s.pdf' % (tmp_dir, os.path.sep, f), os.curdir)
/usr/bin/python /Library/TeX/Root/bin/pdflatex.py
import os
import sys
import shutil
tmp_dir = '.tmp'
# find out the name of the file to compile
tex_file = sys.argv[-1]
file_name, file_ext = os.path.splitext(tex_file)
assert file_ext[1:] == 'tex'
# create the temporary directory if it doesn't exist
if not os.path.isdir(tmp_dir):
try:
os.mkdir(tmp_dir)
except OSError:
raise IOError('A file named "%s" already exists in this catalog' % tmp_dir)
# run pdflatex
os.system('pdflatex --shell-escape --output-directory=%s %s' % (tmp_dir, file_name))
# move the pdf file back to the tex directory
try:
shutil.move('%s%s%s.pdf' % (tmp_dir, os.path.sep, file_name), os.curdir)
except IOError:
print '\n\nPdf file not found.'
Nice improvement. Is there a way to make it show up in the Typset in TeXShop and not only in drop-down menu within the .tex file's window?
Don't forget that these auxiliary files are necessary for cross-referencing, producing the table of contents, index, etc.
If you are producing documents that don't require any of those, then this ought to work.
Also, instead of replacing the standard pdflatex, it is better to make it an alternative "Engine", using this nice feature of TeXShop.
Save your script in ~/Library/TeXShop/Engines, as, say,
mypdflatex.engine, and don't forget to make it executable.
(Also, add the line
#!/usr/bin/python
at the top have python run the script when it's invoked)
Then you can access your engine as you would any other engine, like xetex, of latexmk, or whatever. You can select it from either the popup menu or include the line
%!TEX TS-program = mypdflatex
at the top of any tex file to have TeXShop compile it using your script.
---
Luís
Don't forget that these auxiliary files are necessary for cross-referencing, producing the table of contents, index, etc.
Don't forget that these auxiliary files are necessary for cross-referencing, producing the table of contents, index, etc.
I believe that when you set the output-directory, it will also look there for the auxiliary files.
output-directory
And where can I set this Output-Directory?
The script does that for you.
Great hint! But I don't see the point of putting it in a new hidden directory when you can just throw it in /tmp.
/tmp
tmp_dir
where it can find the .aux file. I've tried to create a new version of bibtex by creating a new engine 'hidebibtex.engine' along the same lines as outlined above. Alas, bibtex does not support the option --shell-escape nor --output-directory, or at least that is how I understand the error message.
SetFile -a V *.pdfsync *.log *.bbl *.aux *.blg
When I try this hint, I get an error if my filename has any spaces in it. When I use the LaTeX engine normally, this doesn't happen, though. Is this a problem with python not parsing spaces in names correctly? Any way to correct it?
I changed the script to do two things:
getting it to compile with xelatex was easy. the tricky part was getting support for file name spaces, because you can't use the join(args) command. Therefore, I just switched the command variable to concatenated variables.
The Catch:
#!/usr/bin/python
import os, sys, shutil, subprocess
OUTPUT_ARGUMENT = '--output-directory='
DEFAULT_OUTPUT_PATH = '/tmp'
# Grab the output directory from the arguments
output_arg_specified = False
output_dir = None
for arg in sys.argv:
if arg.startswith(OUTPUT_ARGUMENT):
output_arg_specified = True
output_dir = arg.split('=')[1]
break
# If an output directory argument was not found, then set it to the default
if output_dir is None:
output_dir = DEFAULT_OUTPUT_PATH
# The output pdf will be named the same as the tex file
tex_file = sys.argv[-1] #variable includes spaces in file name no problem here
pdf_file_name, extention = os.path.splitext(tex_file) #no problem here with space in filename
pdf_file_name = pdf_file_name
tex_file = tex_file
print "tex_file --> " + tex_file + " pdf_file_name --> " + pdf_file_name + " extention --> " + extention
# Not sure why this is necessary
assert extention == '.tex'
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
# If command arguments did not contain the oput directory argument, then since
# we set it to have a new detault, add it to the arguments we will pass on
args = sys.argv[1:]
if not output_arg_specified:
args.insert(0, OUTPUT_ARGUMENT + output_dir)
command = 'xelatex ' + OUTPUT_ARGUMENT + output_dir + ' ' + '"' + tex_file + '"'
# %s' % ' '.join(args)
print '%s Executing: %s' % (sys.argv[0], command)
print command
# Run the original command which generates all the files
os.system(command)
pdf_file_src = output_dir + '%s' % (os.path.sep) + pdf_file_name + '.pdf'
pdf_file_dest = '%s%s' % (os.curdir, os.path.sep) + pdf_file_name + '.pdf'
# If the destination pdf already exists, delete it so that the new one may be
# coppied.
if os.path.isfile(pdf_file_dest):
os.remove(pdf_file_dest)
# Move the pdf back to where it normally is
shutil.move(pdf_file_src, os.curdir)
Visit other IDG sites: | http://hints.macworld.com/article.php?story=20070906022746216 | CC-MAIN-2018-05 | refinedweb | 858 | 59.7 |
The following components are used for this project:
HDMI Cable
Monitor
Keyboard
Mouse
Looking for a great introduction to Raspberry Pi? Try the Zagros Raspberry Pi 3 Starter Kit which has everything you need to begin discovering Raspberry Pi.
Step 1: Revise Weather Display.
This tutorial begins with a Python file from a previous instructable: Weather Display with Sense Hat.
You can go back and follow that instructable first or download and open this file in a Python 3 editor for the next steps.
Step 2: Install and Import Flask Framework to Project.
Install Flask. In the Terminal type:
sudo apt-get install python3-flask
Import Flask to your project. In the weather_log.py file add this line below the other imported modules:
from flask import Flask
Step 3: Python Code to Display HTML on the Web.
Insert this code just below the "message" variable and save it. We will build out the rest of the app in future steps.
Python is space sensitive, the entire code below the line of 'def index():' should be indented.
@app.route('/')
def index();
now = str(asctime())
currentWeather = now + " " + "-" + message + "\n"
weatherData = {
'weather': currentWeather
}
return render_template('index.html', **weatherData)
You can go ahead and delete the while True: statement at the bottom of the code. In this step we have moved it inside the index function. The 'weather' property will be passed to the double curly braces in the HTML.
Step 4: Create a Web App Folder for Your Project.
Create a folder webapp in the pi directory.
Create two subfolders templates and static.
Step 5: Create an Index.html File From the Text Editor.
Navigate to Menu > Accessories > TextEditor
Paste in this section of HTML and save it under the templates folder with a file name of index.html.
<html> <head> <link rel = "stylesheet" href = "/static/style.css" /> </head> <body> <h1>Weather:</h1> <h2>{{weather}}</h2> </body> </html>
Step 6: Style Your App.
Create a new file in the text editor save it in the static folder with a file name of style.css.
Paste this CSS code into the editor. Feel free to get creative and change the colors and style to your liking.
body {
background: navy;
color: yellow;
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
border-bottom: 1px solid gold;
margin-bottom: 40px;
padding: 10px;
}
Step 7: Start the Web Server.
In Terminal run the web server by entering:
python3 webapp/weather_log.py
It should output the following:
* Running on
* Restarting with reloader
Step 8: Test Your App in a Browser.
With the web server running point your browser to:
This will also work on any computer on your network!
You should now see the current Temperature, Humidity and Pressure.
As long as the web server is running you can navigate to that site to get the latest weather. | http://www.instructables.com/id/Weather-on-the-Web-With-Sense-Hat/ | CC-MAIN-2017-17 | refinedweb | 470 | 66.23 |
Hey I have started Java Recently and I was wonder if someone could help me!
I have partly created a program which gets Dates and Times and Stores these in array and it just a little program which works out your hours and your salary. However I want to use a Array which can store lots of new dates and times for example if they Bunch in at 1pm it should store this is Array[] if someone could help me out it out be appreciated and feel free to comment about my code.
Sorry I didnt bother Making Methods;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class mainclass {
public static void main(String[]args){
System.out.println("\t" + "\t" + "\t" + "Welcome to HourlyRate");
System.out.println("");
System.out.println("1. Punch In" + "\t" + "2. Punch Out" + "\t" + "3. Set Hourly Rate" + "\t" + "4. Calcuate Wage" + "\t" + "5. Exit Program");
// Scanner Class
//Arrays
String punchIn[] = new String[1];
String punchOut[] = new String [7];
int wage[] = new int [7];
// hourly rate
float hourlywage = 0.00f;
// Case Navigation
int navmenu = 0;
// User Input
Scanner userinput = new Scanner(System.in);
//Date and Time
DateFormat df = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale ("en", "EN"));
while(navmenu=0){
navmenu = userinput.nextInt(); //
Majid Hussain's Profile
Hey I have started Java Recently and I was wonder if someone could help me! | https://thenewboston.com/profile.php?user=40450&type=friend | CC-MAIN-2016-50 | refinedweb | 231 | 59.19 |
vfb2ufo
- RafaŁ Buchner last edited by
Hi guys!
I'm generating UFOs files from old VFBs files.
I'm using this script:
from mojo.UI import GetFolder import os from subprocess import Popen import fontParts.world as fpw # path to vfb2ufo on your machine ufo2vfbLocation = "/usr/local/bin/vfb2ufo" # path to folder with input VFBs vfbsFolder = GetFolder(message="get source folder with *.vfb files") # path to folder for output UFOs ufosFolder = vfbsFolder+'_vfb2ufo' if not os.path.exists(ufosFolder): os.mkdir(uf', '.ufo')) # call the vfb2ufo program p = Popen([ufo2vfbLocation, vfbPath, ufoPath]) # "-64", etc p.wait() font = OpenFont(ufoPath, False) font.save(formatVersion=3)
It is failing to open the font in RF with OpenFont function.
This is what I get in the output:
Traceback (most recent call last): File "lib/fontObjects/fontPartsWrappers.pyc", line 1430, in __init__ File "lib/fontObjects/__init__.pyc", line 440, in createFontObject File "lib/fontObjects/doodleFont.pyc", line 36, in __init__ File "lib/fontObjects/ufo2.pyc", line 530, in normalizeUFO File "lib/fontObjects/ufo2.pyc", line 506, in _normalizeUFO File "/Applications/RoboFont.app/Contents/Resources/lib/python3.6/defcon/objects/font.py", line 529, in _get_features File "/Applications/RoboFont.app/Contents/Resources/lib/python3.6/fontTools/ufoLib/__init__.py", line 580, in readFeatures File "codecs.pyc", line 321, in decode UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 72: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "vfb2ufo.py", line 29, in <module> File "lib/fontObjects/fontPartsWrappers.pyc", line 1932, in OpenFont File "lib/fontObjects/fontPartsWrappers.pyc", line 1438, in __init__ lib.tools.misc.RoboFontError: The file /path/to/file.ufo can not be read by RoboFont.
Is there maybe better way to generate UFO3 files out of VFBs?
- colinmford last edited by
I assume these VFBs are coming from FL5?
We've had a little more luck with Tal's old UFO Central script than vfb2ufo...
(Generates UFO2, but then saving them up to UFO3 is trivial)
Needs to be run from within FontLab5, though. If you're stuck without access to FL5 then vfb2ufo might be the best way.
As for your error, it seems like it's having an issue with the feature file of one of your fonts. Maybe stop it half way and see what the file looks like?
This old repo might come in handy. I haven't used it in a long time but I assume that it still works with the simple py3 adjustments.
- RafaŁ Buchner last edited by
Thanks guys! I will experiment with those scripts
sidetone: if
vfb2ufois installed and accessible in terminal, then RoboFont can open and generate vfb files. But
vfb2ufohas lots of issues... there are combos possible with ufoCentral and eventually generating binaries and converting those...
good luck anyhow! | https://forum.robofont.com/topic/686/vfb2ufo | CC-MAIN-2020-40 | refinedweb | 470 | 52.26 |
31 January 2011 11:07 [Source: ICIS news]
SINGAPORE (ICIS)--Shares in Asian petrochemical companies mostly fell on Monday, in line with regional bourses, as ongoing riots in ?xml:namespace>
“The current happenings in
Massive protests demanding the ousting of Egypt President Hosni Mubarak, who has been in power for the past 30 years, were currently ongoing in Cairo.
In
In
In Singapore, the benchmark Straits Times Index (STI) slipped 49.97 points or 1.60% at 3,179.72, with the shares of crude palm oil producer Wilmar International falling 2.05%.
In
The SET Index closed down 17.73 points or 1.81% lower at 964.10.
Additional reporting by Nurluqman Surat | http://www.icis.com/Articles/2011/01/31/9430615/asia-petrochemical-shares-down-on-egypt-riot-jitters.html | CC-MAIN-2015-06 | refinedweb | 114 | 69.48 |
Difference between revisions of "Meetings/Neutron-DVR"
Revision as of 14:32, 10 August 2016
The OpenStack Networking L3 DVR Sub-team holds public meetings as advertised on OpenStack IRC Meetings Calendar. If you are unable to attend, please check the most recent logs.
Contents
- 1 Meetings
- 2 Agenda
- 2.1 Meeting August 10 August 10
- (MUST FIX) - CSNAT port fails due to no fixed ips. (partial workaround proposed).
- (MUST FIX) - Two masters after reboot of controller when HA enabled. Also seen with DVR
- (SHOULD FIX) - Keepalive process kill vrrp child process with l3/dvr/ha
- (SHOULD FIX) - Metadata error with dvr_snat on compute hosts.
- ( Needs review)
- (SHOULD FIX) - Generic DVR portbinding useful for HA ports.
- ( Need review)
- (MUST FIX) - Itemallocator class can throw a ValueError
- (MUST FIX) - DVR+L3 HA Loss during failover is higher (Need to triage)
-
- (Tempest change) - Needs work - must merge before Nova patch
- (Merged) - Neutron Server side DVR change
- (Merged) - L3 Agent side patch
- (OVS drops RARP packets)
- in neutron (Needs review) Notify vif plugged event (related)
- and nova (Needs review) Notify vif plugged event (related)
- -
- (MUST FIX) - Floatingip move within the same node does not handle fixed ip properly
- (MUST FIX) - Occurences of Duplicate fg port in fip namespace
- (MUST FIX) (Allowed_address_pair delayed FIP association)
- (With DVR Pings to floating IPs replied with fixed-ips if VMs are on the same network)
- (Merged) (Reverted)
Performance/Scalability
Gate failures (haleyb)
- Current failure rate:
- Upstream multinode job failures seen, root cause identified.
- Check job failures were mostly due to the ipv6 dual net test case failure, cause identified and workaround proposed.
- Functional test failures seen in the Check queue, root cause yet to be identified.
- Single node check job failure rates are more when compared to neutron full job.
- Multi-node check job failure rate have gone up from last week
- Bugs in Nova:
- (Volume based live migration aborted unexpectedly)
- (live-migration ci failure on nfs shared storage)
- Old bug to help in debugging the gate
- - Tempest "SSHTimeout" failures (only for debugging)
Wanted to talk about some related patches, so we come up with a good answer going forward These two both do similar things around ip_lib.get_devices() code:
- (L3 agent: check router namespace existence before delete)
- (Check if namespace exists before getting devices)
And this is a change that also checks existence so not throw exceptions:
- (DVR: Clean stale snat-ns by checking its existence when agent restarts)
Need to escalate the nova patch for the live migration. Since we have the tempest test running right now, we need someone from the nova team to take a look at the nova live migration patch.
Meeting commands
/join #openstack-meeting-alt
#startmeeting neutron_dvr
#topic Announcements
#undo topic
#link
#action haleyb will get something specific done this week
#chair Swami
...
#endmeeting | https://wiki.openstack.org/w/index.php?title=Meetings/Neutron-DVR&diff=prev&oldid=130137 | CC-MAIN-2019-47 | refinedweb | 464 | 51.52 |
Here I summarize the iterative implementation for preorder, inorder, and postorder traverse.
Pre Order Traverse
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.add(p.val); // Add before going to children p = p.left; } else { TreeNode node = stack.pop(); p = node.right; } } return result; }
In Order Traverse
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); p = p.left; } else { TreeNode node = stack.pop(); result.add(node.val); // Add after all left children p = node.right; } } return result; }
Post Order Traverse
public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> result = new LinkedList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.addFirst(p.val); // Reverse the process of preorder p = p.right; // Reverse the process of preorder } else { TreeNode node = stack.pop(); p = node.left; // Reverse the process of preorder } } return result; }
Again,.
Sorry if I missed your point, but how can a binary tree has topological dependencies?
Nick's right. You're simply cheating. Because strictly speaking, you've already visited root before left and right.
Your answer is short. The reverse of pre-order is skillful though may not be general. Here I attach my solution of postorderTrav without reversing pre-order. The key point is when you pop a node from stack, you ensure you have already explored its children.
public class Solution { // Important, when you pop a node, ensure its children are traversed. public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> s = new Stack(); List<Integer> ans = new ArrayList<Integer>(); TreeNode cur = root; while (cur != null || !s.empty()) { while (!isLeaf(cur)) { s.push(cur); cur = cur.left; } if (cur != null) ans.add(cur.val); while (!s.empty() && cur == s.peek().right) { cur = s.pop(); ans.add(cur.val); } if (s.empty()) cur = null; else cur = s.peek().right; } return ans; } private boolean isLeaf(TreeNode r) { if (r == null) return true; return r.left == null && r.right == null; } }
Shorter one:
public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList(); TreeNode p = root; Stack<TreeNode> st = new Stack(); while (p != null || !st.empty()) { for (;p != null && !isLeaf(p); st.push(p), p = p.left); if (p != null) ans.add(p.val); for (;!st.empty() && st.peek().right == p; p = st.pop(), ans.add(p.val)); p = st.empty() ? null : st.peek().right; } return ans; }
An alternative one:
public List<Integer> postorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList(); if (root == null) return ans; Stack<TreeNode> st = new Stack(); st.push(root); for (TreeNode p = root, prev; !st.empty();) { prev = p; p = st.peek(); if (p.left != null && p.left != prev && p.right != prev) st.push(p.left); else if (p.right != null && p.right != prev) st.push(p.right); else ans.add(st.pop().val); } return ans; }
I
public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> res = new LinkedList<Integer>(); if(root == null){ return res; } Stack<TreeNode> stack = new Stack<TreeNode>(); while(!stack.isEmpty() || root != null){ while(root != null){ stack.push(root); res.addFirst(root.val);; root = root.right; } root = stack.pop(); root = root.left; } return res; }
@xinying3 Stack is an obsolete class inherited from Vector (so wired), but Deque is a flexible interface which is obviously better than Stack. If you need to deal with concurrency, BlockingDeque is also a better one.
Here is my solution:
public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> list = new ArrayList<Integer>(); TreeNode pre = null; TreeNode current = root; while(current != null || !stack.isEmpty()) { while(current != null) { stack.push(current); current = current.left; } current = stack.pop(); if(current.right != null && pre != current.right) { stack.push(current); current = current.right; continue; } list.add(current.val); pre = current; current = null; } return list; } }
@root; }
Strictly speaking, this algorithm is only for tree sequentialisation in the post order because you are not visiting the nodes in the post-order. Let's put it another way, if you are asked to do some task by traversing the tree in the post order (say, free a tree), you cannot use this algorithm.
@BetaGo checkout my solution..
My iterative solution is as simple as recursive one and it's practical.
@jedihy It's a smart generalized way, using graph-alike traversal. But if you investigate the in-order search, you have more push/pop operations than others' solutions. And another drawback is, you need these additional visited flags.
@BetaGo More space might be consumed but it does not mean slower than other iterative solutions. Actually, I don't think my solution is something related to graph. It's emulating the stack in recursion or you can say emulating the real visiting order when doing traversal. It's very practical because I solved a lot of tree traversal problems using this method.
EDIT: I think it's a kind of BFS but I 0,1 in tuple is not used for visit flag. They are used as command identifier to identify commands in recursion.
I didn't say you solution is slower. I was talking about the space complexity. Actually, if one solution consumes more space, we expect it should be faster. Kind of time-space tradeoff stuff. But for your solution, I don't see this time complexity advantage. Worse, have you investigated the in-order traversal? Some nodes are pushed/popped more than once. It has more stack operations compared with other solutions, which means it's slower.
I don't know what your command identifier is meant for. But without doubt, I can regard it as visited flag to write the exactly same solution as yours.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/30632/preorder-inorder-and-postorder-iteratively-summarization?page=1 | CC-MAIN-2017-43 | refinedweb | 991 | 60.92 |
Hi i am new to struts. I don't know how to create struts please in eclipse help me
Hi - Struts
very urgent....
Hi friend,
I am sending you a link...Hi Hi friends,
must for struts in mysql or not necessary...://
Thanks. Hi Soniya,
We can use oracle too in struts... - Struts
Hi... Hi,
If i am using hibernet with struts then require... of this installation Hi friend,
Hibernate is Object-Oriented mapping tool... more information,tutorials and examples on Struts with Hibernate visit help me. its very urgent Hi friend,
Some points to be remember
struts
struts <p>hi here is my code in struts i want to validate my...;
var i = 0;
var fields = new Array... focusField = null;
var i = 0;
var fields =
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean... for u.the true keyword indicates that if no session is exist before,it will create new
Struts - Struts
Struts Dear Sir ,
I am very new in Struts and want... validation and one of custom validation program, may be i can understand.Plz provide the that examples zip.
Thanks and regards
Sanjeev. Hi friend
struts
struts hi
i would like to have a ready example of struts using"action class,DAO,and services"
so Hi,
i am writing a struts application
first of all i am takeing one registration form enter the data into fileld that
will be saved perfectly.
but now i can apply some validations to that entry details
but with out
validation problem in struts - Struts
string tht i checked wid d help of a joptionbox. so whn m trying to authenticate...validation problem in struts hi friends...
m working on one project using struts framework. so i made a user login form for user authentication
Tapestry - Struts
Tapestry
I want to use Tooltip in my project,
in which i m using Tapestry4.1 as frontend, could anyone guide me, is der any inbuild tapestry... respond me fast
thanks Hi friend,
Code to help in solving
Struts - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I Report Hi,
I m getting Error when runing struts application.
i have already define path in web.xml
i m sending --
ActionServlet...
ActionServlet
*.do
but i m getting error - Struts
java Hi,
I want full code for login & new registration page in struts 2
please let me know as soon as possible.
thanks,. Hi friend,
I am sending you a link. This link will help you. Please visit for more
help - Struts
help Dear friends
I visit to this web site first time.When studying on struts2.0 ,i have a error which can't solve by myself. Please give me help, thans!
information:
struts.xml
HelloWorld.jsp
Error - Struts
Error Hi,
I downloaded the roseindia first struts example and configured in eclips.
It is working fine. But when I add the new action and I... inform what is the problem here. Friends I am stuch with this. Please help me
Hi
Hi I need some help I've got my java code and am having difficulty to spot what errors there are is someone able to help
import... = new Scanner(System.in);
System.out.print("Enter the letter type: ");
String type Hi Friends,
Thanks to ur nice responce
I have sub package in the .java file please let me know how it comnpile in window xp please give the command to compile
HI!!!!!!!!!!!!!!!!!!!!!
();
}
}
CAN ANYONE HELP ME TO DESIGN A FRAME FOR THIS PROGRAMME??
...HI!!!!!!!!!!!!!!!!!!!!! import java.awt.*;
import java.sql.... createSAccount(){
JTabbedPane tp=new JTabbedPane();
panel=new
Hi
Hi I have got this code but am not totally understanding what the errors. Could someone Please help. Thanks in advance!
import java.util.Random... MatchingPair{
private static class input {
private static int nextInt() {
throw new... be greatly appreciated!!
Regards,
shruti Hi friend,
I am sending you file downloading - Struts
for this response
Hi friend,
I am sending you a link. This link...Struts file downloading how to download a file when i open a file... is not showed even i check the file size also and generating excetion Project Planning - Struts
Struts Project Planning Hi all,
I am creating a struts application.
Please suggest me following queries i have.
how do i decide how many...,
I am sending you a link. This link will help you.
Please visit for more first example - Struts
the version of struts is used struts1/struts 2.
Thanks
Hi!
I am using struts 2 for work.
Thanks. Hi friend,
Please visit...Struts first example Hi!
I have field price.
I want to check i have no any idea about struts.please tell me briefly about struts?**
Hi Friend,
You can learn struts from the given link:
Struts Tutorials
Thanks
Is there anyone out there?
Is there anyone out there? Hi please could somebody respond as I am seeking advice but not getting any and do not know whether or not to continue using this site Helloworld problem -Please help - Struts
Struts2 Helloworld problem -Please help Hi
I am a beginner...,
I am sending you a link. This link will help you.
Visit for more... in detail below and provide me a pointer in identifying the problem.
I am
Struts tag - Struts
Struts tag I am new to struts,
I have created a demo struts application in netbean,
Can any body please tell me what are the steps to add new tags to any jsp page
Reply Me - Struts
Reply Me Hi Friends,
I am new in struts please help me...; Hi Soniya,
I am sending you a link. This link will help you.
Please visit for more information.
Thanks
struts application - Struts
struts login application form code Hi, As i'm new to struts can anyone send me the coding for developing a login form application which involves a database search like checking user name in database Hi,
Here my quation is
can i have more than one validation-rules.xml files in a struts application
struts
struts i have one textbox for date field.when i selected date from datecalendar then the corresponding date will appear in textbox.i want code for this in struts.plz help me
Graphs - Struts
Graphs Hi,I have an application developed using struts framework.Now the requirement is for displaying graph in it.Can anyone help me with some code... implementation, I would suggest Google charts.
Java + struts - Struts
to mysql database. Actually i imported single workbook with two sheets of data to mysql database.Please help me as early as possible thanks in advance i used jxl jar...{
private String FilePath;
private Map formFiles = new HashMap();
public void internationalisation - Struts
struts internationalisation hi friends
i am doing struts iinternationalistaion in the site
i followed the procedure as mentioned but i am not getting
exception - Struts
exception Hi,
While try to upload the example given by you in struts I am getting the exception
javax.servlet.jsp.JspException: Cannot...:
can anybody help me
regards,
Sorna
Hi friend,
Here
could anyone please help with the code.
could anyone please help with the code. protected void doPost...(request, response);
}
}
could anyone please check the code. If i enter... the details to the bean class */
userLogin_bean obj=new userLogin_bean
Struts - Struts
Struts What is Struts Framework? Hi,Struts 1 tutorial with examples are available at Struts 2 Tutorials...:// these links will help you build | http://www.roseindia.net/tutorialhelp/comment/12849 | CC-MAIN-2015-11 | refinedweb | 1,263 | 75.1 |
Introduction
While many simple programs fit into a single C or CPP source file, any serious project is going to become far more manageable if split up into several source files. However, many beginning programmers may not realize what the point of this is - especially since some may have tried it themselves and run into so many problems that they decided it wasn't worth the effort. This article will explain why to do it, and how to do it properly. A brief explanation of how compilers and linkers work will be given where necessary, to help understand why things have to be done in a certain way.
Terminology
In this article, I will call standard C and C++ files (usually with the .C or .CPP extension) "source files". This will be to distinguish them from "header files" (usually with the .H or .HPP extension). This terminology is widely used. However,:
- Reduce time wasted on re-compilation - most compilers work on one a file at a time, and have to process the entire file..
- Allow distributed or concurrent builds – it is becoming more common for developers to use concurrent builds now, where tools such as "distcc" or "Incredibuild" make it possible for separate source files to be compiled in parallel, either on separate cores or processors on your own computer, or perhaps distributed across other computers on a network. But obviously, if you only have one source file, you can't take advantage of this.
- code-browsing time by 3/4.
- Facilitate code reuse - If your code is carefully split up into sections that operate largely independently of each other, this makes it easy to use that code in another project, saving you a lot of rewriting later. There is a lot more to writing reusable code than just using a logical approach to at the same time, without needing to duplicate. If you decide to package the shared code into a library later, it will be easier to do if it already lives in files that are separate from the individual programs.
- Split coding responsibilities among programmers - For really large projects, this is perhaps the main reason for separating code into multiple files. It isn't ideal for more than one person to be making changes to a single file at the same time. Version control software such as CVS, Subversion, or even Visual SourceSafe can help to manage this, but the further you split your code up, the less likely you are to use the same file as someone else, and therefore less likely to encounter problems having to merge or coordinate your changes with someone else's. logical sections, each handling a conceptually different part of your application. For example, you might be able to split your program up into separate subsystems or 'modules' such as sound, music, graphics, file handling, etc. You generally want one header file for every source file.
In C, you might have a header for each subsystem you identified, and a source file containing the function implementations. And occasionally a single module could be split into two or more files, because it might make sense to do so on logical grounds. For example, perhaps your sound engine would split cleanly into code dealing with sound effects and code dealing with music.
In C++ it is customary to go a bit further and put each class into its own pair of files - a header containing the class definition and a source file containing the implementation of the various methods. However, this is not really all that different from the C approach, since each class typically corresponds to one distinct area of functionality anyway.
Either way, first create new source files with meaningful filenames so that you know at a glance which class or what kind of code is in them. Then move all the code that belongs to that class or module into that file.
Once you have split it up in this way into separate source files, the next stage is to consider what will go into the corresponding variable declarations (but see below)
- constants
- #define macros
- #pragma directives
Global variable declarations differ from a typical variable definition in that they need to be preceded by the 'extern' qualifier. eg. “extern int myGlobalInt;”. This is important, but again, more on this later.
If you're using namespaces in C++, don't forget to enclose any relevant parts of your header file in that namespace, in much the same way that the functions and variables in question would be within that namespace in your source file.
These header files become the interface between your subsystems or classes. By #including a header, you gain access to all the structure definitions, function prototypes, constants etc. for that subsystem. Therefore, every source file that uses sprites in some way will probably have to #include "sprite.h", every source file that uses sound is likely to need to #include "sound.h", and so on. Note that you typically use double quotes rather than angular brackets when #including your own files. The quotes tell the compiler to look for your headers in the program directory first, rather than among the compiler's standard headers.
As mentioned earlier, as far as the compiler is concerned there is absolutely no difference between a header file and a source file, both are plain text files that are filled with code (with a small exception: some compilers will refuse to compile a header file directly, assuming that you made a mistake in asking.) the functionality provided by another source file by including the second source file's header.
As a final point of interest, sometimes you have functions that exist purely as local helpers that you won't need to access from outside that file. In C, you would prefix these functions with the 'static' modifier. In C++ if they are not methods of a class, you would enclose them in an unnamed namespace. Since these functions aren't available outside of the source file, they wouldn't form part of the interface, so you wouldn't put their function prototypes in the header. Instead place them at the top of the source file if needed. This allows the other functions in that file to see the prototypes, but keeps them hidden from other files. source files.
Typically, there are four basic errors that people encounter when they first enter the murky world of user-defined header files.
- The source files no longer compile as they can't find the functions or variables that they need. (This often manifests itself in the form of “undeclared identifier” errors,. This “chicken or egg” type of problem manifests itself at compile time in a variety of different ways, such as the compiler saying a class isn't defined when you have clearly included the relevant header, or by a class being redefined, etc.
- Duplicate definitions where a class or identifier ends up being included twice in a single source file. This is a compile time error and usually arises when multiple header files include one other header file, leading to that header being included twice when you compile a source file that uses them. (In MS Visual C++, this might look something like "error C2011: 'MyStruct' : 'struct' type redefinition.)
- Duplicate instances of objects within code that seemed to be fine when files are compiled individually. This is a linking error, and often comes with difficult to understand error messages. (In MS Visual C++, you might see something like "error LNK2005: "int myGlobal" (?myGlobal@@3HA) already defined in myotherfile.obj".)
So how do we prevent or fix these issues?
Fixing Problem 1
Luckily these issues are easy to avoid once you understand them.
The first error, where a source file refuses to compile because one of the identifiers was undeclared, is easy to resolve. Simply #include the header file that contains the definition of the identifier you need. If your header files are organized logically and named well, this should be easy. For example, if you need to use the Sprite struct or class,.
Similarly, if the situation arose where File1.cpp no longer required a ClassOne instance, removing that instance and the related #include for would cause the ClassTwo instances to stop compiling.
The key here, is to explicitly #include any header files that you need for a given source file to compile. You should never rely on header files indirectly including extra headers for you, as that status may change. The 'extra' #includes also serve as documentation, by demonstrating what other code this file is dependent on. So if you know you need that header included somehow, put the #include line in.
Fixing Problem 2
Cyclic or two-way dependencies are a common problem in software engineering. Many constructs involve a two-way link of some sort, and this implies that both classes and structures know about each other. Often this ends up looking something like this:
/* Parent.h */ #include "child.h" class Parent { Child* theChild; }; /* Child.h */ #include "parent.h" class Child { Parent* theParent; };
Given that one of these headers has to be compiled first in order for the other to compile, you need some way to break the cycle. In this case, it's actually quite trivial. The Parent class doesn't actually need to know the details of the Child class, as it only stores a pointer to one. Pointers are pretty much the same no matter what they point to, so you don't need to have the definition of the structure or class in order to store a pointer to an instance of that structure or class. So, the #include line is not actually needed here. However, simply taking it out will give you an "undeclared identifier" error when it encounters the word 'Child', as that class definition is no longer visible, so you need to let the compiler know that Child is a class or class that you wish to point to. This is done with a forward declaration, taking the form of a struct.
When using C++, it's usually preferable to use a reference wherever possible rather than a pointer, as references are less error-prone. As with pointers, a forward declaration of the class being referred to is typically all you need in the header.
In the source files, it's quite likely that there will be functions that apply to Parent that will manipulate the Child also, or vice versa. Therefore, it is probably necessary to #include both parent.h and child.h in parent.c and child.c.
Another situation where cyclic dependencies can often arise in C++ is where inline functions are defined in the header file. Inline functions are potentially faster but typically must be fully defined in the header, rather than just having a prototype (the reason for this will be explained below). However, since the inline function may need to know details of classes it operates on, this tends to mean that the header file it's in will need to #include more headers in order for the function to compile. The first piece of advice here is that you should only make functions inline when you are sure that they are too slow otherwise. If you have tested your code and certain functions absolutely need to be inlined - and thus have their definitions in the header file - try and ensure that the dependency between 2 header files is only one way by isolating the inline functions in one of the two headers., or perhaps Header3.h contains basic functionality that is used all over your program. The reason itself is not important; the point is that sometimes headers include other headers indirectly, which means that sometimes a header will end up being conceptually something like this:
For the purposes of compilation, File1.cpp ends up containing copies of Header1.h and Header2.h, both of which include their own copies of Header3.h. The resulting file, with all headers expanded inline into your original file, is known as a translation unit. Due to this inline expansion, anything declared in Header3.h is going to appear twice in this translation unit, causing an error.
So, what do you do? You can't do without Header1.h or Header2.h, since you need to access the structures declared within them. You need some way of ensuring that, no matter what, Header3.h is not going to appear twice in your File1.cpp translation unit when it gets compiled. This is where inclusion guards come in.
If you've looked at other people's code, or perhaps through your compiler's standard libraries, you may have noticed lines near the top similar to the following, taken from one compiler's 'stdlib.h':
#ifndef _INC_STDLIB #define _INC_STDLIB
And at the bottom of the file, after all the important declarations and function prototypes, here */ /* Ensure we won't get this far again */ done = true; }
This ensures that the 'do something' part only ever happens once. The same principle goes for the inclusion guards. Imagine we included the stdlib.h header described above in File1.cpp. During compilation it would reach the #ifndef line and continues because "_INC_STDLIB" is not yet defined. The very next line defines that symbol and carries on reading in stdlib.h. If stdlib.h is included again during the compilation of File1.cpp, perhaps indirectly through another header, it will read to the #ifndef check and then skip to the #endif at the end of the file, leaving out all the declarations in the middle.
Note that the symbol (in this case, "INC_FILENAME_H") needs to be unique across your project. This is why it is a good idea to incorporate the filename into the symbol. Don't add an underscore at the start like stdlib.h does, as identifiers starting with an underscore followed by a capital letter are supposed to be reserved for "the implementation" (ie. the compiler, the standard libraries, and so on). Then add the #endif /* INC_FILENAME_H */ at the end of the file. The comment is not necessary, but will help you remember what that #endif is there for.
On a related note, you may have also noticed the “#pragma once” directive used occasionally at the top of a header file. This effectively achieves the same thing as the inclusion guards, without having to worry about filenames, or adding the #endif at the bottom of the file, by saying that "for this translation unit, only include this file once". However, remember that this, as with all #pragma directives, is not standard across all compilers. Although the Visual C++ and GCC compilers support the #pragma once directive, not all do, it created during compilation, one per translation unit, and joins them together. The linker's main job is to resolve identifiers (basically, variable or function names) to machine addresses in the file. This is what links the various object files together. The problem arises when the linker finds two or more instances of a single identifier in the object files, as then it cannot determine which the 'correct' one to use is. The identifier should be unique to avoid any such ambiguity. So how come the compiler doesn't see an identifier as being duplicated, yet the linker does?
Imagine the following code, showing a global variable used in 2 files:
/*, called something like:
Notice how there are two copies of "my_global" in that final block. Although "my_global" was unique within each translation unit (this would be assured by the correct use of the inclusion guards), combining the object files generated from each translation unit would result in there being more than one instance of my_global in the file. This is flagged as an error, as the linker has no way of knowing whether these two identifiers are actually supposed to be the same one, or if one of them was just misnamed and they were actually supposed to be 2 separate variables. So you have to fix it. subtle distinction -- the first line of the function without the body:
int SomeFunction(int parameter);
Functions are considered 'extern' by default so it is customary to omit the 'extern' in a function prototype.
Of course, since variable or function. So for this example, you would add "int my_global" to either Code1.cpp or Code2.cpp, and everything should work fine. If it was a function, you'd add the function including its body actually compiled at the place of definition, but are generated and compiled as they are used by code elsewhere.
The second exception is inline functions, briefly mentioned earlier. Like template functions, inline functions are not like normal functions, but are blueprints for different code depending on how they're used. An inline function is compiled directly into the code that calls it, rather than called in the normal way. This means that any translation unit where the code 'calls' an inline function needs to be able to see the inner workings , and if you want an inline function in C++, use the 'inline' keyword. If you want a function that operates on different types in C++, use templates or overloading. But if you
- Put the interface into the header files and the implementation into the source files
- Use forward declarations wherever possible to reduce dependencies
- Add an inclusion guard to every header file you make
- Don't put code in the headers that might adversely affect source files that include it
Nice article, it remembers me of a lot of time I've wasted when not knowing this
I gave up when most of my classes ended up being templates... Im not sure if you mentioned templates but you probably should so people dont spend too much time figuring out whats wrong
@Waterlimon - see two paragraphs before "Other Considerations" section. | http://www.gamedev.net/page/resources/_/technical/general-programming/organizing-code-files-in-c-and-c-r3173 | CC-MAIN-2016-36 | refinedweb | 2,975 | 60.95 |
thank you for your answer i have a question about [[ -v $next ]] i havent tried but you say it works it would ? expand $next but wont it then check '[[ -v <content_of_next> ]]' and fail ? ill benchmark the usage of : $next ; before [[ -v now, if its minimal its all fine i can use i just remember it used to work for the [[ -v arr[++elem] ]] style i do cause i can add in the loop to the array and it continues over the new elements, till no more also i think speed wise its very good, not so sure anymore lately i also have another this-same-declare issue with a more complex data structure i have an assoc structure of two types in one array var [$id] mainly, which is coming from the same assoc array by [$keyword] ( with separators, i just simplified here ) the actual code looks around like: KWS[$kwns$_S_$[++kwstot]]=$code KWS[$kwns$_S_$kwstot$_S_]=$takes and in a loop per keyword ( $kw ) : KWS[$kwns$_S_$_S_$kw]=$kwstot KWS[$kwns$_S_$kwstot$_S_$[++elem]]=$kw $kwns is keyword_namespace, empty by default, i havent thought enough yet technics to use it, however its a must to eval the keywords: while [[ -v kws[++i] ]] && kw=${kws[i]} t=$kwns$_S_ id=${KWS[$t$_S_$kw]} code=${KWS[$t$id]} takes=${KWS[$t$id$_S_]} ; do ${code:+kwseval "$code" "${kws[@]:i:takes}" $[i+=takes]} done in fact i hope i send the three files as i am interested in an answer to: 'how can i declare -n right this issue' each of the three files represents the content of the same-as-filename named function i made a linker to map aliases functions and assoc keywords from files to .. bash .. ( id like to publish it but where, my bashhttpd isnt ready yet but soon .. ) there are three different cases in the KWS assoc array the ++id per +kw, which splits into two subelements, a 'code' key and a 'takes' key ( i didnt name em in the code anymore for only $_S_ $SUBSEP $'\34' usage instead of long mixed text and then theres the keyword in question entry that simply points to the id, for the resolver to resolve to eval its code from the structure .. i hope you didnt loose me too much yet 'how would i declare -n right the 3 (or 4) right ?' On Mon, Mar 8, 2021 at 4:30 PM Chet Ramey <chet.ramey@case.edu> wrote: > On 3/7/21 9:36 PM, Alex fxmbsw7 Ratchev wrote: > > [msg(shbot)] # foo() { declare -a foo=( "$@" ) ; declare i=-1 ; declare > -p > > foo ; declare -n next=foo[++i] > > now=foo[i] ; while [[ -v next ]] ; do : $now ; done ; printf -- $i ; } ; > > foo '' 1 2 3 > > [shbot(~shbot@37.139.2.101)] declare -a foo=([0]="" [1]="1" [2]="2" > [3]="3") > > [shbot(~shbot@37.139.2.101)] -1 > > This report would have been better sent to help-bash. > > It's a misunderstanding about how namerefs work. They're not like cpp > macros or some kind of recursive variable expansion; they make one variable > name stand for another. > > In your example, you have next='foo[++i]'. When you run [[ -v next ]], the > nameref gets expanded and the shell looks for a variable named 'foo[++i]'. > This naturally fails, and the loop terminates. > > If you want to iterate through the values of the array, you're better off > ditching namerefs and using `eval' or [[ -v $next ]] (if you want to > maintain the same code structure) or some other construct. It would be much > clearer to simply use a for loop to iterate from 0 to ${#foo[@]}. > > -- > ``The lyf so short, the craft so long to lerne.'' - Chaucer > ``Ars longa, vita brevis'' - Hippocrates > Chet Ramey, UTech, CWRU chet@case.edu >
+kw
Description: Binary data
kwseval
Description: Binary data
kws
Description: Binary data | https://lists.gnu.org/archive/html/bug-bash/2021-03/msg00023.html | CC-MAIN-2022-33 | refinedweb | 640 | 59.98 |
--- address@hidden wrote: > (I'm not at home, but from a cafe ... so excuse the ^Ms) > > > > C# Attributes ? > > > > Sounds interesting. > > That is how you are handling native calls now? (sorry I have not > been > > following this closly) > > [MethodImpl(...)] And the attributes are evaluated at compile time? This is a very powerfull method, then via reflection the attributs of the class are also available? Ok well then you can use whatever is provided by reflection to inspect the class and generate code. I will have to check out the source code, months ago you guys were fighting with attributes... > > We could do something like > > [XmlSerializable] > public struct LoginInfo > { > String sessionid; > DateTime expireOn; > } > > public class MyWebServicelet : WebServicelet > { > // implements GetMethods() automatically > [Webservice(Allow=WebserviceVisibility.All)] > public static LoginInfo Login(String username,String passwd) > { > /// Implement the Call > } > } > > > Store this in a container which accepts XmlRpc calls and > calls Login via Reflection (Method.Invoke()) and all that. > In the future allow it to be called via SOAP or jabberMiddle > or stuff .. Now, here is something crazy : but if I can call it via perl or an existing module, we could use the entire mod_perl and modules for now.... The same goes for java. Of course you will say that it is a suboptimal solution. it has to be simple, standalong and easy. But if you had a simple pnet module that could be used in existing perl, java, python modules, then you will find many people willing to use and expand on it. There might not be enough man power to keep up an entire development effort, but to create a client module so that you can embed pnet inside another system, that would be great. Given that pnet is kept so small and with so few dependancies, it just might be simple to create a pluggable runtime. Even if you had to give it time with a scheduler system, threads are one thing, but if you just want to call a CLI-runtime call to something, and wait for it to return, then should it be able to do without threading? > I can implement this as an ordinary WebServer in a period > of 3 months or so ... But I've commited myself to working > on the compiler (see WW stuff) .... > > > Good point : > > > > Many people use tomcat/apache jserv. > > The less people have to learn, and the more the feel at home, the > more > > likely the will feel inclined to switch over and try it. > > > > my 2 euro cents > > Me feels the same ... But we have to find a way to run libgc inside > Apache ... (how does mod_haydn work ?) Lib garbage collection, you mean to have multiple instances of it, one for each process? Hmmm..... This is over my head. I have encountered libg in the compiler, it tracks what memory you give it, I am not sure how thread safe it is, but if each user ran in its own process..... I dont know. mike ===== James Michael DuPont __________________________________________________ Do you Yahoo!? Faith Hill - Exclusive Performances, Videos & More | http://lists.gnu.org/archive/html/dotgnu-general/2002-10/msg00107.html | CC-MAIN-2016-07 | refinedweb | 504 | 73.27 |
Red Hat Bugzilla – Bug 457708
Missing Requires: gnome-python2-gconf
Last modified: 2013-07-02 19:30:24 EDT
Description of problem:
$ postr
Traceback (most recent call last):
File "/usr/bin/postr", line 32, in <module>
from postr import postr
File "/usr/lib/python2.5/site-packages/postr/postr.py", line 23, in <module>
import gobject, gtk, gtk.glade, gconf
ImportError: No module named gconf
Version-Release number of selected component (if applicable):
postr-0.12-1.fc8.1.noarch
How reproducible:
Always
Steps to Reproduce:
1. Run postr without gnome-python2-gconf installed
2.
3.
Actual results:
Traceback.
Expected results:
postr works
Additional info:
Likely affects F9 as well as rawhide.
i have added missing gnome-python2-gconf requirement to the spec.
postr-0.12.2-1.fc9 has been submitted as an update for Fedora 9.
postr-0.12.2-1.fc9 has been pushed to the Fedora 9 stable repository. If problems still persist, please make note of it in this bug report. | https://bugzilla.redhat.com/show_bug.cgi?id=457708 | CC-MAIN-2017-39 | refinedweb | 166 | 59.7 |
Tell us what you think of the site.
Hi Everyone
I’m just fustrated by selection and things like that. In Maya it seems so simple. It might be because in Maya MEL everything in connection with objects’ names and attributes are strings. In MotionBuilder Pyhton those are classes. As far as I understand if I want to for eg. delete an object first of all I have to know what its class is and whether there is a class function like delete. If there is no delete function I have to find the upper class which have the delete function.
So the question arisen whether are Global Functions in MotionBuilder (pyfbsdk) I mean independently from classes like ls (list) in Maya. Ok it might be stupid question. The help file doesn’t describe things like that at all.
So one current problem.
I’m searching the easiest way to get the selected objects’ names.
Thanks
Hi,
if you like Maya syntax, try pymobu library for Python -
It seems very interesting. I haven’t tried yet but I checked the link and the examples. Pymobu is very promising. Great effort! I hope 1.0 is coming soon :)
Hey man ..
I know its frustrating .. But i still lean to the traditional Mobu way of getting names or objects inside Mobu selected objects .. so..here..
from pyfbsdk import FBGetSelectedModels
# FBLlist instance
lModels = FBModelList()
# get the selected models in the scene
FBGetSelectedModels(lModels)
# get me my names ..
print[obj.Name for obj in lModels]
# or the more traditional way
for obj in lModels:
print obj.Name
# both should work ..:) ...let me know if that helps..Not Maya i know but you get used to it.:)
Cheers
Melvin3d
Thanks, it is useful.
I still have the feeling something wrong with the documentation MotionBuilder SDK Help. The FBGetSelectedModels function is a good example. If I try to find what this function does I have to go through a lot of search result pages find it at the end of doc File List / pyfbsdk.h.
I have to stress I would never found this function if somebody hadn’t told me that. | http://area.autodesk.com/forum/autodesk-motionbuilder/python/selection-list-etc-global-functions/ | crawl-003 | refinedweb | 356 | 76.82 |
a library for controlling certain robot vacuums
Project description
A simple command-line python script to drive a robot vacuum. Currently known to work with the Ecovacs Deebot N79, M80 Pro, M81, M88 Pro, and R95 MKII from both North America and Europe.
Does it work for your model as well? Join the discussion on the sucks-users mailing list.
If you’re curious about the protocol, I have a rough doc started. I’ll happily accept pull requests for it.
Why the project name? Well, a) it’s ridiculous that I needed to MITM my own vacuum. This is not the future I signed up for. And b), it’s a vacuum.
Installation
If you have a recent version of Python 3, you should be able to do pip install sucks to get the most recently released version of this.
Usage
To get started, you’ll need to have already set up an EcoVacs account using your smartphone.
With that ready, step one is to log in:
% sucks login Ecovacs app email: [your email] Ecovacs app password: [your password] your two-letter country code: us your two-letter continent code: na Config saved.
That creates a config file in a platform-appropriate place. The password is hashed before saving, so it’s reasonably safe. (If it doesn’t appear to work for your continent, try “ww”, their world-wide catchall.)
With that set up, you could have it clean in auto mode for 10 minutes and return to its charger:
% sucks clean 10
You could have it clean for 15 minutes and then do an extra 10 minutes of edging:
% sucks clean 15 edge 10
If you wanted it to clean for 5 minutes and then stop without charging:
% sucks clean 5 stop
If it’s running amok and you’d just like it to stop where it is:
% sucks stop
To tell it to go plug in:
% sucks charge
I run mine from my crontab, but I didn’t want it to clean every day, so it also has a mode where it randomly decides to run or not based on a frequency you give it. My crontab entry looks like this:
0 10 * * * /home/william/projects/sucks/sucks.sh clean -f 4/7 15 edge -f 1/14 10
This means that every day at 10 am, it might do something. 4 days out of 7, it will do 15 minutes of automatic cleaning. 1 day out of 14, it will do 10 minutes of edging. And afterward it will always go back to charge.
Library use
You are welcome to try using this as a python library for other efforts. The API is still experimental, so expect changes. Please join the mailing list to participate in shaping the API.
A simple usage might go something like this:
import sucks config = ... api = EcoVacsAPI(config['device_id'], config['email'], config['password_hash'], config['country'], config['continent']) my_vac = api.devices()[0] vacbot = VacBot(api.uid, api.REALM, api.resource, api.user_access_token, my_vac, config['continent']) vacbot.connect_and_wait_until_ready() vacbot.run(Clean()) # start cleaning time.sleep(900) # clean for 15 minutes vacbot.run(Charge()) # return to the charger
Developing
If you’d like to join in on developing, I recommend checking out the code, setting up a virtual environment, and installing this package in editable mode. You can confirm your environment works by running the tests. And please do join the mailing list to discuss your plans.
For more information see the development documentation.
See also
There are now similar libraries in Javascript and Go.
Thanks
My heartfelt thanks to:
- xmpppeek, a great library for examining XMPP traffic flows (yes, your vacuum speaks Jabbber!),
- mitmproxy, a fantastic tool for analyzing HTTPS,
- click, a wonderfully complete and thoughtful library for making Python command-line interfaces,
- requests, a polished Python library for HTTP requests,
- Decompilers online, which was very helpful in figuring out what the Android app was up to,
- Albert Louw, who was kind enough to post code from his own experiments with his device, and
- All the users who have given useful feedback and contributed code!
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/sucks/ | CC-MAIN-2020-10 | refinedweb | 709 | 63.09 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.