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 |
|---|---|---|---|---|---|
Has your Employees Provident Fund (EPF) account been lying idle for over 36 months? Now you can continue to earn interest on it, suggests a report in ToI. According to the report, the Labour Ministry has come up with a new notification on November 11, which states that an individual can continue earning interest on his/her EPF account even if it has been inoperative for 36 months or more. The notification reportedly states that an EPF account will continue to be seen as operative even if employment is terminated. The account holder will earn interest unless he/she seeks to withdraw the accumulated amount, or joins another job in 2 months. In case a new job is taken up, and the new employer is covered under the EPF scheme, then the old account can be transferred under the new employment.
Earlier, if you quit your job and did not take up employment till 2 months, or did not transfer your account to the new employment, then the account was considered dormant after 36 months, and hence failed to earn interest. With the new notification, this provision has been done away with.
Also read: EPFO’s UAN 2.0 in the works; here are 10 things you should know
The Employees’ Provident Fund Organisation (EPFO) is in the process of implementing the next version of Universal Account Number (UAN) or UAN 2.0. The UAN programme was initiated in 2014 to allot a single number to members which would be used for EPF purposes for all employments. According to the EPFO, the next version of UAN being worked on would involve generation and linking of UAN of members in his various employments and its integration with next version of Electronic challan-cum-return (ECR) and Pradhan Mantri Rojgar Protsahan Yojana (PMRPY) scheme.
Earlier, in two back-to-back moves as a follow-up of a meeting with Prime Minister, Narendra Modi, the EPFO has sought to substantially ease the income security for post-retirement years of its members, and their families. Firstly, the Central Provident Fund Commissioners (CPFC), V P Joy, who heads EPFO, issued instructions to all its officers to ensure that provident fund dues in case of death claims are cleared within 7 days of the claim being lodged. This was quickly followed by another set of instruction by the CPFC that “PF claim settlement amount must invariably be credited to the member accounts on or before the date of retirement.” | http://www.financialexpress.com/industry/banking-finance/big-cheer-for-common-man-epf-accounts-idle-for-over-36-months-to-now-earn-interest/447008/ | CC-MAIN-2017-26 | refinedweb | 413 | 52.73 |
Dispatch to functor vtkDataArrayType. More...
#include <vtkDataArrayDispatcher.h>
Dispatch to functor vtkDataArrayType.
vtkDataArrayDispatcher is a class that allows calling a functor based on the data type of the vtkDataArray subclass. This is a wrapper around the vtkTemplateMacro (VTK_TT) to allow easier implementation and readability, while at the same time the ability to use statefull functors.
Note: By default the return type is void. Note: The functor parameter must be of type vtkDataArrayDispatcherPointer
The functors that are passed around can contain state, and are allowed to be const or non const. If you are using a functor that does have state, make sure your copy constructor is correct.
Definition at line 91 of file vtkDataArrayDispatcher.h.
Specify the functor that is to be used when dispatching.
This allows you to specify a statefull functor.
Definition at line 143 of file vtkDataArrayDispatcher.h.
Default constructor which will create an instance of the DefaultFunctorType and use that single instance for all calls.
Definition at line 154 of file vtkDataArrayDispatcher.h.
Definition at line 164 of file vtkDataArrayDispatcher.h.
Execute the default functor with the passed in vtkDataArray;.
Definition at line 175 of file vtkDataArrayDispatcher.h.
Definition at line 134 of file vtkDataArrayDispatcher.h.
Definition at line 135 of file vtkDataArrayDispatcher.h. | https://vtk.org/doc/nightly/html/classvtkDataArrayDispatcher.html | CC-MAIN-2020-45 | refinedweb | 208 | 51.75 |
For original post please refer to good (or bad), missing a feature that everybody is craving for, the odds are you are going to get few number of reviews.
You can increase the chances to get feedback from users by reminding them to do so. But you have to take care not to be too nagging, to the extent to push them away from your app.
Here is how you can do it. (all code is in the main page of your application).
First we need a couple of member variables/references to local and roaming storage where we are going to save a setting whether we should ask the user for feedback or not.
It's a good idea to check for Internet connectivity before asking the user to submit his feedback, obviously he won't be able to access the store app to do so, if there is no connectivity.
For this I use the following method.
The following are helper methods to save and read the setting from local/roaming storage.
I write to both storage, you might opt for using only one of them, and when reading back data, I read first from the local storage, and if not found I attempt to read from the roaming one.
private bool ReadAppRatingSetting(){ if (_localData.Values["AppRatingDone"] != null) return (bool)_localData.Values["AppRatingDone"]; if (_roamingData.Values["AppRatingDone"] != null) return (bool)_roamingData.Values["AppRatingDone"]; return false;}private void SaveAppRatingSetting(){ // for this setting, it's either saved or not, so we save true as the default value _localData.Values["AppRatingDone"] = true; _roamingData.Values["AppRatingDone"] = true;
}
And here is the main method which displays the popup dialog which asks the user for feedback, and act accordingly.
private async Task AskForAppRating(){ if (!CheckInternetConnectivity()) return; if (ReadAppRatingSetting()) return; MessageDialog msg; bool retry = false; msg = new MessageDialog("Kindly, help us provide a better service, would you like to review & rate \"THIS APP\"?");(); while (retry) { try{ await msg.ShowAsync();} catch (Exception ex){} }}private void IgnoreRating(IUICommand command){ SaveAppRatingSetting();}// Launches the store app, using the application storeIDprivate async void OpenStoreRating(IUICommand command){ await Windows.System.Launcher.LaunchUriAsync(newUri("ms-windows-store:REVIEW?PFN=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"));
SaveAppRatingSetting();
Finally you will need to call AskForAppRating() at the end of the LoadState() method, or any other event fired after page is loaded. | http://blogs.msdn.com/b/egtechtalk/archive/2013/09/03/how-to-include-quot-rate-amp-review-quot-api-in-your-windows-8-apps-by-walaa-atef.aspx | CC-MAIN-2015-48 | refinedweb | 386 | 55.44 |
Up to [cvs.NetBSD.org] / src / etc
Request diff between arbitrary revisions
Default branch: MAIN
Current tag: CSRG
Revision 1.1.1.2 / (download) - annotate - [select for diffs] (vendor branch), Sat Feb 15 05:27:28 1997 UTC (22 years, 8 months ago) by mikel
Branch: WFJ-920714, CSRG
CVS Tags: lite-2, lite-1
Changes since 1.1.1.1: +1 -1 lines
Diff to previous 1.1.1.1 (colored)
import 4.4BSD-Lite
Revision 1.1.1.1 / (download) - annotate - [select for diffs] (vendor branch), Sun Mar 21 09:45:37 1993 UTC (26 years, 7 months ago) by cgd
Branch: WFJ-920714, CSRG
CVS Tags: patchkit-0-2-2, netbsd-alpha. | http://cvsweb.netbsd.org/bsdweb.cgi/src/etc/dm.conf?only_with_tag=CSRG | CC-MAIN-2019-43 | refinedweb | 115 | 75.81 |
On Mon, Apr 23, 2012 at 9:51 AM, Michael Foord <fuzzyman at gmail.com> wrote: > On 19 April 2012 21:18, Eric V. Smith <eric at trueblade. >> > >?) <lib_dir>/site-packages/foo/bar <lib_dir>/site-packages/foo/baz The whole point of dropping the __init__.py file requirement is that merging the namespace portions becomes trivial, so you don't need to worry about sys.path hackery in the normal case - you can just install them into a common directory (adding it on install if it doesn't exist yet, removing it on uninstall if the only remaining contents are the __pycache__ subdirectory). However, for zipfile distribution, or running from a source checkout, you could instead provide them as <app_dir>/foo/bar and <app_dir>/foo/baz and they would still be accessible as "foo.bar" and "foo.baz". Basically, PEP 420 should mean that managing subpackages and submodules becomes a *lot* more like managing top level packages and modules. Agreed the packaging implications should be specified clearly in the PEP, though (especially the install/uninstall behaviour when namespace portions get merged into a single directory). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia | https://mail.python.org/pipermail/import-sig/2012-April/000476.html | CC-MAIN-2014-15 | refinedweb | 195 | 56.96 |
So I'm trying to create a "dynamic" docstring which is something like this:
ANIMAL_TYPES = ["mammals", "reptiles", "other"]
def func(animalType):
""" This is a sample function.
@param animalType: "It takes one of these animal types %s" % ANIMAL_TYPES
"""
@param animalType
ANIMAL_TYPES
Class MyClass:
MY_CONST = ['A', 'B']
def func(self, choice):
""" some text`
:param choice: can be one of %s
"""
func.__doc__ %= MY_CONST
Triple-quoted strings are one big string. Nothing is evaluated inside them. The
% part is all part of the string. You'd need to have it operating on the actual string.
def func(animalType): """ This is a sample function. @param animalType: "It takes one of these animal types %(ANIMAL_TYPES)s" """ % {'ANIMAL_TYPES': ANIMAL_TYPES}
I'm not certain this will work properly, though; docstrings are a bit magic.
This will not work; the docstring is evaluated at compile time (as the first statement in the function, given it is a string literal—once it's got the
% in it it's not just a string literal), string formatting takes place at runtime, so
__doc__ will be empty:
>>> def a(): 'docstring works' ... >>> a.__doc__ 'docstring works' >>> def b(): "formatted docstring doesn't work %s" % ':-(' ... >>> b.__doc__ >>>
If you wanted to work this way, you'd need to do
func.__doc__ %= {'ANIMAL_TYPES': ANIMAL_TYPES} after the function is defined. Be aware that this would then break on
python -OO if you didn't check that
__doc__ was defined, as
-OO strips docstrings.
>>> def c(): "formatted docstring works %s" ... >>> c.__doc__ "formatted docstring works %s" >>> c.__doc__ %= 'after' >>> c.__doc__ "formatted docstring works after"
This is not the standard technique anyway; the standard technique is to reference the appropriate constant: "Takes one of the animal types in ANIMAL_TYPES", or similar. | https://codedump.io/share/2mm1CCa2BFVC/1/how-to-put-a-variable-into-python-docstring | CC-MAIN-2017-43 | refinedweb | 285 | 64.2 |
Content negotiation in Jersey
By manveen on Feb 14, 2008
Jersey serializes JAXB beans as JSON (BadgerFish convention) or XML.
Lets say I have an implementation of my service as below,
@UriTemplate("/myresource/") public class MyResource { @HttpMethod @ProduceMime({"application/xml", "application/json"}) public JAXBBean get() { JAXBBean j = ... return j; } }
What do you have to do in your client to get the result in JSON format?
Jersey uses HTTP headers to determine value returned: If there is no accept header or the accept is "\*", "application/\*" or "application/xml" then the JAXB bean will be serialized as XML. If the accept header is "application/json" then the JAXB bean will be serialized as JSON. Content negotiation is done solely through the HTTP Accept header.
Another tip?
For testing from a browser try the Firefox add-on Poster. It let's you specify the HTTP method, set HTTP request headers and send arbitrary content in the body of requests. | https://blogs.oracle.com/manveen/tags/jersey | CC-MAIN-2016-26 | refinedweb | 156 | 52.7 |
I’ve received several emails from readers who have had trouble running code from the ActionScript 3.0 Bible. You can find a step-by-step guide to running example code in the Introduction to that book. We all know that a picture is worth a thousand words, but friends, we are living in the HD age, and pictures are boring us to tears. Today’s sophisticated audience demands excitement, explosions, underwater scenes, bullet time, pole dances, and THX certified sound! So to provide a gripping emotional connection with my readers, I here provide video tutorials on how to build examples from the book (in under 5 minutes!). First, using Flash CS3, then using Flex Builder 3. Pow! Boom! Kachow!
See how to run example code using Flash | See how to run example code using Flex Builder
Those seem like they would be really helpful for new developers. You should do more instructional videos if you have the time. You’re good at it.
Thanks Jason!
In the Flash video, the dialog that comes at 3:43 up warns us that Flash couldn’t find the definition of the class Example. This happens because it can’t find com/wiley/as3bible/Example.as, because we haven’t yet saved the FLA to the right location. If you saved the FLA to the right place before entering anything in the Document class field, you would not see that warning when entering it in, because it would find the corresponding file right away.
In the Flex video, if you are really attentive you might notice that I changed some of the code. I did not resize the textfield to be the same size as the stage, because the stage property is not available in AS3 display objects until the Event.ADDED_TO_STAGE event is fired, an idiosyncrasy that at one point trips up everyone new to AS3, myself included. Remember that stage is now a property of each display object and not global, and that you can’t be guaranteed a non-null value until after Event.ADDED_TO_STAGE is fired. Beware!
Great Book but,
Is there anywhere where we can get the miles of source code published in the book but not available in the download source.
Chapter 33 is a good example.
It’s frustrating that long examples have to be typed in by hand.
Todd,
The code samples are available on the wiley website.
Check this post:
Furthermore, Wiley has linked to this blog post on the book site but you probably know that since you’re reading this.
Thanks this video helped out a lot but I have a question about the code. I have another question about running some of the code. In the files for Chap 12_2 and Chap 12_3 how are we suppose to run these? What links them together?
Many Thanks!!
Mike
The code in chapter27 exercise is giving me multiple errors.
will you please double check, triple check that coding I have copy and followed your steps, but I still can not get the app to execute.
Thanks
J.
My comment is the same as Mike.
I can follow the video but don’t know how to incorporate the code from 12_2 and 12_3.
Hi Steve, Mike, Jeremiah,
I’m forwarding your concerns to our publisher who can help coordinate with the author of that chapter to get things straightened out. In the meantime, the best thing you can do is fill out an Errata form on the Wiley website.
Thanks!
Mims
Regarding code for Chap 12_2 and 12_3 (I think you’re referring to the StageListenerSprit and StageTestProject scripts?)
It isn’t too clear in the text. I was able to get it to work by saving the StageTestProject class as a package in the same directory as the StageListenerSprite package. I had to add the fully qualified path and that it extends Sprite to the beginning of the file. Both packages then reside in the same com.wiley.as3bible folder:
So for example, StageListenerSprite’s code would begin with:
package com.wiley.as3bible
{
import flash.display.Sprite;
import flash.events.Event;
public class StageListenerSprite extends Sprite
…etc…
and the StageTestProject package/class would begin with:
package com.wiley.as3bible
{
import flash.display.Sprite
// you need this because StageTestProject extends Sprite
public class StageTestProject extends Sprite
…etc…
Then, in your FLA file, in the Document Class field, you would enter:
com.wiley.as3bible.StageTestProject
as your document class, so it will be the first thing to run when you run your movie. StageTestProject will look for the StageListenerSprite class in the same directory (com.wiley.as3bible) to access its function.
The output once it all is hooked up would be:
after the constructor is called the stage = null
(since nothing was added to the stage yet, so the stage/display list is null)
0
(since adding an item to the display list now creates a stage so it is no longer null)
0
(since removing an item doesn’t remove the display list so the stage still exists)
I got to this conclusion because both StageListenerSprite and StageTestProject are listed as public classes so they would need to reside in separate packages (files) because including them in the same file produces the error:
5006: An ActionScript file can not have more than one externally visible definition: com.wiley.as3bible.StageListenerSprite com.wiley.as3bible.StageTestProject
Hi Roger,
Happy X’mas and Happy New Year to all of you!!
I had been working with AS2.0, till recently. But now I have been reading your book and trying the AS3Bible – examples as per the instructions.
I am storing class files in com.wiley.ac3bible and flash documents outside com, but for every program that i run i get only blank swf file, when debugged it gives only message that
“A definition for the document class could not found in the ckasspath, so one will automatically generated in the SWF file upon export”
I have flash player 9 (debug version) only flash files work but class files dont.
Is it required to set the classpath? How??
Kindly help me out.
You have written the book nicely, the language is so down-to-earth, easy to understand and you have made tedious topics quite interesting to read !!
Hope I will get the required hints from you.
Regards to Mims and Joushua too.
Satish
Bangalore/India.
Hi everybody! Im at the page 13 (Overriding variables) and i have no idea to run this code:
package {
public class Local {
public var a:String = “instance”;
public var b:String = “instance”;
public function method():void {
var a:String = “function”;
b = “function”;
trace(a);
trace(b);
}
}
}
Please help me run this (i can’t run any code in this book except the Hello World example – same problem with the downloaded codes)
Please HEEEELP!!!
Can anyone explain step-by-step how to accomplish it?
Thank you!! | http://dispatchevent.org/roger/building-and-running-as3-bible-examples/ | crawl-002 | refinedweb | 1,152 | 70.33 |
Hello,
is it somehow possible to draw a map on a dashboard without having to get an mapbox-key?
I would like to use my own custom shapefiles or use openstreetmap-data.
Thanks in advance &
kind regards
Hello,
is it somehow possible to draw a map on a dashboard without having to get an mapbox-key?
I would like to use my own custom shapefiles or use openstreetmap-data.
Thanks in advance &
kind regards
If you work with shapefiles, you will probably need Shapely. And maybe also Cartopy.
To embed images in a Dash component, this answer and this thread might be useful.
See also:
Hi! Can you solve this? Is there any code example?
Thank you.
As I can see, this resources are not interactive as Mapbox (mouse hover, click actions, etc…). Am I right?
Thank you!
@masio_gelp You’re right: if you don’t use mapbox (or perhaps Google Maps), then your maps will be mostly static. users can hover over datapoints to get values, but can’t pan/zoom.
Here’s an example of a ScatterPlot Plotly plot which can quickly be turned into a full Plotly Dash app:
You can turn this (or any) Plotly example into Plotly Dash app by adding this code before the example code:
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd app = dash.Dash()
And then at the end of a Plotly example where you see code like
py.iplot( fig, filename='some_name' ), just replace it with these lines:
app.layout = html.Div([ dcc.Graph(id='graph', figure=fig) ]) if __name__ == '__main__': app.run_server(debug=True)
We’re working on adding the ability to use alternative tileservers in
scattermapbox (e.g. open street map instead of mapbox). I’ll keep this thread updated with progress
Would love to see alternatives to MapBox. OSM is a great free alternative. Can’t wait to see it getting implemented and using it in my website.
I would also like to see OpenStreetMap maps as an optional tileserver for the mapboxes. Any updates?
Yup! This was improved in July thanks to a customer that sponsored the development of this open source feature. See for the new options.
It is not working for images.
mapbox_layers do work with
sourcetype = 'image'. A detailed example is given as answer to your opened issue on plotly.py: .
Dash Leaflet supports any tile provider, i.e. also OSM, and it includes support for drawing polygons as well | https://community.plotly.com/t/adding-maps-without-using-mapbox/9584 | CC-MAIN-2021-25 | refinedweb | 413 | 67.25 |
19 July 2010 07:40 [Source: ICIS news]
By Nurluqman Suratman
SINGAPORE (ICIS news)--South Korean polymer producer Honam Petrochemical was able to get a reasonable price for its acquisition of Malaysian polyethylene (PE) major Titan Chemicals at more than seven times its earnings, analysts said on Monday.
Honam agreed on 16 July to buy 72.2%, or 1.25bn shares, of Titan from the Chao Group of ?xml:namespace>
The company expects to get full ownership of Titan by November, with a total investment of about $1.3bn, marking its first venture into the southeast Asian country.
“A lot of people think that the Titan deal is good for the company as the price is not too expensive,” said Kim Jae Joong, an analyst with brokerage Woori Investments and Securities in
.
Honam produces synthetic resins, basic petrochemicals, basic chemicals and performance polymers, and has an ethylene capacity of 1.75m tonnes/year.
Titan, an integrated olefins and polyolefins producer, runs a 285,000 tonne/year No 1 cracker and a 435,000 tonne/year No 2 cracker at
In Indonesia, Titan has a polyethylene capacity of 450,000 tonnes/year, which was included in the sale to Honam.
The Malaysian company would likely post a flat earnings per share (EPS) of M$0.31 this year, analysts said, although the first six months saw its net profit slump 45% to M$172.6m due to poor margins. In 2009, the company posted a net profit of M$237.8m with revenues at M$5.6bn ($1.73bn).
The acquisition of Titan would help Honam tap into the southeast Asian market, where demand for petrochemicals was booming, said Lee Hee-Cheol, an analyst with brokerage firm Hi Investment & Securities.
“[Honam is] going to look at further changes, and may contact other petrochemical producers in southeast Asia to see how they can work with them through Titan,” said Kim of Woori Investments.
Honam was also eyeing potential acquisitions in the
Titan would start contributing to Honam’s bottom line by the end of January in 2011, said Lee of Hi Investment & Securities.
Based on a consensus forecast from analysts, Honam would register W210bn in operating profit in the second quarter, down from W246bn due to weaker chemical prices.
Honam is to announce its financial results in mid-August.
($1= €0.77/$1=W1,217/$1 = M$3.23) | http://www.icis.com/Articles/2010/07/19/9377336/titan-price-tag-reasonable-for-s-koreas-honam-analysts.html | CC-MAIN-2014-10 | refinedweb | 397 | 60.45 |
Type: Posts; User: 2kaud
?...
Nice - using &*
The underlying issue is with .end() which doesn't seem to be as expected. But using the &* trick you can remove the need to construct the string, giving just:
inline auto...
Even simpler:
#include <string_view>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <ranges>
That code doesn't compile with any of the compilers used with godbolt (gcc/clang et al)... However I'm not convinced that the compilers are currently totally conforming for std::ranges.
From MSDN:
This compiles OK:
#include <string_view>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <sstream>
#include <iomanip>
[Also asked here ]
2) Yes. see std:chrono.
Note that strtok changes the data and cannot be nested. It needs to be used with std::string::data() (C++17 and later only) as it is a c function.. | https://forums.codeguru.com/search.php?s=44fccc4bb0a109d68ee73c6bda543eb9&searchid=22105998 | CC-MAIN-2021-43 | refinedweb | 138 | 56.96 |
10 Things you should know about react
- What is React?
React is a popular javascript library. Day by day its popularity is increasing. Because it shortens the time and increases the efficiency of code. It creates a pipeline for the frontend only. But you can use it with the backend easily.
2. Create React app:
If you want to do a project with react you must create a react app. For this, you must operate some command. For this, you must have npm and the latest node version on your computer. Then you will go to your drive and run this command by command prompt or vs code.
npx create-react-app my-app
cd my-app
npm start
Here my-app is your project folder. You can change your project folder name as your wish.
3. Introducing JSX:
Actually, react doesn’t work as plain javascript. It uses some different but interesting way to use javascript. Which called JSX.
JSX means javascript XML. It allows us to write HTML in react. It also allows us to add any type of components in javascript without createElement() and appendChild()
Again the syntax of JSX is different than simple HTML.Such as
Input:
import React from 'react';
import ReactDOM from 'react-dom';
const myelement = <h1>I Love JSX!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
Output:
I Love JSX!
4. Components :
Components are like javascript functions that return HTML elements.There are two types of components in react. Class components and function components.
Create a Class component called
Car
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Create a Function component called
Car
function Car() {
return <h2>Hi, I am also a Car!</h2>;
}
5. Props:
Props are that which used to pass data through components. It works like function arguments in JavaScript and attributes in HTML.
const myelement = <Car brand="Ford" />;
Here <Car/> is a component which is called in myelement. And an argument brand has been passed through <Car/> component. Hence this argument will be accessed in the <Car /> component.
6. React Events:
Just like javascript events react has many events like onClick, mouseOver etc. The main difference between javascript events and react events is their syntax. In javascript then event onclick is right but in react it is written in camelCase. like onClick.
import React from 'react';
import ReactDOM from 'react-dom';
function shoot() {
alert("Great Shot!");
}
const myelement = (
<button onClick={shoot}>Take the shot!</button>
);
ReactDOM.render(myelement, document.getElementById('root'));
7. React Style :
There are many ways to include CSS in react components.
** The first one is inline CSS which will be written like an object. Such as -
<h1 style={{color: "red"}}>Hello Style!</h1>
** The second method is to create a style object in the main function.
class MyHeader extends React.Component {
render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
** The third method is to create a style.css file in the same folder and access it. Such as -
import “./style.css”;
8. React SASS :
It is a CSS preprocessor. Sass files are executed on the server and send CSS to the browser.If you use the
create-react-app in your project, you can easily install and use Sass in your React projects.
Install Sass by running this command in your terminal:
C:\Users\Your Name>npm install node-sass
Now you are ready to include Sass files in your project!
Example:
$myColor: red;
h1 {
color: $myColor;
} | https://asif-eee-cu.medium.com/10-things-you-should-know-about-react-65f147db69?source=post_internal_links---------4---------------------------- | CC-MAIN-2021-39 | refinedweb | 596 | 69.07 |
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Servlets
Author
Html in serlets for ajax apps?
shaf maff
Ranch Hand
Joined: Sep 07, 2008
Posts: 180
posted
Jan 14, 2009 10:01:36
0
Hi Guys
I am in need of some advice, I am working on an ajax app. At the moment when I want to retrieve some html I have it hard coded into the
servlet
and simply print that out to the xml. See example below:
if(strtype.equals("home")) {<div class=\"differentcorners\"><h1>Overview</h1></div><div id=\"TitlePadding2\">"
+ "<div id=\"OverviewCreditFormat\">Credit: £" + credit
+ "<input type=\"button\" value=\"TopUp Now\" class=\"creditBtn\"/></div><div id=\"OverviewTblColor\">"
+ "<div id=\"Alerts\">Alerts</div><form action=\"#\" id=\"OverviewForm\">";
out.println(Html);
}
My question, is the good practise ? Is there a better way of handling html in ajax applications ? As you can see from the above example I have a credit variable which has the amount of credit, so I am placing variables into the html before printing. I know presentation should be seperate from logic but the line has been blurred in ajax (well, for me atleast).
.
Omar Al Kababji
Ranch Hand
Joined: Jan 13, 2009
Posts: 357
posted
Jan 14, 2009 11:04:50
0
You can put your code in a
JSP
since the JSP will be translated to a Servlet at the end. this is much faster and you will be able to modify it when needed without the need to redeploy the application.
(peace)
Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% -
Story
] [SCWCD - 94% -
Story
] [SCBCD - 80% -
Story
] |
My Blog
Ben Souther
Sheriff
Joined: Dec 11, 2004
Posts: 13410
I like...
posted
Jan 14, 2009 13:36:22
0
The best practice is to handle the request from your servlet and then forward to a JSP to build the HTML.
If you look up MVC (Model, View, Controller) you will find several explanations and tutorials.
Java API
J2EE API
Servlet Spec
JSP Spec
How to ask a question...
Simple Servlet Examples
jsonf
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 63529
72
I like...
posted
Jan 14, 2009 14:28:05
0
And just because it's an Ajax request doesn't make MVC any less useful*. Remember, a JSP
does not have to be a complete HTML page*.
A JSP can return whatever HTML fragment is appropriate for the response.
* This appears to be a common misconception.
[
Asking smart questions
] [
About Bear
] [
Books by Bear
]
Omar Al Kababji
Ranch Hand
Joined: Jan 13, 2009
Posts: 357
posted
Jan 14, 2009 14:51:31
0
Regarding using a JSP as i said i think its the best and fastest way to do respond to your AJAX requests if you have little thing calls, however if your application uses AJAX extensively it would be better if you implement a dedicated Servlet to respond to AJAX requests, the servlet will act as a front controller, and you will differentiate between AJAX calls using a parameter for example "operation", and passing additional parameters if needed
so for example if you for example if you want to check if the user already exists you would call
and if you want for example make another AJAX call to get user information you would use the same path but change the operation value
from the server side you will have a servlet that reads the operation parameter from the request and then gets the correct handler for that operation by sending the operation
string
to a factory object for example, which will give you back the handler, then you can invoke a certain method that object to get the response string to be sent back to the user. to support what i am advicing here is an abstract view
first you need an interface that has a method named geteAjaxResponse(HttpServletRequest request) you can pass other parameters if needed.
public interface IAjaxProcessor{ public String getAjaxResponse(HttpServletRequest request) throws Exception; }
then in your AjaxFrontController you can define a servlet with the following logic
public class AjaxFrontController extends HttpServlet{ public void doGet(... needed parameters) throws ... { PrintWriter out = response.getWriter(); try{ //get the operation parameter String operation = request.getParameter("operation"); //get the AjaxProcessor corresponding to the corrent operation IAjaxProcessor processor = Factory.getAjaxProcessorFor(operation); //invoke the getAjaxResponse() method and write the result back to the user out.print(processor.getAjaxResponse(request)); }catch(Exception e){ //handle the error and send an error notification back to the user }finally{ out.flush(); out.close(); } } }
and finally for each AJAX operation you will have a class that extends IAjaxProcessor and define the getAjaxResponse() method.
i ommitted the code needed to create the factory since its obvious, in addition using some naming conventions a lot of code could be reduced, and you could use a configuration file to specify the names and classes used for AJAX so that you will not have to recompile your code if you will have to add a new AJAX operation.
(peace)
shaf maff
Ranch Hand
Joined: Sep 07, 2008
Posts: 180
posted
Jan 14, 2009 21:12:56
0
Thanks for th replies guys. I have a similar layout omar, just that I dont have a factory.
I will post my proccess and you can take a look and tell me how I can integrate the JSP files into the ajax.
User makes ajax request -> request recieved by servlet which gets the DB stuff and hardcoded html and prints it out as XML -> javascript updates page.
Now, is there a way of returning chunks of JSP code as xml without hard coding it into the servlet ? I know there are ways of including chunks of JSP in jsps to prevent repetition. Can the same be achieved with
servlets
? Or is there a different way of handling such an issue ?
I agree. Here's the link:
subject: Html in serlets for ajax apps?
Similar Threads
PrimeFaces Newbie: How to control content on page?
If last char of textarea is \n, Safari 3.2.1 seems to think the textarea contains extra \n.
Need Help with Jquery Selector logic
Need help selecting a value from a list with multiple ids that are the same
How to display value in combo box using AJAX
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/426243/Servlets/java/Html-serlets-ajax-apps | CC-MAIN-2015-40 | refinedweb | 1,076 | 57 |
Print the Elements of a Linked List
Print the Elements of a Linked List
aparnaelangovan + 7 comments
Why are other languages such as C# not included in this?
amitgala555 + 1 comment
+1
Sleepnever + 1 comment
+1
besselfunction + 2 comments
scala?
talebilling + 1 comment
I believe C++ accepts C code, it works for me, you sould try it
chiragkalia1 + 0 comments
If you can create test cases for 6 languages, I think it shouldn't be that difficult to add for one more. Makes sense?
saikiran9194HackerRank Admin + 1 comment
C# has been enabled for sometime now. :)
j_kibirige + 1 comment
Doesn't work for me I have a recursive solution to this problem in C# and I get errors Null reference exceptions....
yakamoz + 1 comment
These type of questions is good to improve ourselves in academic aspect, because these question's solutions can be hand written on paper before code it. It is significant practise before midterms and interviews. I hope there will be more question like that in different topics such as trees.
alexkeyes + 0 comments
You're totally right! its simple and an important solution on how to practice basic CS. There are Tree tutorials as well: checkout this link.
cordobestexano + 1 comment
Why no C# on this? it makes no sense.
nikilp + 6 comments
Here is Python 3 implementation:
def print_list(head): if head is not None: print(head.data) print_list(head.next)
keerthi7vasan + 1 comment
Could you please help me undersrtand "print_list(head.next)"...
Pjmcnally + 0 comments
It is a recurisve function. You call the function inside of itself.
def print_list(head): if head is not None: print(head.data) print_list(head.next)
In this example the function takes a node, checks if it exists and if it does prints the data in that node. Then it runs that same function (print_list) on the next node (node.next). This will keep calling that function inside of itself until it runs out of nodes.
Pjmcnally + 1 comment
That approach works but if the list is long enough (around 1000 elements) you will hit the recursion depth and error out. Also, as the list length increases your stack size will grow with it linearly.
An approach like this (below) is much safer, has a constant stack size and doesn't require any more code.
def print_list(node): while node: print(node.data) node = node.next
csnuhman + 1 comment
What's a recursion depth? And, what would be a case where I should never use recursion?
Pjmcnally + 1 comment
Please note the comment below is about Python. There are languages for which this isn't a problem but I don't program in any of them.
A recursive function calls itself. This mean that a new function is called from within the original function.
For example look at the code below and assume a linked list counting from 0 to n by 1.
def print_list(head): if head is not None: print(head.data) print_list(head.next)
The first function looks at the head of the list and prints it. It then creates a new function to print the next element. However, the first function hasn't ended yet. It can't end until all the functions within it end. This is key to understand.
If we look at the call stack (the list of running functions) it looks like this:
print_list() # the original outer most function, waiting for internal functions to end. print_list() # the new function called within the original func.
This just keeps on going. The new function calls another function. Now our stack looks like this:
print_list() # the original function print_list() # level 1 function. print_list() # level 2 function.
The call stack keeps getting bigger and bigger because none of the outer functions can terminate because they are waiting on inner functions.
print_list() # the original function print_list() # level 1 function. print_list() # level 2 function. ... ... ... print_list() # level 1000 - Recursion depth hit. Program ends and error displayed.
Recursion depth is a count of how many layers are active inside your recursive function. The default recursion depth limit for Python 3 is 1000. The limit exists to prevent a stack overflow caused by too much (possibly infinite) recursion.
To answer your second question, recursion is a cool tool and you should use it (or at least understand it). However, some languages have optimized tail call recursion (what is the kind of recursion being shown above) and avoid this problem by ending the outer function when the inner one is called. Python has not.
If you are writing a function that may hit the recursion limit it may be better to approach it iteratively (at least in Python).
csnuhman + 0 comments
You explained it really well. Thanks! And I did look up for why Python hasn't and probably never will optimize the tail recursion. For the ones who are intrested: Stack Overflow
joranbeasley + 0 comments
how did you know to name your function
print_listI found that nowhere in the problem statement and had tried using Print (which is what the problem statement calls out)
karid55 + 3 comments
Java:
void Print(Node head) {
while ( head != null) { System.out.println(head.data); head = head.next; }
}
rishabh0_9 + 1 comment
This code is giving error ..Can you gives me another one
ramin_anush + 1 comment
Similar solution. You don't need the if statement for this problem though.
if(head == null){ System.out.print(""); } else{ Node current = head; while(current != null){ System.out.println(current.data); current = current.next;} }
sarwarhayatt + 2 comments
can I see the full code Im not exactly gettin it .
karid55 + 1 comment
What do you not understand?
This is a simple commented explanation of my code above:
void Print(Node head) {
while ( head != null) { //Iterate through the linked list until head is equal null (after last node)
System.out.println(head.data); //Display the value of the current node
head = head.next; //Move pointer to the next node
}
nashrahmeraj + 0 comments
public static void Print(Node head) {
if(head!=null) { Node temp; temp=head; while(temp!=null){ System.out.println(temp.data); temp=temp.next; } }
}
sarwarhayatt + 1 comment
got it. Thanks for the effort.
somendra_raj5 + 1 comment
void Print(Node head) { Node current = head; while(current!=null){ System.out.println(current.data); current = current.next; } }
dmillerconsulti1 + 1 comment
Is anyone else using Swift having a compilation error from the uneditable code?
Sort 290 Discussions, By:
Please Login in order to post a comment | https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/forum | CC-MAIN-2018-43 | refinedweb | 1,070 | 67.35 |
Egor V.2 - Robo-Animatronic (Carl Strathearn University of Huddersfield: Multimedia Design 2013-14)
Step 1: Actulatiy and Artificiality (Egor V.2)
The title of my final year Multimedia Design project (Actuality and Artificiality) is an adaptation of the post-modernist philosopher Jean Baudrillard’s ideology, Simulacra and Simulation: Simulacra as object and Simulation as process. The robot robots.
Full instructions with image and video //ref guides available ()
Step 2: Equipment
1x wooden circle (20cm dia)
1 x check plate (aluminium) same size as wooden circle
Black paint
Processing free from Processing.org
Arduino free from Arduino.cc
Mac computer
Bolts and Nuts of Various sizes 1mm-4mm (m3)
2 x 12g micro servos
5 x hex screws
2 x meccano L brackers small (fish plate)
3 mm wire (sturdy)
1 x kinect sensor
1 x kinect sensor stand
1 x arduino (leonardo)
1 x servo shield v2
3 x Robot L bracket
1 x Robot circular rotating base (aluminium not plastic) - (ebay) (around £30)
1 x 10kg servo (base)
3 x silver small 'short' robotic U brackets (ebay)
1 x guitar neck plate - black
1 x 15 kg servo (neck) u / d
3 x large robot brackets in black (ebay)
false teeth
Artificial eyes
Miliput (black)
3 x 9g micro servos
Guitar string (E)
2 x Springs from pegs
1 x pocket speaker (anker - front)
1 x pocket speaker (larger - back)
4 x metal rods 15 cm
1 x short 7 cm
8 x brass screw bricks from wire connector blocks
2 x circular servo horns
1 x meccano long plate
1 x breadboard
reel of tribind wire (90lb fishing wire)
10 x servo lead extension leads
2 x multifunctional robot brackets
8 x brass spacers (m4)
4 x m4 bolts 8 cm
2 x ball and socket joints (lego)
extension lead 2.1mm audio
1 x 5 kg sero (jaw)
1mm wire
black thermo plastic (small bag)
2 mm eyelets
Step 3: Base
Take the wooden circular base (1.1) and paint it black (1.2), drill 4 holes on the outer edge of the base to attach the aluminium plate (1.3). Match the holes in the aluminium check plate, drill an additional 4 holes that match the m4 screws (1.4) in the base of the robotic rotational base (1.5). The base comes as a kit but needs assembling (look on ebay under robot arm base) it is a pretty straight forward installation and has placement for the base servo (1.6). Attach the aluminium plate to the end of the m4 screws on the rotational base and attach the base to the wooden base. This completes the base structure.
Step 4: Neck
Take a multifunctional robot bracket (2.1) and attach a servo (2.2) and a large robotic U bracket (2.3). Take the L bracket and bolt it into the back of the multifunctional bracket using M3 bolts and nuts (2.4). Fit the other end of the L bracket to to upper aluminium platform of the rotational robotic base (2.5). Attach A large black U bracket to the servo via a circular servo horn (2.6) and a ball and flange cup bearing on the other (standard formation) to the end of the Large L bracket attach another L bracket facing the opposite way to for a H shape. To the front of this mechanism attach the guitar neck place to the front to finish it off using the bolts supplied with the fitting. This completes the neck set up. (2.7).(2.8)
Step 5: Jaw
The jaw is made up of a multifunctional bracket (3.1) with a small silver aluminium U bracket (3.2) attached to the end in standard formation (3.3). To make the lower jaw take the lower part of the false teeth and some 3 mm metal wire (3.4), bend the wire into the shape of the lower jaw use black miliput to fix this element in place on the ends fix meccano L fish plates into the milliput and under the wire for extra support. Fit the wire through the holes in the U bracket and curl the wire to fix in place, use miliput to seal these ends to form a stable structure. Do the same procedure for the upper jaw, take two multifunction brackets and attach them back to back. Use two L shaped small meccano parts to secure the upper jaw wire to the two multifunctional brackets. Example set up (3.5) video (3.6)
Step 6: Eyes
Take two medium aluminium U brackets (4.1) and bolt them back to back ][ like this (4.2) there are four holes at each end of the bracket. The holes will be used to thread the 3mm x 100mm straight rods through (4.3). To make the eyes move up and down we need to use the top holes and left and right we need to use the left hole on the left side and the left hole on the right side (4.4). Attach the 70mm smaller rods (4.5) to the ends of the upper (eyes up / down) and lower (eyes left / right) rods with brass bricks taken from cable connector blocks (4.6), bolt the frame together with the supplied bolts. This forms two large U shapes that slide in and out of the holes in the two medium aluminium U brackets. Take the artificial eyes (4.7) and using miliput (4.8) secure the socket joint of the ball and socket (4.9) element into the middle of the back of the eyes. Then take 4 (2 for each eye) small brass screw eyelets (4.2.1) and .secure them into the miliput. These eyelets should be level with the rods that are coming out of the upper two medium aluminium brackets. To each end of the rod take a brass wire connector block and bolt it half way onto each of the metal rods. Make a small loops using 1mm wire and attach it to the spare hole in the end of the brass connectors and secure in place with miliput. The the ball part of the ball and socket joint and secure it to middle lower part of each of the medium aluminium U brackets. Secure this part onto the bracket using Black thermo plastic (4.2.4). Attach the ball and socket joints together and 1mm wire through each of the brass eyeless, close the eyelets with pliers and tighten the 1mm wire (with caution) to form a snug fit. Use miliput on the renaming parts of the brass connectors and 1mm wire loops to secure in place. Take two micro servos and attach them upside down to eachother by their bases using glue. Add stand plastic servo arms take some 3mm wire and cut two pieces into 4cm strips. Loop one end and fit it through one of the holes in the servo arm and loop the other end around the back part of the large U bracket the controls the eyes up and down / left and right. secure this in place on each side with thermo plastic (allows the loop to turn with the servo arm but not move up and down the metal rod). Attach the two servo to the upper part of the back of the robot with miliput (see picture). This completes the eye mechanism. see video for test footage.
Step 7: Lips.
Attach 2 micro servos (5.1) to each side of the middle head bracket (aluminium multifunctional robot brackets bolted back to back) one servo here > ][ < on here (5.2). These motors will drive the lips. To make the lips take a long 18 hole meccano (5.3) strip and attach brass wire blocks (5.4) to the middle and either side secure in place with black thermo plastic (5.5). On the end of each block take a small spring from a peg (5.6) and place it over the end of the block (this with retract the lips back into place) Take the guitar string (5.7) and cut it to size using the teeth as a guide leave plenty spare on each end so you can play around with getting the fit right before securing each end to frame with miliput. Take some thick fishing wire (5.8) and thread it through the arms of the micro servos, through the brass blocks and secure to the upper lips with a knot. Secure in place with miliput (I used metal clasps in the picture but replaced because they kept slipping along the guitar string). Use the same set up for securing the lower lip into the bottom jaw aluminium L bracket (5.9) and secure with thermoplastic. Attach a mirco servo to the underneath of the bottom jaw using two bolts and thermoplastic. Take a brass block wire connector and attach it to the middle of the lower jaw (underneath) use miliput to secure in place. Run wire from the servo arm through the brass block and attach to the lower lip with a knot and secure with miliput.
This completes the lip functions, see test video and photos of finished set up.
Step 8: Fixing the Head Together and Securing Speakers
Attach the eye mechanism to the top of the multifunctional brackets (bolted back to back in the middle of the head) use thermoplastic to secure in place as this gives it a strong tight hold (6.1). Take the bigger pocket speaker (giz wiz 6.2)and place it at the back of the robot ( it will fit perfectly between the Large upper black U bracket if you buy the one stated in the equipment list. Take the smaller speake (6.3)r and secure it to the upper top part of the jaw mechanism. Extend the reach of the cables using extension leads (2,1mm)
Step 9: Arduino Set Up and Audio Trigger
Take an arduino and place the servo shield on top of it, place each of the servos into a digital port on the board. (Note: I run a 6v 3amp psu / battery into the servo shield to power to motors: remember to remove the crossover on the shield if you are going to do this). Take a 2.1 mm headphone/audio cable and remove the female end. Take the wires and twist the ground together and the signal. Place the ground in the ground port on the arduino and the signal into one of the analog ports. (It does not matter which port because you can change the code to suit the ports of our liking). Place the end of the cable into a apple laptop or computer.
Step 10:
Step 11: Processing Script and Kinect Libraries
First of all we need to download the kinect libraries for processing (look it up on google) Make sure you install the point tracking for kinect library into your processing library. When you can run the demo for point tracking you know it is installed correctly on your system. We also need to install the Eliza chat bot library, this comes with a test package.
You will need to make your own background image for your program and call it bg1.jpeg
You will also need to make your own Eliza script ive called it something like newscript.txt but call it what you want, or unhash the internet sample code if you just want to use the original.
You can also comment out point tracking and access skeleton tracking mode to interactive with multiple participants.
Step 12: Applescript Voice App Script and Voice Recognition Output
Make an apple script app with the following:
set theVoices to
{"Alex", "Bruce", "Fred", "Kathy", "Vicki", "Victoria"}
set thePath to (path to desktop as Unicode text) & "test.txt"
set the_file to thePath
set the_text to (do shell script "cat " & quoted form of (POSIX path of the_file))
set the clipboard to the_text
set theSentence to the clipboard
log (theSentence)
say theSentence using ("Bruce") speaking rate 140 modulation 5 pitch 15
on readFile(unixPath)
return (do shell script "cat /" & unixPath)
end readFile
To use voice recognition simple activate the function on your apple mac from the system menu and out put it to the processing / eliza chat interface instead of using a keyboard. (You will need to set up the microphones in the kinect sensors for this to work)
Step 13: Setting Up the Kinect Sensor
This is a little bit tricky but if you buy a kinect stand or make one you can move it around a little bit and find the best position for your robot. I find this easier to do than re-programming everytime, although sometimes this is practical if the robot is going to be stationary for a long period of time to refine the positions. | http://www.instructables.com/id/Egor-V2-Robo-Animatronic/ | CC-MAIN-2017-17 | refinedweb | 2,145 | 76.76 |
Recursion is a straightforward solution :
public class Solution { public int addDigits(int num) { int sum = 0; if(num < 10) return num; while(num!=0){ sum+=num%10; num/=10; } return addDigits(sum); } }
For O(1) solution if you think about it what happen when you adding 2 numbers, There is 2 conditions x+y >= 10 or < 10 , then if it greater than 10 then the sum of its digits will be less than 10 why ? because the biggest result you can achieve is 18 -> 9+9 -> 1+8 -> 9 , So easily we can define when the number (x) exceeds 10 is by 10-x , for example for 8 -> 8 + any number greater than 2 >= 10, so the idea of xy number we need to get the 10 start of x and the distance between y and this start.
example :
(let x be the biggest).
38 -> x = 8,y = 3
z => 10 - 8 = 2 (start of 8)
y-z = 1 -> 1 + 1 = 2
for 75 -> x = 7,y = 5
z => 10-7 = 3
y-z = 2 + 1 = 3
public class Solution { public int addDigits(int num) { int sum = 0; if(num < 10) return num; int x = num%10,y = (num/10)%10,z; z = x; x = Math.max(x,y); y = Math.min(z,y); num/=100; while(num!=0){ if(10-x <= y){ z = ((y-(10-x)) + 1); }else{ z = x+y; } sum+=z; x = z; y = num%10; x = Math.max(x,y); y = Math.min(z,y); num/=10; } return (10-x <= y) ? ((y-(10-x)) + 1) : x+y; } } | https://discuss.leetcode.com/topic/84755/recursion-solution-o-1-solution | CC-MAIN-2017-39 | refinedweb | 261 | 77.57 |
Java Reference
In-Depth Information
applet method paint . This method takes a Graphics object as its single argument and
is not called directly by the applet, but is executed by the Web browser. In Swing
applets, however, the required components are added to the applet's surface within
method init (also executed implicitly by the browser) and no painting should be
specifi ed (though there is nothing that actually prevents us from doing so).
Example
Taking the simplest possible example, we'll create an applet that displays a greeting
to the user. In order to avoid specifying painting onto the applet's window, we can
use a JLabel and add this to the applet (within method init , of course), just as we
would do for the application JFrame in a GUI application.
Remember that the applet class must extend class JApplet .
import java.awt.*;
import javax.swing.*;
public class AppletGreeting extends JApplet
{
public void init()
{
JLabel message =
new JLabel("Greetings!",JLabel.CENTER);
//Default layout manager for JApplet is
// BorderLayout …
add(message,BorderLayout.CENTER);
}
}
Just as we would do for a Java application, we save this applet with the name
AppletGreeting.java . We then compile it in the usual way:
javac AppletGreeting.java
However, before we can run it, we must place it in an HTML page via the
<APPLET> tag. This tag has three mandatory attributes (as well as a number of
optional ones):6
CODE (specifying the name of the applet's .class fi le);
WIDTH (specifying the width of the applet, in pixels);
HEIGHT (specifying height of the applet, in pixels).
As will be the case for all subsequent applets in this chapter, we shall employ a
minimal HTML page:
<HTML>
<APPLET CODE = "AppletGreeting.class"
WIDTH = 300
HEIGHT = 150>
</APPLET>
</HTML>
Search WWH ::
Custom Search | http://what-when-how.com/Tutorial/topic-547t9a4dbp/An-Introduction-to-Network-Programming-with-Java-360.html | CC-MAIN-2019-09 | refinedweb | 297 | 52.49 |
maxlength on input box can be overriden by autocomplete
Bug Description
No, not a dupe. It's asking (without providing any reason other than Fx2-compat) that bug 345267 be reverted. Assuming the comments there are correct, and the current behavior is the same as every other browser except Fx2, it's a wontfix.
Indeed.
It's just strange behaviour for javascript to not respect html when the DOM is modified. Are there any official specifications on how this should actually work - rather than saying "other browsers do it like that"? If this mentality is used, then we'd have to duplicate all IE quirks as it's how the other half of the world is doing it.
> Are there any official specifications on how this should actually
> work - rather than saying "other browsers do it like that"?
Not yet. HTML5 is specifying this behavior (and Firefox 3 is following the draft HTML5 spec).
> then we'd have to duplicate all IE quirks
We basically do duplicate all the IE quirks that don't violate existing specifications and are needed to make significant numbers of existing web sites work... So do all the other browsers.
User-Agent: Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9) Gecko/2008052912 Firefox/3.0
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9) Gecko/2008052912 Firefox/3.0
It is possible to bypass the maximum length limitation for text input fields with autocomplete. Autocomplete offers any text, even if it's longer than what is allowed and the field is consequently populated after selecting the too long text.
Reproducible: Always
Steps to Reproduce:
1. Create a new html file with following content in the body:
<form id="testForm" method="GET">
<input id="testInput" type="text" />
<input type="submit" />
</form>
2. Open the file in the browser and type "0123456789" in the input field and hit submit.
3. Change the file and add 'maxlength="5"' to the input field.
4. Go back to the browser and refresh.
Actual Results:
Now it is possible to select "0123456789" as value for the input field.
Expected Results:
Autocomplete should not render suggestions that are longer than _maxlength_ or when such a value is selected, it should be trimmed to a total length of _maxlength_.
I believe this is quite a critical issue, as most developers rely on the size of the strings that are provided by the limited input fields. That is - many applications probably would behave in an unexpected manner, when provided with longer texts.
Hunh - no doubt about it, confirmed via data url.
I don't think this needs to be hidden, there are plenty of ways to get around maxlength parameters and they aren't something web developers should ever rely on as a safety mechanism; they only keep honest people honest, basically. The exploit possibilities seem somewhat remote, and only make slightly more visible an existing vulnerability in the target website (i.e. relying on maxlength).
Nevertheless, we should fix it, and I'm surprised it hasn't come up earlier, but I'm not having any luck finding an existing bug. Bug 204506 is similar, but clearly didn't fix this problem. Bug 443363 is a dup of this bug.
This is a regression from Firefox 2.0.0.x which correctly truncates the autocomplete data at the maxlength.
> I believe this is quite a critical issue, as most developers rely on
> the size of the strings that are provided by the limited input fields.
That would be unwise. Hackers are not constrained by the maxlength limit and would love to find that exceeding it throws your server for a loop.
Mike: did anyone re-work autocomplete for FF3? I assume the awesomebar is its own thing and not built on autocomplete but that could be wrong.
The autocomplete code doesn't do anything special related to maxlength, so this was probably caused by bug 345267. That change made it possible to enter more than maxlength characters into a text field programmatically, to match other browsers. The autocomplete code sets the value via the same code path as page scripts, so it was affected too.
Boris, can you look at this?
This needs a fix on the autocomplete side: it needs to be checking the maxlength. It didn't need to before, as Gavin said, because it was relying on a core bug. Then we fixed the core bug.
Created an attachment (id=335666)
WIP
I put this together a while ago but couldn't get the test to work. The entries added by the test are apparently not added correctly because they don't appear as options, and even if they did I'm not sure that the code I use to select the autocomplete entry will work.
Created an attachment (id=389264)
v.1 only show entries that fit (applies to patch v.3 on bug 446247)
Instead of truncating, only show form history entries that will fit in the field.
(From update of attachment 389264)
>+ if (aField && aField.maxLength > -1)
>+ result.
Use an inline anonymous function here...
foo = foo.filter(function (e) { return (element.
(A refinement of having a local function in the if-block to do this, which would be my choice instead of having a tiny utility function stuck, at distance, onto the component's object).
Created an attachment (id=390343)
v.2 inline function & update unit tests
(From update of attachment 390343)
sr? for API change, this was added in 3.6 so there's no compat issues.
Created an attachment (id=390676)
v.3 fix bitrot
(From update of attachment 390676)
sr=mconnor
verified with: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2b1pre) Gecko/20090925 Namoroka/3.6b1pre
Thanks for reporting this bug and any supporting documentation. Since this bug has enough information provided for a developer to begin work, I'm going to mark it as Triaged and let them handle it from here.
I am moving this to Firefox 3.5 as 3.0 will be EOL next month and this is a low priority issue. Thanks for taking the time to make Ubuntu better! Please report any other issues you may find.
I think I was too hasty here. My test case was for javascript overriding maxlength, but I found https:/
Nevermind, I found the upstream bug which seems to be what you were describing. Take a look and if it's not, let us know. This is scheduled to be fixed in Firefox 3.6
Please report any other bugs you may find.
" - maxlength not stop long values
+ maxlength on input box can be overriden by autocomplete "
ok, i tryed say just this !
not problem with javascript only with autocomplete , javascript ist a choice of programmer, but auto complete its a feature of Firefox , i think that can not overriden forms restrictions , or will allow wrong datas to be input , auto-complete need respect maxlength value
sorry for my bad english i am brasilian and are very hard to me explain the problem ,
firefox will be the source package...
Created an attachment (id=323854)
maxlength test | https://bugs.launchpad.net/ubuntu/+source/firefox-3.5/+bug/486284 | CC-MAIN-2018-34 | refinedweb | 1,198 | 65.93 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Searching By Address3:35 with Jason Seifer
In our final bit of search functionality, we add the ability to search by address.
Code Samples
def find_by_address(query) results = [] search = query.downcase contacts.each do |contact| contact.addresses.each do |address| if address.to_s('long').downcase.include?(search) results.push(contact) unless results.include?(contact) end end end print_results("Address search results (#{search})", results) end
- 0:00
Okay, so we have address book looking pretty good.
- 0:04
We can find people by name and we can find people by phone number.
- 0:08
Finally, let's go ahead and add the ability to find somebody by their address.
- 0:14
Now, this is going to follow a similar pattern as finding by name and
- 0:19
phone number, except this time we're going to be querying by the address.
- 0:23
So, let's go ahead and create a method to find by an address.
- 0:33
Now if we scroll up,
- 0:34
we can see we have this pattern of creating an empty results array and
- 0:38
then manipulating the search to get sent in, and then looping through the contacts,
- 0:43
and depending to the array, unless the contact is included in that array.
- 0:48
So let's go ahead and follow that same pattern now, and this time,
- 0:53
what we're going to send in is a query, because we're going to be looping and
- 0:58
finding the address, but we'll see that in just a second.
- 1:02
So, we'll set up our empty results array, and then we'll create our search variable,
- 1:10
which is just going to be a lowercase version of the query.
- 1:15
Now we can loop through our contacts.
- 1:22
And then we're going to have to loop through our addresses too.
- 1:26
Now let's go ahead and look at the address class for a moment.
- 1:29
We have this two string method, and we learned before that we can use the include
- 1:34
method to see if one string is included in another.
- 1:39
So we're gonna use the long form of the address to see whether or
- 1:43
not the search is included in there.
- 1:46
But we need to loop through each address for
- 1:51
each contact to see if the query is contained there.
- 1:56
So let's go ahead and do that.
- 1:57
We're in a contact right now, so we'll go ahead and loop through the addresses.
- 2:08
Now we can say if the long form of the address downcase that,
- 2:14
and then we'll see if that includes the search.
- 2:21
Then we can follow the same pattern as before.
- 2:26
And append the contact to the results,
- 2:30
unless the results already have that contact.
- 2:35
So, we don't have any duplicates when we print it out.
- 2:39
And then finally, we can use that print results method to display the results.
- 2:54
So now, all we have to do is, we can scroll down here.
- 3:04
And let's just search for two, since we know that Nick has an address on Two Lane.
- 3:14
And comment those out just to clean up the output a little bit.
- 3:19
And then go down in the console here.
- 3:21
If I type ruby address_book.rb,
- 3:26
we can see that we have Nick turning up in the address search results for
- 3:31
two, which is exactly what we wanted. | https://teamtreehouse.com/library/build-an-address-book-in-ruby/search/searching-by-address | CC-MAIN-2019-43 | refinedweb | 642 | 79.9 |
Hi show you how to send an image file.
For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.
I have already shown you three other methods on uploading a file to server. If you want you can check these posts.
- How to Upload Multiple files in one request along with other string parameters in android?
- Uploading audio, video or image files from Android to server.
- How to upload an image from Android device to server? – Method 4
These are for downloading files from the server.
- How to Download an image in ANDROID programatically?
- How to download a file to your android device from a remote server with a custom progressbar showing progress?
if you want to use the android using php and mysql
please check these posts.
Add Permission
Add “android.permission.INTERNET” permission to your AndroidManifest.xml file.
Note
You need to add the below to your build.gradle since Apache library is deprecated by Google.
android {
useLibrary ‘org.apache.http.legacy’
}
build.gradle
Our Sample build.gradle may look like this.
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.coderzheaven.uploadimage" minSdkVersion 21 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } android { useLibrary 'org.apache.http.legacy' } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.1' compile 'com.android.support:design:23.2.1' }
Layout
Our Sample XML layout will look like this.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <Button android: <ImageView android: <Button android: <TextView android: </LinearLayout>
Android Source Code
We will have a separate class for sending image.
Create a class named “UploadImageApacheHttp” and copy the below contents to it.
Before that, download the Base64 file from here which encodeBytes in Base64 Format.
Add it to your project.
File Upload Utility class
package com.coderzheaven.uploadimage; import android.graphics.Bitmap; import android.os.Handler; import android.util.Log;.util.EntityUtils; import java.io.ByteArrayOutputStream; import java.util.ArrayList; public class UploadImageApacheHttp { public static final String TAG = "Upload Image Apache"; public void doFileUpload(final String url, final Bitmap bmp, final Handler handler){ Thread t = new Thread(new Runnable() { @Override public void run() { Log.i(TAG, "Starting Upload..."); final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image", convertBitmapToString(bmp))); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); String responseStr = EntityUtils.toString(response.getEntity()); Log.i(TAG, "doFileUpload Response : " + responseStr); handler.sendEmptyMessage(1); } catch (Exception e) { System.out.println("Error in http connection " + e.toString()); handler.sendEmptyMessage(0); } } }); t.start(); } public String convertBitmapToString(Bitmap bmp){ ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want. byte[] byte_arr = stream.toByteArray(); String imageStr = Base64.encodeBytes(byte_arr); return imageStr; } }
Now the Activity that implements it.
Note : Make sure you select the image from the Gallery, because this demo is designed for selecting from Gallery.
MainActivity
package com.coderzheaven.uploadimage; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String TAG = "Upload Image"; // I am using my local server for uploading image, you should replace it with your server address public static final String UPLOAD_URL = ""; public static final String UPLOAD_KEY = "upload_image"; private int PICK_IMAGE_REQUEST = 100; private Button btnSelect, btnUpload; private TextView txtStatus; private ImageView imgView; private Bitmap bitmap; private Uri filePath; private String selectedFilePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); imgView = (ImageView) findViewById(R.id.imgView); btnSelect = (Button) findViewById(R.id.btnSelect); btnUpload = (Button) findViewById(R.id.btnUpload); txtStatus = (TextView) findViewById(R.id.txtStatus); btnSelect.setOnClickListener(this); btnUpload.setOnClickListener(this); } Handler handler = handler = new Handler() { @Override public void handleMessage(Message msg) { Log.i(TAG, "Handler " + msg.what); if (msg.what == 1) { txtStatus.setText("Upload Success"); } else { txtStatus.setText("Upload Error"); } } }; private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); selectedFilePath = getPath(filePath); Log.i(TAG, " File path : " + selectedFilePath); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imgView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } uploadImage() { UploadImageApacheHttp uploadTask = new UploadImageApacheHttp(); uploadTask.doFileUpload(UPLOAD_URL, bitmap, handler); } @Override public void onClick(View v) { if (v == btnSelect) showFileChooser(); else { txtStatus.setText("Uploading Started..."); uploadImage(); } } }
Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a UIThread only.
Add Base64.java to your project
However you can put in your own package but don’t forget to change the package name otherwise you will get error.
Server part
Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.
I am saying the htdocs folder because I am using XAMPP. You change this according to your use.
< ?php $base=$_REQUEST['image']; $binary=base64_decode($base); header('Content-Type: bitmap; charset=utf-8'); $file = fopen('uploaded_image.jpg', 'wb'); fwrite($file, $binary); fclose($file); echo 'Image upload complete!!, Please check your php file directory……'; ?>
Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.
If you want to upload another file in your SDCARD you have to change this line to give the exact path
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
For example if I have to upload a file residing in my SDCARD I would change the path like this.
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/android.jpg");
Source Code
You can download the complete Android studio Source Code from here.
Please send your comments to coderzheaven@gmail.com
Just what I was looking for, appreciate it for posting .
Hi, Please could you tell me what i need to use for main.xml file, thankyou
Lucy
Hello Lucy..
The main.xml file is for the interface. Since in this example it shows how to upload an image to server there is actually no need of an interface. You can put anything in the main.xml file. For example you can have a button which when clicked will upload the image, then put the code provided inside the button click, that’s all.
You have to provide a layout for the setContentView() otherwise the program will not run.
Hi James,
Thanks for the quick response, I confess, i’m an android newbie 🙁
Would you be ever so kind as to help me out getting this to work, i guess all i need is the main.xml with a button that will upload the image, and the code to know that the button is there.
Hope you can help, you can email me if you wish
Thankyou
Lucy
@Lucy : Please wait for the answer we will contact you shortly.
Pingback: How to Download an image in ANDROID programatically? | Coderz Heaven
Very nice tutorial:)
Thank u .Nice Tuto:)
I would like to uploade many images..
How can I give a name for each image?
Pingback: How to Upload Multiple files in one request along with other string parameters in android? | Coderz Heaven
Thanks.
It helps me so much
I prefer to send it just as a byte array
I don’t code for the server.
Thanks a lot
but i have problem with Base64.encodeBytes(byte_arr);
it gives me error :S
Did you include the file Base64.java.
Hi, I have the same problem with Peter gabra, and I have include the Base64.java in the src, could you help me to fixed it?
Did you download the complete source code. Try changing the filename to something else and change accordingly in the main file.
Hi, thanks my problem solve now. I want to ask about base 64, because it just possible to send the image with small size, is there possible to send the image in big size to server using base64?
thanks
hei james nice tutorial. I am a newbie for android. May i have the full source code for this? and also i cannot find the “get picture from sd card gallery” thing like a picker in your code. so how do i pick the pic from my gallery?
Hi,,
Nice post … But I have question what about image captured by Image and store it at Media.EXTERNAL_CONTENT_URI location.
Thanks
It works fine, thanks.
On the server the image gets “uploaded_image” filename.
I’m sending to the server a file from my device’s sd card, it works ok (I have to downsize it though because I get out of memory error)
I want the file name to be the same as the original, how can I do that??
Hey LamprosGk : If you want the filename as such then try this example
or try this
Thanks James
I’ve found out how to do it..
(passed the file name in nameValuePairs to the php file
Thank you very very very much!!! This has been a tremendous help!
I’d just like to add one small comment. I would suggest resizing the image before sending it the server because otherwise if the image is too big, it is very likely that you’ll get an out of memory exception.
Bitmap resizedDishImage = Bitmap.createScaledBitmap(dishImage, 150, 150, false);
Hello,
I tried your code and it works fine with a local server, but with a remote server it doesn’t work 🙁
Have you an idea why ?
No, it works perfectly with any server. Please check your server address or anyother parameters you are sending.
hlo sir, is it possible to upload image on cpanel server with this code
yes, ofcourse.
Hello,
Very nice post. Is there a way I can do this using a web app instead of an installed app?
thank you!
I cant see the php code.
Sorry Hari that was problem with my syntax highlighter, please check the post again.
Hello James,
Thanks for the reply. Its working very fine. Thanks man
Hi,
the encodeBytes method is giving me an error saying “encodedBytes is undefined for type Base64” . i have downloaded the Base64 class, and inserted it into my project..could you please help me????
hey this “Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/mypic.jpg”);” does not work, do you have any idea why?
but if it works whrn i used Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
This is because you don’t have mypic.jpg in that path.
hi i run ur apps successfully…result also displayed successfully.Image upload complete!!, Please check your php file directory……But my doubt is where is uploaded file is saved..how is know the above image is successfully uploaded…where i see the image after successful completion…
The uploaded file will be saved in the uploads directory in your server where your php file is located.
Wooow… thanku so much. It works great. And how can I upload an image which is captured? where I have modify in this code…?
hi!
can anyone suggest me an alternative to above server side phpscript.
Any help will be appreciated..
hi,
its so excellent tutorial…..i m getting a problem……i want to upload an image on jboss server……what i has to bb done on jboss server……what code i hv to write there…….plz any one guide me………..
hi guys
can i ask qustion?
did i need to write code to start xampp for android?
because i didnt sure cellphone can work?
No Steven, there is no connection between starting the xampp server and android. if your http request have to reach the server, xampp should be on and running.
Hi James
I am Sorry ,Could you tell me
I just need to put the upload_image.php this file to htddocs folder in xampp
Did I need to set any about website?
oh I know where is my problem.
if you want to connection and run in Android cellphone.
Your IP must be entity.
otherwise you can,t connection, this is message for dont understand other guys.
No you can test it locally. The post describes how to work with it locally. If you have a server then put the file in the right place and just change the UR.
i am able to sleect both the files..but when i hit StartUpload button, the upload process dialog box shows for 1 sec and then the error message is shown saying “Unfortunately the process pack.coderzheaven” has stopped.
i have added the internet permission in manifest also.. my Wamp server is On..also i have used localhost instead of 10.0.2.2 in the code.. Can u plz tell me where i am going wrong ?
what is the reason for the error in the logcat? please check that and paste it here.
package pack.coderzheaven;
what is this thing ?
and how come i dint see any package from the coding above ?
example like : package com.sample.testing
opps sorry, when i see the coding above the package seems to be appear as something like this,
span id=”IL_AD1″ class=”IL_AD” package /span pack.coderzheaven;
i only see it as “package pack.coderzheaven;’
after i dropped comment..
Sorry Kyle, that was the problem with the syntax highlighter.
pls help me error
ERROR Permission denied
That’s the problem with you server. Check the permissions.
How to download pictures that i have just uploaded in this localserver i tried putting back in for example ‘’ where i presume i uploaded but didnt work
Change 192.168.1.3 to 127.0.0.1
I am getting error as null. Bitmap.compress is not working.Can you plz help me..
echo ‘Image upload complete!!, Please check your php file directory……’;
sir i have a problem.. how can we view the image($file) in our page. because u can view the image only in the php..
this is my code
echo ‘$file’ …
code is not workng Try this link. You have to upload the image back or download the image and show it in an imageView.
I have an app that captures an image and displays it.how do I upload the captured image?thanks
You will get the image inside onActivityResult() function. From there save it in a temporary file and then upload using the above example.
Great tutorial 🙂 i am getting ERROR null(showing in toast).Plz help me out…….
So I am …
I have traced that the application stopped at the following statement.
HttpResponse response = httpclient.execute(httppost);
The httppost information is correct. Any idea?
Thanks a lot!
Give internet permission in the Manifest file.
Pingback: Best way to store camera clicked pics on android? : Android Community - For Application Development
Pingback: how to send photo from android device to FTP server : Android Community - For Application Development
setContentView(R.layout.main);
I am getting error on this line and all other lines where R is present
There is R.java file in my gen folder i always get error on this please help!
setContentView(R.layout.main);
you have to chage “main ” according to the name of your xml file .for example : activity_main.xml ,..
After Uploading a file in mnt/sd card to mySQL ,Dialog box is still being uploading..Do I need to remove files in my Gallery (Emulator)???I am not getting Output
great tutorial! but I have a stupid question..
“How does the server know where this image uploaded to?”
I added in the SQL statement for tables and columns. good news is the image string had successfully changed to the image path(eg. sdcard/…../sample.png)
but bad news is.. my server’s image folder does not contain that image that i just uploaded.. may i know which code did i missed out? or what went wrong?
no error code given.. only success all the way..
Server will not know where to upload the files. The folder to upload the file is written by you in the PHP file.
Pingback: PHP to ASP.NET code migration | BlogoSfera
I already have the Internet Permission in manifest.Always i try to upload the file i get:
07-23 14:46:12.681: I/System.out(16675): Error in http connection android.os.NetworkOnMainThreadException
Sometimes make a jpg file in server with the name but with 0 size.
About this line: HttpResponse response = httpclient.execute(httppost);
Wait for the response?or make a threat?
It can be the size of the pic to upload?there is a limit?
I tried with small icon pic but nothing.
Hello segen
Do the uploading inside a thread, because on newer versions of android it will not allow network operations to be done in the main thread. Update UI elements inside the thread from another runonUIThread only. Otherwise the application will crash.
I have made an edit to reflect the changes.
Nice work man, Thanks, This is exactly I was looking for. I want to save the file in the root folder but it is toasting the message permission denied. I guess I need to be the super user. How can we do it? Do we need to change in Android or the PHP code.
One more question I need to take pictures from camera and send it without saving it in the phone memory location. I have a code running which takes pictures every 10 Sec but I need to integrate with this, So instead of using BitmapFactory.decodeResource(getResources(),R.drawable.icon); what shall I use?
Regards
Abhishek
Great tutorial, but I get an error on line 33; The method encodeBytes(byte[]) is undefined for the type Base64 and I have the Base64.java in my package. Can you help me out?
Sorry my line 33 is your line 30
Please tell me how can i assign a variable name to my image file which is being uploaded?
please tell me how can i change the name of my image file which is being uploade?
Thank
Hi James, do you have the code to retrieve the image and display it in a listview?
check this code.
Hello, I’m having a little trouble with this program. It is with this line:
HttpResponse response = httpclient.execute(httppost);
it says:
Description Resource Path Location Type
Syntax error on tokens, TypeArgumentList1 expected instead NewSpotActivity.java /AndroidConnectingToPhpMySQL/src/com/example/androidhive line 142 Java Problem
Can you show me the source code of main.xml layout of project you use?
great tutorial and it works !! thank you James.
And i have a question ,well i’m triying to follow the speed of the upload .I already did it with the download and it worked .
while ((count = input.read(data)) != -1) {
total += count;
long endtTime = System.currentTimeMillis();
long passed;
passedTime =endtTime – startTotalTime;
// publishing the progress….
// After this onProgressUpdate will be called
publishProgress(“”+(int)((total*100)/lenghtOfFile));
Log.i(“log_lenghtOfFile”,lenghtOfFile+”” );
Log.i(“log_total”,total+”” );
Log.i(“log_ourcentage”,(int)((total*100)/lenghtOfFile)+”” );
Log.i(“log_passed_time”,passedTime +”” );
}
but i had a problem with the uploading i need to get :
t= 10 s uploded data =10byte /total data
t =45 uploaded data =150byte/total data (for example )
Ididn’t found where i could follow the rate of uploading ,i tryed to do that in base64,but it didn’t work.
please if you have an idea help me.
hey i m new to android development, i want to do my final year project based on this. can u plz send me complete code with main.xml and menifest.xml.. plzz mail me the code as soon as possible. ur help is very iportant for me. plz
Thank you very much………thanks a loooooooooooooot..
God bless you
Pingback: how to send the image in an ImageView to a php server? - PHP Solutions - Developers Q & A
Where to see the uploaded image?
Check the directory specified in the code.
is it necessary to use
header('Content-Type: bitmap; charset=utf-8');
or can we remove that?
didn’t try removing it.
Silly me.. I forgot to change the request tag in the PHP script. Working perfect now. Thanks for this. It’s just what I needed. Simple enough for me to understand and a good starting point. Next I will try to assign a specific file name, put the file name in my database, and also retrieve the image back to my list view.
OK. Great
Notice: Undefined index: image in C:\wamp\www\Upload_image_ANDROID\upload_image.php on line 2
i found this error while running server part code and i also run this code on wamp
Hi how to upload both image file and string details from android to server using post methode with basic namevalue pairs can u give some sample code please.
You can simply copy paste the code into an Activity and it will work.
excellent tutorial have to do a lot of changes but at the end code works….
if you don’t the errors then follow these steps..
1
permission (internet)(read external storage) in manifest file
2
download base64 file to your project package where image file is placed
3
then some exceptions that android studio will handle as well
4
thanks to JAMES nice tutorial…..
5
setContentView(here put you xml file just and rest is fine…just run the code now and image will be uploaded to the website through app…:)….. )
6
some may have errors regarding gradle build
use sdk min 8 max 21 | http://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/ | CC-MAIN-2018-43 | refinedweb | 3,689 | 61.33 |
[SOLVED, moved] Drag from another application and drop to a PySide app?
- ThomasDalla last edited by
Dear community,
I am trying to implement a dropEvent in a PySide application to open a file when someone drags it from the file explorer and drops it in the PySide application.
So I added self.setAcceptDrops(True) in the init of my MainWindow and implemented a dropEvent like that:
@
def init(self):
...
self.setAcceptDrops(True)
def dropEvent(self, *args, **kwargs):
print args@
However, I cannot drop to my application.
The cursor is a ∅ that doesn't want me to drop there...
How can I drop something in a PySide application?
Note: I tried adding setAcceptDrops(True) to inside widgets, it doesn't work neither.
- frankcyblogic.de last edited by
You also have to implement the "dragEnterEvent()": to tell the window system which drags you actually want to accept.
- ThomasDalla last edited by
Oh yeah I didn't notice I have to "accept" the drag first, thanks ;)
If it helps anyone who was also wondering how to do a drag an drop in PySide, here is my working code:
@ @Slot(QDropEvent)
def dropEvent(self, event):
self.loadInputFile(self.dropFile)
@Slot(QDragEnterEvent)
def dragEnterEvent(self, event):
m = event.mimeData()
if m.hasUrls():
self.dropFile = m.urls()[0].toLocalFile()
event.acceptProposedAction()@ | https://forum.qt.io/topic/5513/solved-moved-drag-from-another-application-and-drop-to-a-pyside-app-63 | CC-MAIN-2019-43 | refinedweb | 215 | 55.44 |
Sound in Python
Have you ever wanted to work with audio data in Python? I know I do. I want to record from the microphone, I want to play sounds. I want to read and write audio files. If you ever tried this in Python, you know it is kind of a pain.
It's not for a lack of libraries though. You can read sound files using wave, SciPy provides scipy.io.wavfile, and there is a SciKit called scikits.audiolab. And except for
scikits.audiolab, these return the data as raw
bytes. Like, they parse the WAVE header and that is great and all, but you still have to decode your audio data yourself.
The same thing goes for playing/recording audio: PyAudio provides nifty bindings to portaudio, but you still have to decode your raw
bytes by hand.
But really, what I want is something different: When I record from the microphone, I want to get a NumPy array, not
bytes. You know, something I can work with! And then I want to throw that array into a sound file, or play it on a different sound card, or do some calculations on it!
So one fateful day, I was sufficiently frustrated with the state of things that I set out to create just that. Really, I only wanted to play around with cffi, but that is beside the point.
So, lets read some audio data, shall we?
import soundfile data = soundfile.read('sad_song.wav')
done. All the audio data is now available as a NumPy array in
data. Just like that.
Awesome, isn't it?
OK, that was easy. So let's read only the first and last 100 frames!
import soundfile first = soundfile.read('long_song.flac', stop=100) last = soundfile.read(start=-100)
This really only read the first and last bit. Not everything in between!
Note that at no point I did explicitly open or close a file! This is Python! We can do that! When the
SoundFile object is created, it opens the file. When it goes out of scope, it closes the file. It's as simple as that. Or just use
SoundFile in a context manager. That works as well.
Oh, but I want to use the sound card as well! I want to record audio to a file!
from pysoundcard import Stream from pysoundfile import SoundFile, ogg_file, write_mode with Stream() as s: # opens your default audio device # This is supposed to be a new file, so specify it completely f = SoundFile('happy_song.ogg', sample_rate=s.sample_rate, channels=s.channels, format=ogg_file, mode=write_mode) f.write(s.read(s.sample_rate)) # one second
Read from the stream, write to a file. It works the other way round, too!
And that's really all there is to it. Working with audio data in Python is easy now!
Of course, there is much more you could do. You could create a callback function and be called every four1 frames with new audio data to process. You could request your audio data as
int16, because that would be totally awesome! You could use many different sound cards at the same time, and route stuff to and fro to your hearts desire! And you can run all this on Linux using ALSA or Jack, or on Windows using DirectSound or ASIO, or on Mac using CoreAudio2. And you already saw that you can read Wave files, OGG, FLAC or MAT-files3.
You can download these libraries from PyPi, or use the binary Windows installers on Github. Or you can look at the source on Github (PySoundFile, PySoundCard), because Open Source is awesome like that! Also, you might find some bugs, because I haven't found them all yet. Then, I would like you to open an issue on Github. Or if have a great idea of how to improve things, please let me know as well.
UPDATE: It used to be that you could use indexing on SoundFile objects. For various political reasons, this is no longer the case. I updated the examples above accordingly.
Footnotes:
You can use any block size you want. Less than 4 frames per block can be really taxing for your CPU though, so be careful or you start dropping frames.
More precisely: Everything that libsndfile supports. | http://bastibe.de/2013-11-27-audio-in-python.html | CC-MAIN-2017-17 | refinedweb | 716 | 85.49 |
An Introduction to Recurrent Neural Networks for Beginners
A simple walkthrough of what RNNs are, how they work, and how to build one from scratch in Python..
This post assumes a basic knowledge of neural networks. My introduction to Neural Networks covers everything you’ll need to know, so I’d recommend reading that first.
Let’s get into it!
1. The Why
One issue with vanilla neural nets (and also CNNs) is that they only work with pre-determined sizes: they take fixed-size inputs and produce fixed-size outputs. RNNs are useful because they let us have variable-length sequences as both inputs and outputs. Here are a few examples of what RNNs can look like:
This ability to process sequences makes RNNs very useful. For example:
- Machine Translation (e.g. Google Translate) is done with “many to many” RNNs. The original text sequence is fed into an RNN, which then produces translated text as output.
- Sentiment Analysis (e.g. Is this a positive or negative review?) is often done with “many to one” RNNs. The text to be analyzed is fed into an RNN, which then produces a single output classification (e.g. This is a positive review).
Later in this post, we’ll build a “many to one” RNN from scratch to perform basic Sentiment Analysis.
2. The How
Let’s consider a “many to many” RNN with inputs that wants to produce outputs . These and are vectors and can have arbitrary dimensions.
RNNs work by iteratively updating a hidden state , which is a vector that can also have arbitrary dimension. At any given step ,
- The next hidden state is calculated using the previous hidden state and the next input .
- The next output is calculated using .
Here’s what makes a RNN recurrent: it uses the same weights for each step. More specifically, a typical vanilla RNN uses only 3 sets of weights to perform its calculations:
- , used for all → links.
- , used for all → links.
- , used for all → links.
We’ll also use two biases for our RNN:
- , added when calculating .
- , added when calculating .
We’ll represent the weights as matrices and the biases as vectors. These 3 weights and 2 biases make up the entire RNN!
Here are the equations that put everything together:
All the weights are applied using matrix multiplication, and the biases are added to the resulting products. We then use tanh as an activation function for the first equation (but other activations like sigmoid can also be used).
No idea what an activation function is? Read my introduction to Neural Networks like I mentioned. Seriously.
3. The Problem
Let’s get our hands dirty! We’ll implement an RNN from scratch to perform a simple Sentiment Analysis task: determining whether a given text string is positive or negative.
Here are a few samples from the small dataset I put together for this post:
4. The Plan
Since this is a classification problem, we’ll use a “many to one” RNN. This is similar to the “many to many” RNN we discussed earlier, but it only uses the final hidden state to produce the one output :
Each will be a vector representing a word from the text. The output will be a vector containing two numbers, one representing positive and the other negative. We’ll apply Softmax to turn those values into probabilities and ultimately decide between positive / negative.
Let’s start building our RNN!
5. The Pre-Processing
The dataset I mentioned earlier consists of two Python dictionaries:
data.py
train_data = { 'good': True, 'bad': False, # ... more data } test_data = { 'this is happy': True, 'i am good': True, # ... more data }
We’ll have to do some pre-processing to get the data into a usable format. To start, we’ll construct a vocabulary of all words that exist in our data:
main.py
from data import train_data, test_data # Create the vocabulary. vocab = list(set([w for text in train_data.keys() for w in text.split(' ')])) vocab_size = len(vocab) print('%d unique words found' % vocab_size) # 18 unique words found
vocab now holds a list of all words that appear in at least one training text. Next, we’ll assign an integer index to represent each word in our vocab.
main.py
# Assign indices to each word. word_to_idx = { w: i for i, w in enumerate(vocab) } idx_to_word = { i: w for i, w in enumerate(vocab) } print(word_to_idx['good']) # 16 (this may change) print(idx_to_word[0]) # sad (this may change)
We can now represent any given word with its corresponding integer index! This is necessary because RNNs can’t understand words - we have to give them numbers.
Finally, recall that each input to our RNN is a vector. We’ll use one-hot vectors, which contain all zeros except for a single one. The “one” in each one-hot vector will be at the word’s corresponding integer index.
Since we have 18 unique words in our vocabulary, each will be a 18-dimensional one-hot vector.
main.py
import numpy as np def createInputs(text): ''' Returns an array of one-hot vectors representing the words in the input text string. - text is a string - Each one-hot vector has shape (vocab_size, 1) ''' inputs = [] for w in text.split(' '): v = np.zeros((vocab_size, 1)) v[word_to_idx[w]] = 1 inputs.append(v) return inputs
We’ll use
createInputs() later to create vector inputs to pass in to our RNN.
6. The Forward Phase
It’s time to start implementing our RNN! We’ll start by initializing the 3 weights and 2 biases our RNN needs:
rnn.py
import numpy as np from numpy.random import randn class RNN: # A Vanilla Recurrent Neural Network. def __init__(self, input_size, output_size, hidden_size=64): # Weights self.Whh = randn(hidden_size, hidden_size) / 1000 self.Wxh = randn(hidden_size, input_size) / 1000 self.Why = randn(output_size, hidden_size) / 1000 # Biases self.bh = np.zeros((hidden_size, 1)) self.by = np.zeros((output_size, 1))
We use np.random.randn() to initialize our weights from the standard normal distribution.
Next, let’s implement our RNN’s forward pass. Remember these two equations we saw earlier?
Here are those same equations put into code:)) # Perform each step of the RNN for i, x in enumerate(inputs): h = np.tanh(self.Wxh @ x + self.Whh @ h + self.bh) # Compute the output y = self.Why @ h + self.by return y, h
Pretty simple, right? Note that we initialized to the zero vector for the first step, since there’s no previous we can use at that point.
Let’s try it out:
main.py
# ... def softmax(xs): # Applies the Softmax Function to the input array. return np.exp(xs) / sum(np.exp(xs)) # Initialize our RNN! rnn = RNN(vocab_size, 2) inputs = createInputs('i am very good') out, h = rnn.forward(inputs) probs = softmax(out) print(probs) # [[0.50000095], [0.49999905]]
Our RNN works, but it’s not very useful yet. Let’s change that…
Liking this introduction so far? Subscribe to my newsletter to get notified about new Machine Learning posts like this one.
7. The Backward Phase
In order to train our RNN, we first need a loss function. We’ll use cross-entropy loss, which is often paired with Softmax. Here’s how we calculate it:
where is our RNN’s predicted probability for the correct class (positive or negative). For example, if a positive text is predicted to be 90% positive by our RNN, the loss is:
Want a longer explanation? Read the Cross-Entropy Loss section of my introduction to Convolutional Neural Networks (CNNs).
Now that we have a loss, we’ll train our RNN using gradient descent to minimize loss. That means it’s time to derive some gradients!
⚠️ The following section assumes a basic knowledge of multivariable calculus. You can skip it if you want, but I recommend giving it a skim even if you don’t understand much. We’ll incrementally write code as we derive results, and even a surface-level understanding can be helpful.
If you want some extra background for this section, I recommend first reading the Training a Neural Network section of my introduction to Neural Networks. Also, all of the code for this post is on Github, so you can follow along there if you’d like.
Ready? Here we go.
7.1 Definitions
First, some definitions:
- Let represent the raw outputs from our RNN.
- Let represent the final probabilities: .
- Let refer to the true label of a certain text sample, a.k.a. the “correct” class.
- Let be the cross-entropy loss: .
- Let , , and be the 3 weight matrices in our RNN.
- Let and be the 2 bias vectors in our RNN.
7.2 Setup
Next, we need to edit our forward phase to cache some data for use in the backward phase. While we’re at it, we’ll also setup the skeleton for our backwards phase. Here’s what that looks like:)) self.last_inputs = inputs self.last_hs = { 0: h } # Perform each step of the RNN for i, x in enumerate(inputs): h = np.tanh(self.Wxh @ x + self.Whh @ h + self.bh) self.last_hs[i + 1] = h # Compute the output y = self.Why @ h + self.by return y, h def backprop(self, d_y, learn_rate=2e-2): ''' Perform a backward pass of the RNN. - d_y (dL/dy) has shape (output_size, 1). - learn_rate is a float. ''' pass
Curious about why we’re doing this caching? Read my explanation in the Training Overview of my introduction to CNNs, in which we do the same thing.
7.3 Gradients
It’s math time! We’ll start by calculating . We know:
I’ll leave the actual derivation of using the Chain Rule as an exercise for you 😉, but the result comes out really nice:
For example, if we have and the correct class is , then we’d get . This is also quite easy to turn into code:
main.py
# Loop over each training example for x, y in train_data.items(): inputs = createInputs(x) target = int(y) # Forward out, _ = rnn.forward(inputs) probs = softmax(out) # Build dL/dy d_L_d_y = probs d_L_d_y[target] -= 1 # Backward rnn.backprop(d_L_d_y)
Nice. Next up, let’s take a crack at gradients for and , which are only used to turn the final hidden state into the RNN’s output. We have:
where is the final hidden state. Thus,
Similarly,
We can now start implementing
Reminder: We created
self.last_hsin
forward()earlier.
Finally, we need the gradients for , , and , which are used every step during the RNN. We have:
because changing affects every , which all affect and ultimately . In order to fully calculate the gradient of , we’ll need to backpropagate through all timesteps, which is known as Backpropagation Through Time (BPTT):
is used for all → forward links, so we have to backpropagate back to each of those links.
Once we arrive at a given step , we need to calculate :
The derivative of is well-known:
We use Chain Rule like usual:
Similarly,
The last thing we need is . We can calculate this recursively:
We’ll implement BPTT starting from the last hidden state and working backwards, so we’ll already have by the time we want to calculate ! The exception is the last hidden state, :
We now have everything we need to finally implement BPTT and finish # Initialize dL/dWhh, dL/dWxh, and dL/dbh to zero. d_Whh = np.zeros(self.Whh.shape) d_Wxh = np.zeros(self.Wxh.shape) d_bh = np.zeros(self.bh.shape) # Calculate dL/dh for the last h. d_h = self.Why.T @ d_y # Backpropagate through time. for t in reversed(range(n)): # An intermediate value: dL/dh * (1 - h^2) temp = ((1 - self.last_hs[t + 1] ** 2) * d_h) # dL/db = dL/dh * (1 - h^2) d_bh += temp # dL/dWhh = dL/dh * (1 - h^2) * h_{t-1} d_Whh += temp @ self.last_hs[t].T # dL/dWxh = dL/dh * (1 - h^2) * x d_Wxh += temp @ self.last_inputs[t].T # Next dL/dh = dL/dh * (1 - h^2) * Whh d_h = self.Whh @ temp # Clip to prevent exploding gradients. for d in [d_Wxh, d_Whh, d_Why, d_bh, d_by]: np.clip(d, -1, 1, out=d) # Update weights and biases using gradient descent. self.Whh -= learn_rate * d_Whh self.Wxh -= learn_rate * d_Wxh self.Why -= learn_rate * d_Why self.bh -= learn_rate * d_bh self.by -= learn_rate * d_by
A few things to note:
- We’ve merged into for convenience.
- We’re constantly updating a
d_hvariable that holds the most recent , which we need to calculate .
- After finishing BPTT, we np.clip() gradient values that are below -1 or above 1. This helps mitigate the exploding gradient problem, which is when gradients become very large due to having lots of multiplied terms. Exploding or vanishing gradients are quite problematic for vanilla RNNs - more complex RNNs like LSTMs are generally better-equipped to handle them.
- Once all gradients are calculated, we update weights and biases using gradient descent.
We’ve done it! Our RNN is complete.
8. The Culmination
It’s finally the moment we been waiting for - let’s test our RNN!
First, we’ll write a helper function to process data with our RNN:
main.py
import random def processData(data, backprop=True): ''' Returns the RNN's loss and accuracy for the given data. - data is a dictionary mapping text to True or False. - backprop determines if the backward phase should be run. ''' items = list(data.items()) random.shuffle(items) loss = 0 num_correct = 0 for x, y in items: inputs = createInputs(x) target = int(y) # Forward out, _ = rnn.forward(inputs) probs = softmax(out) # Calculate loss / accuracy loss -= np.log(probs[target]) num_correct += int(np.argmax(probs) == target) if backprop: # Build dL/dy d_L_d_y = probs d_L_d_y[target] -= 1 # Backward rnn.backprop(d_L_d_y) return loss / len(data), num_correct / len(data)
Now, we can write the training loop:
main.py
# Training loop for epoch in range(1000): train_loss, train_acc = processData(train_data) if epoch % 100 == 99: print('--- Epoch %d' % (epoch + 1)) print('Train:\tLoss %.3f | Accuracy: %.3f' % (train_loss, train_acc)) test_loss, test_acc = processData(test_data, backprop=False) print('Test:\tLoss %.3f | Accuracy: %.3f' % (test_loss, test_acc))
Running
main.py should output something like this:
--- Epoch 100 Train: Loss 0.688 | Accuracy: 0.517 Test: Loss 0.700 | Accuracy: 0.500 --- Epoch 200 Train: Loss 0.680 | Accuracy: 0.552 Test: Loss 0.717 | Accuracy: 0.450 --- Epoch 300 Train: Loss 0.593 | Accuracy: 0.655 Test: Loss 0.657 | Accuracy: 0.650 --- Epoch 400 Train: Loss 0.401 | Accuracy: 0.810 Test: Loss 0.689 | Accuracy: 0.650 --- Epoch 500 Train: Loss 0.312 | Accuracy: 0.862 Test: Loss 0.693 | Accuracy: 0.550 --- Epoch 600 Train: Loss 0.148 | Accuracy: 0.914 Test: Loss 0.404 | Accuracy: 0.800 --- Epoch 700 Train: Loss 0.008 | Accuracy: 1.000 Test: Loss 0.016 | Accuracy: 1.000 --- Epoch 800 Train: Loss 0.004 | Accuracy: 1.000 Test: Loss 0.007 | Accuracy: 1.000 --- Epoch 900 Train: Loss 0.002 | Accuracy: 1.000 Test: Loss 0.004 | Accuracy: 1.000 --- Epoch 1000 Train: Loss 0.002 | Accuracy: 1.000 Test: Loss 0.003 | Accuracy: 1.000
Not bad from a RNN we built ourselves. 💯
Want to try or tinker with this code yourself? Run this RNN in your browser. It’s also available on Github.
9. The End
That’s it! In this post, we completed a walkthrough of Recurrent Neural Networks, including what they are, how they work, why they’re useful, how to train them, and how to implement one. There’s still much more you can do, though:
- Learn about Long short-term memory networks, a more powerful and popular RNN architecture, or about Gated Recurrent Units (GRUs), a well-known variation of the LSTM.
- Experiment with bigger / better RNNs using proper ML libraries like Tensorflow, Keras, or PyTorch.
- Read about Bidirectional RNNs, which process sequences both forwards and backwards so more information is available to the output layer.
- Try out Word Embeddings like GloVe or Word2Vec, which can be used to turn words into more useful vector representations.
- Check out the Natural Language Toolkit (NLTK), a popular Python library for working with human language data.
I write a lot about Machine Learning, so subscribe to my newsletter if you’re interested in getting future ML content from me.
Thanks for reading! | https://victorzhou.com/blog/intro-to-rnns/ | CC-MAIN-2020-05 | refinedweb | 2,702 | 69.38 |
Forum:Namespace aliases
From Uncyclopedia, the content-free encyclopedia
Forums: Index > Ministry of Love > Namespace aliases
Note: This topic has been unedited for 1462 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response.
So guys. We've had the fake namespace alias "UN" for a while (UN:BAN, UN:VAIN, UN:AA) but it's technically not a namespace alias. (On Wikipedia, the namespace alias WP automatically redirects to the Wikipedia namespace (ex. WP:Blocking policy is equivalent to Wikipedia:Blocking policy). So why can't we just make UN an actual namespace alias for the Project namespace? --
This has been an automated message by Cute Zekrom (talk) 01:43, May 7, 2012 (UTC)
- I don't think I understand what you mean. UN is just used to redirect to the Uncyclopedia namespace, similar to how Wikipedia has it. --Hotadmin4u69 [TALK] 20:18 May 11 2012
- What he means is that Wikipedia has done some cody shit to make "WP:" an exact equivalent to "Wikipedia:" (so you don't need to create a load of redirect pages) and he suggests we do the same with "UN:" and "Uncyclopedia:". :26, 11 May 2012 | http://uncyclopedia.wikia.com/wiki/Forum:Namespace_aliases?t=20120516222916 | CC-MAIN-2016-22 | refinedweb | 202 | 62.58 |
The Idaligo.Time library consists of a set of tools which allow iterating through a timeline. The iteration process is based on a schedule that specifies what time pieces to be involved into the iteration.
The .NET framework has strong means to deal with time, but there are no standard classes that help to arrange time scheduled processes. This library is a first attempt to generalize time walking mechanisms using advantages of the C# 2.0 language.
The very basic usage of the library is to set up a schedule and start an iterating process based on it.
CronSchedule schedule = new CronSchedule().Hour(14).Hour(22).DayOfMonth(2,
4).DayOfWeek(DayOfWeek.Thursday).Month(2).
Month(11).Month(10).Minute(3).Minute(10, 30);
ISequence sequence = Helper.CreateSequence(schedule);
int times = 0;
foreach (DateTime at in sequence.Walk(DateTime.Now))
{
Trace.WriteLine(at.ToString("f"));
if (times > 500)
{
break;
}
times++;
}
As you can see, there is the CronSchedule class which allows to set up a schedule in the way the Unix cron command does. In this example, we are going through all the 3rd and 10th to 30th minutes of every 14th and 22nd hour of the second, third, and forth days of every February, October, and November as well as every Thursday of these months. Time traveling starts from the present time, which is specified as an argument of the Walk(...) method of the time sequence.
CronSchedule
Walk(...)
Note that the iteration process will never stop unless we terminate it intentionally, or we are out of the range of the DateTime values.
DateTime
Some times, you may want to iterate through two separate sequences simultaneously. In this case, you are likely to use the following pattern:
DateTime now = new DateTime(2007, 5, 2);
SequenceSet<String> set = new SequenceSet<string>();
set.Add("One",
Helper.CreateSequence(new CronSchedule().Minute(13, 20).Hour(12)));
set.Add("Another",
Helper.CreateSequence(new CronSchedule().Minute(0, 59).Hour(12)));
int number = 0;
foreach (SequenceSetPoint<string> point in set.Walk(now))
{
Trace.WriteLine(point.Key + ": " + point.At);
if (number > 100)
{
break;
}
number++;
}
In this sample, we are going through two time sequences and getting time events from both of them in the order whichever comes first. In order to find out which sequence has produced an event, we mark them with some arbitrary keys, the only purpose of which is to distinguish one sequence from another.
Sometimes, you might want to iterate not through separate moments of time but through time ranges. If so, try following the next example:
DateTime now = new DateTime(2007, 05, 2);
CronSchedule schedule = new CronSchedule().Hour(14).Hour(22).DayOfMonth(
2, 4).DayOfWeek(DayOfWeek.Thursday).Month(2).Month(11).
Month(10).Minute(3).Minute(10, 30);
SuperposedArea area = Helper.CreateSuperposedArea(schedule);
int times = 0;
foreach (TimeRange at in area.Walk(now))
{
Trace.WriteLine(at.ToString("f"));
if (times > 500)
{
break;
}
times++;
}
Every time range you will get in this traverse represents a passage of time which includes the point of beginning but does not include the point at the end. That is, the following holds true:
t is in the time range, if timerange.from <= t < timerange.till
This is a class that has not been documented intentionally because it is quite hard to fully test it and I cannot guarantee that it works absolutely properly. However, people ask me to show how to use it. Here we go:
[TestFixture]
public class TestTimer
{
/// <summary>
/// Any custom class you may want to use, for example
/// to keep the current state of the process
/// </summary>
public class MyMegaClass
{
private string name;
public MyMegaClass(string name)
{
if (name == null)
throw new ArgumentNullException("name");
this.name = name;
}
public override string ToString()
{
return name;
}
}
private void timer_Fire(object sender, FireEventArgs<MyMegaClass> args)
{
Trace.WriteLine(args.Key.ToString() + ": " +
args.At.ToString("f"));
}
[Test]
public void Test()
{
DateTime now = DateTime.Now.AddTicks(new
Random(DateTime.Now.Millisecond).Next());
SequenceSet<MyMegaClass> set =
new SequenceSet<MyMegaClass>();
set.Add(new MyMegaClass("One"),
Helper.CreateSequence(new CronSchedule().Minute(0, 59)));
set.Add(new MyMegaClass("Another"),
Helper.CreateSequence(new CronSchedule().Minute(0, 59)));
// in this test we set up the schedule to fire every minute,
// but in a real life the CronSchedule is likely to look like this
// new CronSchedule().Hour(14).Hour(22).DayOfMonth(2,
// 4).DayOfWeek(DayOfWeek.Thursday).Month(2).Month(11).
// Month(10).Minute(3).Minute(10, 30)
using (Timer<MyMegaClass> timer = new Timer<MyMegaClass>(set))
{
timer.Fire += new FireEventHandler<MyMegaClass>(timer_Fire);
timer.Start();
Thread.Sleep(1000 * 10 * 60);
timer.Stop();
Thread.Sleep(1000 * 2 * 60);
}
}
}
In order to create an instance of the Timer class, we have to create a SequenceSet first and pass it to the constructor. The generic Timer class has to have the same class parameter as a corresponding SequenceSet. The purpose of this class parameter is to be as an indicator that allows to distinguish events from different sequences in the sequence set. In the simplest case, it would be a string or GUID. When you start the timer, you will get events that have this string or GUID or whatever else, just to let you make a decision what to do with this event. In a more complex case, you may want to associate some state information with an event; if so, you have to define your own state class and use it as a class parameter creating both Timer and SequenceSet instances. Later, when you get an event from the timer, you will also get your state object.
Timer
SequenceSet
Please note!!! My Timer class is based on the standard System.Threading.Timer class which puts a callback method in a separate thread of the ThreadPool each time the event happens. This means that the timer will not wait until the previous event has been processed completely; instead of this, it just starts executing another thread for each next event despite of if the previous one has finished or not. So keep in mind, if your event handler takes too much time to process the current event, the next event might not be processed if the thread pool is out of free threads.
System.Threading.Timer
Take a look at my productivity tool for C# coders.
As of May 16th,. | http://www.codeproject.com/Articles/18633/Time-scheduler-in-C?fid=414000&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None | CC-MAIN-2015-14 | refinedweb | 1,036 | 54.52 |
zerorpc 0.6.1
zerorpc is a flexible RPC based on zeromq.zerorpc
=======
.. image::
:target::
* expose Python modules without modifying a single line of code,
* call those modules remotely through the command line.
Installation
------------
On most systems, its a matter of::
$ pip install zerorpc
Depending of the support from Gevent and PyZMQ on your system, you might need to install `libev` (for gevent) and `libzmq` (for pyzmq) with the development files.-hand to
"tcp://0.0.0.0:1234" and means "listen on TCP port 1234, accepting
connections on all IP addresses".
Call the server from the command-line
-------------------------------------
Now, in another terminal, call the exposed module::
$ zerorpc --client --connect tcp://127.0.0.1:1234 strftime %Y/%m/%d
Connecting to "tcp://127.0.0.1:1234"
"2011/03/07"
Since the client usecase is the most common one, "--client" is the default
parameter, and you can remove it safely::
$ zerorpc --connect tcp://127.0.0.1:1234 strftime %Y/%m/%d
Connecting to "tcp://127.0.0.1:1234"
"2011/03/07"
Moreover, since the most common usecase is to *connect* (as opposed to *bind*)
you can also omit "--connect"::
$ zerorpc tcp://127.0.0.1:1234 strftime %Y/%m/%d
Connecting to "tcp://127.0.0.1:1234"
"2011/03/07"
See remote service documentation
--------------------------------
You can introspect the remote service; it happens automatically if you don't
specify the name of the function you want to call::
$ zerorpc tcp://127.0.0.1:1234
Connecting to "tcp://127.0.0.1:1234"
tzset tzset(zone)
ctime ctime(seconds) -> string
clock clock() -> floating point number
struct_time <undocumented>
time time() -> floating point number
strptime strptime(string, format) -> struct_time
gmtime gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
mktime mktime(tuple) -> floating point number
sleep sleep(seconds)
asctime asctime([tuple]) -> string
strftime strftime(format[, tuple]) -> string
localtime localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
Specifying non-string arguments
-------------------------------
Now, see what happens if we try to call a function expecting a non-string
argument::
$ zerorpc tcp://127.0.0.1:1234 sleep 3
Connecting to "tcp://127.0.0.1:1234"
Traceback (most recent call last):
[...]
TypeError: a float is required
That's because all command-line arguments are handled as strings. Don't worry,
we can specify any kind of argument using JSON encoding::
$ zerorpc --json tcp://127.0.0.1:1234 sleep 3
Connecting to "tcp://127.0.0.1:1234"
[wait for 3 seconds...]
null
zeroworkers: reversing bind and connect
---------------------------------------
Sometimes, you don't want your client to connect to the server; you want
your server to act as a kind of worker, and connect to a hub or queue which
will dispatch requests. You can achieve this by swapping "--bind" and
"--connect"::
$ zerorpc --bind tcp://*:1234 strftime %Y/%m/%d
We now have "something" wanting to call the "strftime" function, and waiting
for a worker to connect to it. Let's start the worker::
$ zerorpc --server tcp://127.0.0.1:1234 time
The worker will connect to the listening client and ask him "what should I
do?"; the client will send the "strftime" function call; the worker will
execute it and return the result. The first program will display the
local time and exit. The worker will remain running.
Listening on multiple addresses
-------------------------------
What if you want to run the same server on multiple addresses? Just repeat
the "--bind" option::
$ zerorpc --server --bind tcp://*:1234 --bind ipc:///tmp/time time
You can then connect to it using either "zerorpc tcp://*:1234" or
"zerorpc ipc:///tmp/time".
Wait, there is more! You can even mix "--bind" and "--connect". That means
that your server will wait for requests on a given address, *and* connect
as a worker on another. Likewise, you can specify "--connect" multiple times,
so your worker will connect to multiple queues. If a queue is not running,
it won't affect the worker (that's the magic of zeromq).
.. warning:: A client should probably not connect to multiple addresses!
Almost all other scenarios will work; but if you ask a client to connect
to multiple addresses, and at least one of them has no server at the end,
the client will ultimately block. A client can, however, bind multiple
addresses, and will dispatch requests to available workers. If you want
to connect to multiple remote servers for high availability purposes,
you insert something like HAProxy in the middle.
Exposing a zeroservice programmatically
---------------------------------------
Of course, the command-line is simply a convenience wrapper for the zerorpc
python API. Below are a few examples.
Here's how to expose an object of your choice as a zeroservice::
class Cooler(object):
""" Various convenience methods to make things cooler. """
def add_man(self, sentence):
""" End a sentence with ", man!" to make it sound cooler, and
return the result. """
return sentence + ", man!"
def add_42(self, n):
""" Add 42 to an integer argument to make it cooler, and return the
result. """
return n + 42
def boat(self, sentence):
""" Replace a sentence with "I'm on a boat!", and return that,
because it's cooler. """
return "I'm on a boat!"
import zerorpc
s = zerorpc.Server(Cooler())
s.bind("tcp://0.0.0.0:4242")
s.run()
Let's save this code to *cooler.py* and run it::
$ python cooler.py
Now, in another terminal, let's try connecting to our awesome zeroservice::
$ zerorpc -j tcp://localhost:4242 add_42 1
43
$ zerorpc tcp://localhost:4242 add_man 'I own a mint-condition Volkswagen Golf'
"I own a mint-condition Volkswagen Golf, man!"
$ zerorpc tcp://localhost:4242 boat 'I own a mint-condition Volkswagen Golf, man!'
"I'm on a boat!"
Congratulations! You have just made the World a little cooler with your first
zeroservice, man!
- Author: François-Xavier Bourlet <bombela+zerorpc@gmail.com>.
- License: MIT
- Categories
- Package Index Owner: bombela
- DOAP record: zerorpc-0.6.1.xml | https://pypi.python.org/pypi/zerorpc/ | CC-MAIN-2017-43 | refinedweb | 974 | 56.96 |
Helper class for OffsetOfExpr. More...
#include "clang/AST/Expr.h"
Helper class for OffsetOfExpr.
Definition at line 1822 of file Expr.h.
For an array element node, returns the index into the array of expressions.
Definition at line 1880 of file Expr.h.
Referenced by PrintFloatingLiteral().
For a field offsetof node, returns the field.
Definition at line 1886 of file Expr.h.
References clang::SubobjectAdjustment::Field, and getKind().
For a field or identifier offsetof node, returns the name of the field.
Definition at line 1391 of file Expr.cpp.
Referenced by PrintFloatingLiteral().
Determine what kind of offsetof node this is.
Definition at line 1876 of file Expr.h.
Referenced by PrintFloatingLiteral().
Definition at line 1909 of file Expr.h.
References clang::SourceRange::getEnd().
Definition at line 1908 of file Expr.h.
References clang::SourceRange::getBegin().
Retrieve the source range that covers this offsetof node.
For an array element node, the source range contains the locations of the square brackets. For a field or identifier node, the source range contains the location of the period (if there is one) and the identifier.
Definition at line 1907 of file Expr.h. | https://clang.llvm.org/doxygen/classclang_1_1OffsetOfNode.html | CC-MAIN-2017-51 | refinedweb | 189 | 54.69 |
Edit: If you are interested in learning F#, let me take the opportunity to provide a shameless plug for my book Programming F#.
Edit: Updated for the September CTP.
Edit: While I certainly encourage you to read my blog, there is a great video we did for PDC titled An Introduction to Microsoft F# at
With the September CTP
So if you're interested in seeing what the fuss is all about, the read on.
What is F# and why should I learn the language to get your idea expressed, then perhaps F# is what you’ve been looking for.
Getting Started
To get started with F# download and install the latest release (v1.9.6.0) at:
Or just click ‘Download’ on the F# Development center at
This will install the F# Project System on top of Visual Studio 2008. First, create a new F# Project.
Next, add a new F# Source File. By default it will add a lot of ‘tutorial’ code, delete all that and insert the following into the empty code editor:
#light
letsquare.
F# Interactive for Visual Studio
The F# Interactive Console (FSI) is what’s know as a ' REPL loop’ for Read-Evaluate-Print-Loop. This means: taking a code snippet, compiling and executing it, then printing the results. With it you can rapidly prototype and test your programs. To launch FSI simply highlight some code and press ALT+ENTER; the FSI window will immediately pop up..)
Language Basics
#light (OCaml compat).
let square x = x * x (Type Inference).
let numbers = [1 .. 10] (F# Lists).
let squares = List.map square numbers (List.map and first-order functions).
printfn "N^2 = %A" squares.
Console.ReadKey(true) (.NET Interop) ‘first order functions’ and is a hallmark of functional programming."
No, it’s called ‘first-class functions’ (because functions are first-class citizens, like, e.g., numbers) or ‘higher-order functions’ — not ‘first-order functions’. Languages with ‘first 😉
Thanks,
-Chris
@R, re: "require the full version of VS..?";
}
static void Main()
{
var squares = from x in Sequence(1, 10) select x * x;
Console.WriteLine("N^2 = {0}", squares.Aggregate("", (s, i) => s + " " + i));
Console.ReadKey
从Allen Lee的《从C# 3.0到F#》一文开始,感觉园子里F#正在升温。Chris Smith写了一个F#的小系列,这里翻译出来与大家分享。在本文从零开始编写我们的第一个F#程序。
Tried to install the latest F# CTP where the platform is "Vista Ultimate" and VS 2008…hmmm – install dies saying that it not an appropriate MSI file???
Strange..
Ron
Hey Ron, could you be more specific. What was the exact error message you recieved? Please send it to fsbugs@microsoft.com.
Thanks!
Good little intro to f#. I used this for my initial lesson when learning f#. If you’re a VB programmer you may want to take a look at the series of blogs i’ve just started.
Unfortunately – as it seems, F# developers decided to use the way of the such aincient programming languages as Fortran – minimal type control, maximal possibility to make errors. If I am right, it’s a mistake. The banner of this way could be expressed (using gross exaggeration in order not to say too much words) as follows – we will write the code as soon as possible (<all the rest will not be said to customers> but then we will look for the mistakes all the life remaining). Making mistakes is usual way for the middle-level programmer, F# will help him to do that?
With F# being presumably distilled into the same CLI, does using F# confer any speed advantages to the same logically-identical function in C#/etc?
Basically, I’m wondering for intensive math calculations (such as stuff for), will F# confer a speed of execution advantage?
whoops. I meant
Since C# and F# both compile down to IL and get executed with the same JIT engine, there is no distinct speed ‘advantage’ for using one language over the other. F# should have the same performance profile as C#.
Any significant difference in benchmarks is usually due to different algorithms being used.
Yes this is quite good . And what more advantanges with this lang.
Hi I’d like to know (as mentioned by somebody above) what List.map square [1 .. 2 .. 10];;
I can see from the result that it’s outputting the squares of 1, 3, 5, 7 and 9 but I’m at a bit of a loss as to why!
Thanks, great article by the way.
Excellent.. I am very much impressed the way you explained about the functional programming language F#. I also keep the specification document for F# when i am reading this post. Twice i turned to spec document for :: and @ operators meaning.
Enjoyed writing F# code … i am really become the fan of F# language after reading your blog. Thank you so much. Eagerly Waiting for second part. 🙂
There may be some performance advantage in the fact that F# does tail call optimization where it can (C#, in contrast, never does it).
Great introduction to F# for beginners, thanks.
@Rupert
List.map square [1 .. 2 .. 10];;
2 must be increment by: 1+2=3+2=5+2=7+2=9
First, let me remind you that in my new ongoing quest to read source code to be a better developer ,
First, let me remind you that in my new ongoing quest to read source code to be a better developer ,
It can be even easier in C# than Eric’s.
MessageBox.Show(Enumerable.Range(1, 10).Select(a => a * a).Aggregate("", (b, c) => b + " " + c));
Very nice tutorial. I hope to learn some F# soon and this really helped.
Just learn Python and use IronPython and be done with it. Too many languages create vertical markets. VB dropped "let" 20 years ago, why bring it back?
I was hoping to see something tuly nice, and readable:
numbers = range(1,10)
print "N^2="+str([x*x for x in numbers])
Oh wait, that is python. If you feel the need to use a map construct:
def square(n):
return n*n
print "N^2="+str(map(square, numbers))
What is more readable?
F# is more readable and powerful, of course.
There’s no obligation about learning functional programming, but it’s an important part from Computer Sciences, and, if you want to compare two different languages as Python and F#, you should know the basic concepts behind FPLs for making a sensible evaluation.
I have F#ver1.9.6.2 installed on my machine.Since I dont have VS2008 installed,I run F#I Console.I have executed the below two lines of code
let vowels = [‘e’,’i’,’o’,’u’];;
let attacha = ‘a’ :: vowels;;
however i get the below errors
let attacha = ‘a’ :: vowels;;
———————^^^^^^^
stdin(15,22): error FS0001: Type mismatch. Expecting a char list but given a ( char * char * char * char) list
the type char does not match the type ‘char * char * char * char’.
Can anybody please explain why I get the above error.
I certainly feel that to learn F# C# is not a criteria,because I dont know C# but I am primarily a VC++ guy.
Regards,
Srinivasan S Saripalli
Bangalore,India
The problem is the way you declared the list:
[‘e’;’i’;’o’;’u’]
is a list of characters (semicolon delimited)
[‘e’,’i’,’o’,’u’]
is a single-element list, which is a tuple of 4 characters. (Duples are comma delimited.)
Make sense?
The reason it didn’t work Srinivasan is because you separated the list elements with commas instead of semicolons. Comma separation creates a tuple, or compound type, so what you actually made there was a list with one element, a tuple of four chars, instead of a list with four char elements.
This article should explain it better than I can:
Whoops, sorry Chris, for some reason your answer wasn’t showing up on my browser until after I posted mine.
原文链接:
You’ve been kicked (a good thing) – Trackback from DotNetKicks.com
Hello,
The programs below are well received. However an expensive source code (MATLAB) is used. Several potential users would like to use an open source code like F#. Is it suitabel to use F# to solve differential equations?
Research reactor
Chernobyl avalanche
Re: "Is it suitabel to use F# to solve differential equations?"
Certainly. F# seems to be very productive in highly algorithmic domains – e.g. the math and number crunching. As for the MatLab piece, I assume it is just a matter of finding the right math libraries and graphing libraries.
Unfortunately I don’t have any reccomendations for mathematical .NET libraries.
Thanks for Your answer. Could You recomend somebody I could turn to for answer?
I don’t understand Alex’s complaint about minimal type checking. As far as I can see, F# has quite strict type checking at compile time (much stricter than the C family of languages, for example). Maybe it’s not obvious from the tutorial, because you don’t have to /tell/ F# the type of an identifier if F# can unambiguously infer it.
Jason, you do realise that "let" in F# is completely unrelated to "let" in BASIC, don’t you? The F# equivalent to BASIC’s
LET A = 5
is
a <- 5
No sign of a "let". In F#, "let" means something quite different, that I don’t think has a direct equivalent in non-functional languages (I suppose it has /some/ similarity to "&" in C++, because it’s defining a sort of alias).
For those that still don’t understand the [1 .. 2 .. 10] bit, it reminds me a bit of the FOR statement when used with the /L option:
FOR /L (start, step, end) DO action
Although I don’t have much knowledge of the .NET library, it is reasonable to infer that "List.map square [1 .. 2 .. 10]" creates a list by mapping its elements to the result of calling square with arguments 1, 3, 5, 7 and 9 (because the step value is 2, and the constraints specified 1 to 10 inclusive). The end result is that we end up with with the squares of the numbers above. It also reminds me of list comprehensions in Python:
>>> [square(i) for i in range(1, 11, 2)]
[1, 9, 25, 49, 81]
Of course, in Python, the range function excludes the upper limit, so 11 needs to be used rather than 10.
I love these types of languages. They can get so much done with such little code!
F# you can even write XBox games using XNA.
I tried a small demo, it works very nicely.
Selami Ozlu
Stupid Microsoft, this is just another VBscript.
Stupid VBstscript, certainly stuoid F# again.
Just Learn Python instead. Get all the Dynamic stuff without the .net Framework. Why would you try to do dynamic stuff in the CLR?
I tried doing a recursive lambda once in c#. nightmare and it doesn’t work.
The new stuff on DLR looks interesting though, although I am thinking of jumping ship to Python as it does all that I want and then some. Who needs stupid acronyms like LINQ when you got list comprehensions.
If you really want the functional style then go Haskell, the only one that doesn’t cause a stack overflow as far as I can tell.
It would be nice to see a better example of the advantages of F# over C#. As a C# developer, I agree with some others that it just looks like some awkward syntax and easy way to code in more errors so far.
Can you give an example of something F# can do that C# can’t?
Why Caml (instead of – say – Haskell, Standard ML, or even Erlang)?
Just curious – I don’t consider this decision to be bad, after all…
@MarcinK – Haskell is pure FP, no OO construct. Ocaml has the OO stuff that F# also supports.
F# is the new kid on the block in terms of .NET languages. Currently in CTP form , it will be one
F# has its roots in a programming language called OCaml, C# has its roots in a programming language called Java, Garbage Collection has its roots in Lisp, etc.
So why all this efforts to re-invent the wheel?
Good Article. But why I used F#, if I already have C#? If possible make a comparison among F#, C# and Java. Only for mathematical calculation, I will never usr F#.
Why would you use F# …….. ?
Anyone who thinks that this is a) like Fortran (trust me it isnt) or b) just for calculation so wont use it either hasnt gone far enough yet or has their head wedged where the sun dont shine 🙂
May I point you to the excellent PDC demo (about 78 minutes) go to the F# research page click on getting started and about halfway down you will see a thumbnail marked demo – run that demo and be amazed.
It’s nice to have had someone write a tutorial, but (IMHO) this one just leaves out too many concepts for a part-one. It’s borders on a turn-off, for what is basically a lot of clutter.
It’s not that I’m particularly dim-witted, having followed a language use path of FORTRAN->assembly->C->C++ , and C# when necessary (because MS didn’t see fit to include the functionality in C++). The [1..2..10] was (to me), an obvious syntax, given the results.
I just think that a tutorial should <i>teach more and extol less</i>. Again, this is an IMHO.
I read these comments and I wonder about if some of you even read anything about F# before you commented. I’m certainly not a F# evangelist as I only really started looking at it more closely in the past few weeks.
It’s interesting how many of the commenters don’t understand "side effects" They keep asking what good is F#? WHy would I use this.. Etc. Etc. Perhaps you should watch the Anders interview about C# 4.0 they go off on a tangent that might help you understand.
@Eric Eilebrecht
"Note that the hard part is declaring the sequence (which of course would be easier if there was an "Enumerable.Sequence" method or somesuch)"
You could use Enumerable.Range
Nice Intro .
I’m new to F#, enjoyed reading this article.
F# looks similar to Matlab programming (.M code) .
Next Chicago ALT.NET meeting will bring a practical look at F#, showing that it does not need to be seen
I did not try F#
But based on this introduction, I think F# borrows the idea of Prolog
@Bui Viet Duc:
F# is part of a family of so-called "functional languages". Examples of these languages are Haskell, LISP, Scheme. They also borrow some concepts from languages such as Prolog. They don’t, however, copy their core ideals and syntax from Prolog. ,
Great article. Will definitely be reading up more on F#.
Just wish that MS would offer lisp as well.
I suspect for a beginner this might not be the most friendy introduction…
It’s a great article to know about F#. | https://blogs.msdn.microsoft.com/chrsmith/2008/05/02/f-in-20-minutes-part-i/ | CC-MAIN-2018-05 | refinedweb | 2,516 | 73.47 |
Can I get dual citizenship and an Ecuadorian passport?
Any foreigner who has been a legal resident for three years may acquire an Ecuadorian passport (and nationality) after due process. Ecuador allows its
citizens to be dual nationals, provided the country of origin (such as the U.S. and Britain) permits this.
Can I use my cell phone from the U.S. in Ecuador?
Yes, although must phones are programmed to use only the frequency ranges that are in the region where they are sold, they can be "un-locked" for
less than $25.00 at most cell-phone repair shops, of which there are many.
What do I need to open a bank account?
Just a valid passport and one other piece of picture ID.
What's the best way for me to get my stuff shipped from the U.S.?
A container is by far the most economical way. Ecuador allows you a one time duty free shipment of your household goods. You have six months from the time you enter the country with the intent to establish domicile to get your one time duty free shipment into the country. However, you must have your cedula (government issued ID), or risk paying storage if it enters the country before you get your Visa.
Can I bring my pets?
Sure, you can bring pets, birds or domestic animals into Ecuador. If you are coming from the United States by plane, then you can bring your pet with
you. You need a veterinarian to sign an animal Health Certificate stating that the animal is free from contagious diseases and is up to date with the
required vaccinations. Then the document must then be legalized by the USDA office of the State where you live within 10 days of your flight. Finally
you must take or send your documents to the Consulate at the Ecuador Embassy to be certified.
Can I use my ATM card to get money out?
Credit cards and debit cards that have the "PLUS" and "Cirrus" logos can be used at the ATM machines of all major banks here to withdraw money. There are also dozens of locations where you can send or receive money with Western Union or Money gram.
What kinds of jobs can I find?
Some people coming from other countries to Ecuador do not work jobs but, rather they start their own business or invest because the business opportunity is far greater for those that have a little money, however...
Entry level jobs in Ecuador pay about $200.00 per month. There is a lot of demand for English teachers because of the fact that many Ecuadorians want to learn English. It is a job many English-speaking people choose because it does not require you to speak any Spanish whatsoever. It pays around $4-$5 per hour which is high for Ecuador since many people only earn $7-$10 a day.
What currency does Ecuador use? Is it stable?
Ecuador only uses US dollars for their currency and does not accept any other currency. All transactions are done in dollars and they accept all
denominations except two dollar bills. Many stores don't take hundred dollar bills but the banks will. How stable it is is up to you to determine.
What’s the food like in Ecuador?
Ecuador has a much wider variety of food than most other South American countries, comparable to the US. They have
supermarkets here which are well-stocked and clean with all the same foods as is in the US with the exception of real maple syrup (they have the other kinds), sour cream and sharp cheddar cheese (there is mild cheddar here). They have many farmers markets which are literally overflowing with fresh garden-grown fruits and vegetables, both North and South American varieties, as well as organically grown meat. There are many different types of restaurants here, anything from Pizza parlors to Sushi bars.
What is the weather like?
Ecuador is on the equator. Lower elevation areas will be hot and humid, like Guayaquil which is near the coast, while higher up areas where Cuenca and Quito are located will have both sunshine and rain most days. The temperature in Cuenca varies between 60º and 80º and you will want to wear a long sleeve shirt and a thin coat which you will want to take on and off throughout the day as the temperature changes. In a nutshell it never gets either too cold or too hot here in Cuenca.
Do I have to learn Spanish?
You will need to learn Spanish to really be comfortable living here; however you don't need Spanish, at least not in the larger cities. There are
many English speaking people here. In fact a surprising number of Ecuadorians speak English well and many can carry on a basic conversation in English.
Will I have a problem finding clothes?
There is a good selection of clothing here. The people here are pretty small so if you are six feet tall or more you will find the clothing selection
limited. For example you can get a new pair of brand name Levi jeans for $11.00 in one of the local street markets. If you have big feet, you will not be able to find shoes that will fit you. Ladies 9 1/2 shoes are hard to find here and men's size 11 or more are not available here.
Will I be able to get Internet?
Yes, high-speed Internet is available in the three main cities. You can get DSL through the phone company, cable internet through the cable TV company, or even get high-speed service through the cell towers. Out in the country, you can get high-speed Internet with a satellite dish, if no other methods are available.
What are the people like down there?
Most of the people here are respectful and hard working. They are more friendly than in western nations. They are less stressed, more laid back and not in a
hurry, especially the Indigenous people who live in the country. They seem to go out of their way to avoid confrontation. Family relationships are very important to the people here and family members tend to cooperate well with each other. There is very little anomosity towards North Americans here. In fact, many Ecuadorians have either lived in the US or Canada, or have a relative that lives there. They have a very positive attitude toward foreigners.
Why did the foreigners who live in Ecuador choose Ecuador over other South American countries?
Ecuador is very modern for a third world country. Land here is less expensive than in other S. American countries and the roads and conveniences are better here than in Paraguay and Bolivia where land is cheaper still. The Ecuadorian government is friendly to emmigrants and you are allowed to open bank accounts, become permanent residents, start businesses etc. without too much hassle. Other S. American countries do not have all the components for an enjoyable life, as does Ecuador. Many ex-patriots are happily intermingled with the Ecuadorian people & culture. They enjoy experiencing the natural beauty of Ecuador, having low
monthly living costs, and not having to sacrifice any of the comforts that they are accustomed to having in the United States.
What kind of public transportation do they have?
Cuenca has a pretty good bus system. It costs 25 cents to ride the bus and you can buy a bus card so that you don't have to keep using coins (which are
always in short supply here). It is easy to catch a taxi as there are so many roaming around that you usually don't have to wait more than three minutes
to get one. Short taxi trips cost $1.50 and you can go anywhere in the city for $5.00 or less.
Can I import my car?
You can import a car made within the last three years. If you want an older or classic car, you must buy it from somebody here because they won't let you
import it. Check the prices of cars they sell here first because you will be taxed.
What is there to do down there?
There are many types of tours, anything from biking, hiking and horseback riding into the mountains, exploring Inca ruins, shopping for Ecuadorian
souvenirs, seeing the country from a bus or in a private vehicle, hanging out at the beach, or touring the Galapagos islands. Cuenca has movie theaters, bowling alleys, shopping malls, disco tecs, concerts, rodeos, polo matches, soccer games, dancing lessons, many types of seminars from financial to religious, parks everywhere for family outings, plus visiting other ex-pats at the weekly Ex-Pat night. There are many retirement communities here that are made up of Americans and Canadians with many things available right within the retirement community. There is plenty to do here.
Your
information is safe with us... We will never
sell, trade, or give away your personal information! | http://movingtoecuador.net/faqs.html | CC-MAIN-2014-10 | refinedweb | 1,513 | 72.87 |
BREAK
Set a program breakpoint in the debugger
BREAK routine BREAK line BREAK routine:line BREAK label [/LABEL] BREAK . BREAK method BREAK method:line BREAK method#id BREAK method#id:line BREAK method#ALL BREAK method(signature) BREAK image/routine
Arguments
routine
Sets a breakpoint on entry to the specified routine.
line
Sets a breakpoint at the specified source line in the current routine.
routine:line
Sets a breakpoint at the specified source line in the specified routine.
label [/LABEL]
Sets a breakpoint at the specified label in the current routine.
.
(period) Sets a breakpoint at the current line in the current routine.
method
Sets a breakpoint on entry to the specified method.
method:line
Sets a breakpoint at the specified source line in the specified method.
method#id
Sets a breakpoint on entry to the specified implementation of the specified method.
method#id:line
Sets a breakpoint at the specified source line in the specified implementation of the specified method.
method#ALL
Sets a breakpoint on entry to all implementations of the specified method.
method(signature)
Sets a breakpoint on entry to an explicit method.
image/routine
Sets a breakpoint on entry to the specified routine that is inside the specified shared image. (OpenVMS only)
Discussion
The BREAK command sets a program breakpoint, which is a point at which your program stops and goes into the debugger.
You can specify two kinds of breakpoints: entry breakpoints and specific breakpoints. An entry breakpoint causes the program to break upon entering a routine. You can set a break at the entry to a routine using the BREAK routine syntax, and to a method using the BREAK method syntax. A specific breakpoint causes the program to break at a specific line in a routine or method. You can set a specific breakpoint using the BREAK line, BREAK routine:line, BREAK label, BREAK ., BREAK method:line, or BREAK method#id:line syntax.
When a breakpoint occurs, the break line has not yet been executed.
When specifying a line number with the BREAK routine or BREAK method syntax, the colon can be replaced with a space.
You can specify more than one breakpoint, separated by commas. If routine is not specified, the break specification is assumed to be for the current routine.
You can set breakpoints in routines that are .INCLUDEd into another routine. To do so, specify each one in the form
source_file#.line#
You can determine the source file number by viewing a listing file.
The maximum number of breakpoints is 32.
If you try to set a breakpoint in a method whose name is overloaded within the class or whose specified name matches methods in more than one class, the debugger presents a numbered selection list that includes the method name and its parameter types to allow you to select which method should have the breakpoint.
For example,
DBG> break testdrive Found multiple matches: 1: BREAKMETH.CAR.TESTDRIVE() 2: BREAKMETH.CAR.TESTDRIVE(A) 3: BREAKMETH.CAR.TESTDRIVE(A,A,I) *** Choose which breakpoint to set DBG> break testdrive #2 DBG> show break BREAKMETH.CAR.TESTDRIVE(A) on entry
You can either set the breakpoint using one of the unique identifiers, as shown above in the line
DBG> break testdrive #2
or you can set the breakpoint for all of them, like this:
DBG> break testdrive #all
You can use the method#id syntax at any time to set a breakpoint to a particular method, even without a set break attempt generating the list of overloaded methods.
You can alternatively specify an overloaded method by specifying the signature, or parameter list, enclosed in parentheses. (A method does not have to be overloaded to use this syntax, although the signature is not required for a nonoverloaded method.) For example,
BREAK mymethod(i, i)
or
BREAK myclass.mymethod(a, @Class1)
The parameter list is a comma-delimited list of one or more of the following parameter specifications:
Except for ^VAL and ^REF, each parameter specification can optionally be preceded by a dimension specification.
A method signature that has a real array parameter must specify it by a left square bracket ([) followed by the number of dimensions. A method signature that has a dynamic array parameter must specify it by a left curly brace ({) followed by the number of dimensions. In either case, if the number of dimensions is one, the number of dimensions may be omitted.
For example,
method mthd arg1, [*]a arg2, [*,*]d arg3, [#]@cls arg4, [#,#][#]@cls proc mreturn end BREAK ns.cls.mthd([A,[2D,{1@cls,{2{@cls)
If the signature doesn’t match a single method implementation exactly, the debugger displays a list of one or more choices, all having the same number of arguments as the signature you specified.
On OpenVMS, you can also set breakpoints in routines inside a shared image using the BREAK image/routine syntax. To do so, you must have done the following when linking the shared image file:
- Included $ELB_DBGn=DATA within the “SYMBOL_VECTOR=” line of the options file used
- Included DBLDIR:elbn.obj
By linking different shared images against different object files, you can specify up to five debuggable shared images in the same application. Linking with an elb.obj file (elb.obj, elb1.obj, elb2.obj, elb3.obj, or elb4.obj) and adding the corresponding vector ($ELB_DBG=DATA, $ELB_DBG1=DATA, $ELB_DBG2=DATA, $ELB_DBG3=DATA, $ELB_DBG4=DATA, respectively) enables the OpenVMS runtime to find the list of routines in the shared image so the debugger can find the routines in the shared image. The logical used to reference the shared image must be used as the image part of the image/routine break specification.
Examples
The following example sets a breakpoint at lines 7 and 10 in the current routine and also at line 5 in routine ABC.
BREAK 7, abc 5, 10
The following OpenVMS example sets a breakpoint at the entry of the post_data routine in the shared image referenced by the MCBA_LIB logical.
BREAK MCBA_LIB/post_data
The example below shows a breakpoint being set in a .INCLUDEd routine.
Break at 4 in MYFILE (myfile.dbl) on entry 4> xcall flags(1001010, 1) DBG> set break 2.2 DBG> go Break at 2.2 in MYFILE (MYFILEA.DBL) 2.2> nop DBG> step Step to 2.3 in MYFILE (MYFILEA.DBL) 2.3> writes(1, "Exiting include file")
The example below breaks at line 14 within the method mynamespace.myclass.mymethod.
BREAK mynamespace.myclass.mymethod:14
The following example breaks in the third method of myclass at line 53.
BREAK myclass#3:1.53 | https://www.synergex.com/docs/tools/toolsChap2BREAK.htm | CC-MAIN-2020-34 | refinedweb | 1,093 | 55.24 |
import "encoding/csv"
Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.") // TrailingComma bool // Deprecated: No longer used. //.
The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses..
As returned by NewWriter, a Writer writes records terminated by a newline and uses ',' as the field delimiter. The exported fields can be changed to customize the details before the first call to Write or WriteAll.
Comma is the field delimiter.
If UseCRLF is true, the Writer ends each output line with \r\n instead of \n.
The writes of individual records are buffered. After all data has been written, the client should call the Flush method to guarantee all data has been forwarded to the underlying io.Writer. Any errors that occurred should be checked by calling the Error) and is imported by 5550 packages. Updated 2020-06-02. Refresh now. Tools for package owners. | https://godoc.org/encoding/csv | CC-MAIN-2020-29 | refinedweb | 186 | 64.91 |
Even the defense department security protocols are breached on occassion. So, to
think that the security policies we've put in place are 100% fool proof is
a bit naive. Securing applications is all about determining risk if a breach
occurs, lowering that level of risk, and reducing the number of people who are
technically knowledgeable enough to pull it off (and not all attackers have the
same skillset or background).
The end goal is to make it take more effort to breach your security protocols than
it is worth. Of course, this is easier said than done and often requires numerous
small steps to achieve. Personally, I like to apply both known best practices,
obfuscation, encryption, and a healthy amount of purposeful confusion.
Every application and its data is different which makes writing an article that gives
you a complete set of best practices impractical. What I'll do instead is
to give you some things to think about and some suggestions as to how you might
address them. For now, I'll focus strictly on Silverlight applications that
reference your WCF service. A typical Silverlight / WCF architecture looks a
little like this:
Silverlight -> SSL -> WCF Service -> Business Logic -> DataBase
Silverlight <- SSL <- WCF Service <- Business Logic <- DataBase
The areas in red represent potential security holes and the areas in green are your
last line of defense. Not only is Silverlight a red area but so is the SSL secured
network traffic between itself and the WCF service.
WCF Suggestions
1. ClientAccessPolicy.xml
This file helps you control which domains have access to call your WCF service. Here
is a very basic example of how you can restrict access to only those applications
running under your desired domain. This permits someone running your Silverlight
application from both a secure and a non-secure url.
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from
<domain uri=""/>
<domain uri=""/>
</allow-from>
<grant-to>
<resource path="/" include-
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
2. Secured Socket Layer Certificates (SSL)
Use secure socket layer certificates to protect "most" sets of prying eyes
from monitoring unencrypted network traffic. This requires an increased level
of expertise, hardware, and software to monitor your data transmissions. Assume
that someone knows how to use a networking tool like Fiddler to monitor your
Silverlight application's network traffic and thus discover your WCF service
url. Also assume they know how to use Fiddler's capability to decrypt SSL
encrypted traffic.
Yes, every piece of data you transmit back and forth from your Silverlight application
to your WCF service can be decrypted by tools like Fiddler. This refers specifically
to data you did not encrypt inside your application(s) and only to data encrypted
automatically via the SSL certificate. They would just fire up Fiddler and configure
it to decrypt SSL traffic. Then, launch your Silverlight application in their
browser. Fiddler would immediately decrypt all traffic to and from your Silverlight
application as it transmits/receives data from your WCF service. If you have
ever heard of "man in the middle" attacks, this is a good example of
a simplistic one.
All of that said, unless the end user is running an unsecured wireless configuration
on their laptop, the risk is low that your WCF service would expose something
to a hacker that is potentially harmful to another user.
However, you also need to protect your service from exposing information to your
user that you only want your Silverlight application to see. Application secrets
or proprietary company information that no one should ever see come to mind.
The rule of thumb I use when sending secrets over SSL is that if you don't
absolutely need to send it, don't.
Here is just one example. If your application retrieves user accounts other than
the hacker's own account, they could decrypt SSL encrypted strings and expose
passwords belonging to other users. Even if the password itself is encrypted
in the database, having the encrypted value is one step closer to a breach. Since
the Silverlight application doesn't need to use the passwords of these other
users, one option is that we could just clear that property value in the WCF
service. You will need to evaluate the risk of sending each and every class property
over SSL and make the appropriate adjustments.
3. WCF Service Meta Data
If your service is only going to be used by your applications, you should not publicly
expose the meta data. It is the meta data that enables someone to most easily
determine what your service, operation, message, and data contracts look like.
Many client applications dynamically assign their web service urls at runtime.
However, your Silverlight application does not need to see the WCF service meta
data in order to create the endpoint binding to a different production web service
url at runtime.
Why not? When you created a service reference to your WCF service running on localhost,
those classes created by Visual Studio .NET that act as your service reference
can be pointed to a different service url at runtime. The classes are tied directly
to ServiceContract namespaces but not to the actual web service url. As long
as the service contracts that exist in your development environment are the same
as those you've deployed to production, it will work properly.
To hide the meta data, you should remove the highlighted line below from your web.config
file when you deploy this to production:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service behaviorConfiguration="Your Service Behavior Name" name="Your Service Name">
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>
Also, you'll need to change the highlighted properties from true to false:
<behaviors>
<serviceBehaviors>
<behavior name="Your Service Behavior Name">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
4. Alter your service contract namespaces
[ServiceContract(Namespace = "")]
public interface IServiceReference1
Various ServiceContract attributes will show up in the service references created by Visual Studio .NET.
Many of these references are not obfuscated or string encrypted (obfuscation
discussed in the Silverlight suggestions section) by obfuscation tools. They
are clearly visible using Reflector (also discussed below). So, make sure people
can see only what you want them to see. One last thing, if you change some of
these attributes, you will need to update the service reference in your Silverlight
application.
5. Customized Access Tokens
I like to require one or more custom access tokens be passed in to each WCF service
operation. The WCF operation would be responsible for validating the token prior
to operation execution.
6. Assume You Will Fail To Secure Your WCF Service
Someone with the right know-how and motivation may get by steps 1 through 4. You
should carefully review each WCF operation and what it does in order to determine
the risk if that operation is called inappropriately. Keep in mind, your operation
contracts can be called in any order and at anytime. You can't trust that
a series of steps has taken place prior to the execution of the contract. Also,
critical operations should not trust that the values of their input parameters
have come from their own client application or the user designated as having
sent them.
Add extra parameters in these critical operation contracts requiring the user to
authenticate, validate permissions, retrieve existing records, and compare ownership/access
rights prior to allowing the query, data change, or data delete to occur. Not
every operation contract requires this level of complexity. Operation contracts
that return look up tables probably would not qualify. An operation contract
that enables user passwords to be changed probably would.
Silverlight Suggestions
1. Assembly Obfuscation and String Encryption
As I'm sure you know, tools like Reflector are out there that will let anyone
disassemble your .NET assemblies into readable and usable source code. Obfuscation
and string encryption of your assemblies makes this much, much more difficult.
There are numerous third party .NET obfuscation and encryption tools. The free versions
typically aren't secure enough for corporate applications. Most of these
tools are used on a single build machine. It is important to note that many obfuscation
tools do not come preconfigured to obfuscate Silverlight assemblies. You will
most likely need to include the paths to your version of Silverlight in their
user defined assembly path section.
After you have compiled your application into a .xap file (compressed file containing
your compiled Silverlight assemblies) via Visual Studio .NET, copy your .xap
file over to your build machine, obfuscate, string encrypt, and then zip up the
obfuscated assemblies into your deployable .xap file. You could use WinZip, 7Zip,
or just about any other compression tool to recreate your .xap file.
Most current obfuscation software will cause your Silverlight application to choke
at runtime if you attempt to obfuscate an assembly with XAML in it. They just
don't handle this well. So, keep all mission critical C# code that you don't
want people to see (which means every single line you can possibly obfuscate
:) in separate assemblies. The Model/View/ViewModel pattern takes care of this
for us if you put the Model and ViewModel in different assemblies from the View.
Follow the pattern and you'll end up with XAML code behind classes that you
could care less whether someone can view.
2. Runtime Reflection
You may be tempted to hard code secrets into your assemblies versus exposing even
an encrypted value in a config file. Should you do this, remember that these
secrets can be extracted at runtime using reflection. As an example, someone
could take your .xap file from their browser cache, decompress it, and then include
some of your assemblies in their own Silverlight application. Fire up the debugger
in Visual Studio .NET and start stepping through code looking at method return
values and property values.
Paste the following code in a .NET console application and you'll see what I'm
referring to. Notice how it
was even able to extract values of private class level variables. However, Reflection
cannot interrogate local variables declared inside methods and event handlers.
using System;
using System.Diagnostics;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var blog = new Blog();
var fieldInfos = blog.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fieldInfos)
{
Debug.WriteLine(fieldInfo.Name +" "+ fieldInfo.GetValue(blog));
}
}
}
class Blog
{
private string _test = "this is a reflection test.";
public string MyProperty { get; set; }
}
}
Another trick centers around hard coded strings that you may think are hidden by
using the obfuscation and string encryption process. You are partially correct.
Tools like Reflector won't be able to expose the string encrypted value but
runtime Reflection certainly could.
If you really need to store critical secret hard coded strings, ask yourself if the
Silverlight application needs to decrypt them or not. If not, encrypt the string
via some other tool (maybe a whipped up console app of yours) and paste the encrypted
string in your code instead and remove all references to the encryption key from
your application (and never transmit it to or from your Silverlight application).
Again, it is just one more level complexity for someone to have to work through.
3. Silverlight 3.0 Does Not Support Code Access Security
Without getting into too much detail, I often place very low level hidden environment
oriented checks in various assemblies preventing their misuse outside my applications.
Let your imagination run wild here.
4. Wrap Business Logic Classes Around WCF Service Clients
Try to set as much of your code that directly interacts with your WCF service reference
to private or internal. Only expose your wrapper methods and event handlers to
the public interface. This makes misuse of your own assemblies to call your WCF
service inapproriately that much harder to do.
5. Purposeful Confusion
I have also been known to purposely provide inaccurate error messages, config settings,
urls, and a wide variety of other pieces of information to make diagnosing failed
hack attempts that much more difficult. Don't tell them anymore than is absolutely
necessary and attempt to track failed actions. Just because they failed doesn't
mean they didn't get close. Clues as to what types of attempts are being
made can help you refine your security plan.
6. Lock Down Source Control Of Key Assemblies
This is pretty much standard practice. If you have things in your Silverlight or
WCF code you don't want the outside world to see, you should reduce the number
of your own internal software developers that have access to it. Nothing like
a knowledgable disgruntled employee attempting to create issues for you.
Summary
As I mentioned above, nothing is 100% fool proof but I think these suggestions used
in conjunction with one another can go a long way toward securing your applications
or at the very least making them a pain to disect. Of course, there are other
things I do but would prefer not to make them public.
There are a lot of creative and knowledgable people out there. If you are one of
them and would like to contribute additional suggestions, please add your comments
at the bottom of this article. | http://www.nullskull.com/a/1373/silverlight-wcf-security-and-things-you-might-not-know.aspx | CC-MAIN-2015-32 | refinedweb | 2,211 | 53.1 |
By Ishan Shah
After reading this, you will be able to:
- Cross validate whether your model is good in predicting buy signal and/or sell signal
- Demonstrate the performance of your model in different stress scenarios
- Comprehensively validate your model
But before I explain how to cross-validate in machine learning model, I will first create a sample machine learning decision tree classifier model using price data of the Apple stock. Then, I’ll implement various cross validation measures on this model.
To implement this in Python, I’ll follow below steps
- Importing the necessary libraries
- Fetching the data
- Defining the input and output dataset
- Training the machine learning model
If you are already well versed with these steps and Python coding then you can skim through this part.
Importing the libraries
import quantrautil as q import numpy as np from sklearn import tree
The libraries imported above will be used as follows:
- quantrautil – this will be used to fetch the price data of the AAPL stock from yahoo finance.
- numpy – to perform the data manipulation on AAPL stock price to compute the input features and output. If you want to read more about numpy then it can be found here.
- tree from sklearn – Sklearn has a lot of tools and implementation of machine learning models. ‘tree’ will be used to create Decision Tree classifier model.
Fetching the data
The next step is to import the price data of AAPL stock from quantrautil. The get_data function from quantrautil is used to get the AAPL data for 19 years from 1 Jan 2000 to 31 Dec 2018 as shown below. The data is stored in the dataframe aapl.
aapl = q.get_data('aapl','2000-1-1','2019-1-1') print(aapl.tail())
[*********************100%***********************] 1 of 1 downloaded Open High Low Close Adj Close \ Date 2018-12-24 148.149994 151.550003 146.589996 146.830002 146.830002 2018-12-26 148.300003 157.229996 146.720001 157.169998 157.169998 2018-12-27 155.839996 156.770004 150.070007 156.149994 156.149994 2018-12-28 157.500000 158.520004 154.550003 156.229996 156.229996 2018-12-31 158.529999 159.360001 156.479996 157.740005 157.740005 Volume Date 2018-12-24 37169200 2018-12-26 58582500 2018-12-27 53117100 2018-12-28 42291400 2018-12-31 35003500
Creating input and output dataset
In this step, I will create the input and output variable.
- Input variable: I have used ‘(Open-Close)/Open’, ‘.
The choice of these features as input and output is completely random. If you are interested to learn more about feature selection, then you can read here.
# Features construction aapl['Open-Close'] = (aapl.Open - aapl.Close)/aapl.Open aapl['High-Low'] = (aapl.High - aapl.Low)/aapl.Low aapl['percent_change'] = aapl['Adj Close'].pct_change() aapl['std_5'] = aapl['percent_change'].rolling(5).std() aapl['ret_5'] = aapl['percent_change'].rolling(5).mean() aapl.dropna(inplace=True) # X is the input variable X = aapl[['Open-Close', 'High-Low', 'std_5', 'ret_5']] # Y is the target or output variable y = np.where(aapl['Adj Close'].shift(-1) > aapl['Adj Close'], 1, -1)
Training the machine learning model
All set with the data! Let’s train a decision tree classifier model. The DecisionTreeClassifier function from tree is stored in variable ‘clf’ and then a fit method is called on it with ‘X’ and ‘y’ Dataset as the parameters so that the classifier model can learn the relationship between X and y.
clf = tree.DecisionTreeClassifier(random_state=5) model = clf.fit(X, y)
The model is ready. But how do we validate this model? If this model is validated or tested on the same data from which the model learned then it is a no brainer that the performance of the model is bound to be spectacular.
from sklearn.metrics import accuracy_score print('Correct Prediction: ', accuracy_score(y, model.predict(X), normalize=False)) print('Total Prediction: ', X.shape[0])
Correct Prediction: 4775 Total Prediction: 4775
As you can see above, all the predictions are correct.
But there is a lot of Python code here. Yes! accuracy_score is a function from sklearn.metrics package which tells you how many predictions are correct. It takes as input the actual output (y) and predicted output (model.predict(X)), compares both the inputs and tells us how many of them were correct. If you want to see the output in percentage then set the normalize parameter to True as done below.
print(accuracy_score(y, model.predict(X), normalize=True)*100)
100.0
How do you overcome this problem of using the same data for training and testing?
One of the easiest and most widely used ways is to partition the data into two parts where one part of the data (training dataset) is used to train the model and the other part of the data (testing dataset) is used to test the model.
# Total dataset length dataset_length = aapl.shape[0] # Training dataset length split = int(dataset_length * 0.75) split
358)
(3581, 4) (1194, 4) (3581,) (1194,)
In the above code, the total dataset of 3581 points is divided into two parts; first 75% of dataset creates X_train and y_train which contains the dataset to train the model and the remaining 25% of dataset creates X_test and y_test which contains the dataset to test the model. The choice of 75% is random.
# Create the model on train dataset model = clf.fit(X_train, y_train)
# Calculate the accuracy accuracy_score(y_test, model.predict(X_test), normalize=True)*100
49.413735343383586
If you test the model on test dataset then a significant drop in accuracy is seen from 100% to 49.41%. The model performance in test dataset is closer to what you can expect if you take this model for live trading. However, there is still a major problem. The model is validated on a single test dataset. In this example, on last 1194 data points. It could be by sheer luck that this model was able to predict with 49.41% in the test dataset. If I change the length of the train-test split from 75% to 80% or use different data points say first 1194 data points, then the accuracy of the model can vary a lot. Therefore, there is a need to test on multiple unseen datasets. But how do you achieve this?
K-Fold
Don’t worry! K-fold technique, one of the most popular methods helps to overcome these problems.
This method splits your dataset into K equal or close-to-equal parts. Each of these parts is called a “fold”. For example, you can divide your dataset into 4 equal parts namely P1, P2, P3, P4. The first model M1 is trained on P2, P3, and P4 and tested on P1. The second model is trained on P1, P3, and P4 and tested on P2 and so on. In other words, the model i is trained on the union of all subsets except the ith. The performance of the model i is tested on the ith part.
When this process is completed, you will end up with four accuracy values, one for each model. Then you can compute the mean and standard deviation of all the accuracy scores and use it to get an idea of how accurate you can expect the model to be.
Some questions that you might have.
How do you select the number of folds?
The choice of the number of folds must allow the size of each validation partition to be large enough to provide a fair estimate of the model’s performance on it and shouldn’t be too small, say 2, such that we don’t have enough trained models to validate.
Why is this better than the original method of a single train and test split?
Well, as discussed above that by choosing a different length for the train and the test data split, the model performance can vary quite a bit, depending on the specific data points that happen to end up in the training or testing dataset. This method gives a more stable estimate of how the model is likely to perform on average, instead of relying completely on a single model trained using a single training dataset.
How can you test the model on a dataset which is prior to the dataset used to train the model? Is it not historically accurate?
If you train the model on a data from January 2010 to December 2018 and test on data from January 2008 to December 2009. Rightly so, the performance which we will obtain from the model will not be historically accurate. One of the limitations of this method. However, from the other side, this method can help to validate how the model would have performed in the stress scenarios such as 2008. For example, when investors ask how the model would perform if stress scenarios such as the dot com bubble, housing bubble, or qe tapering occur again. Then, you can show the out-of-sample results of the model when such scenarios occurred. That should be likely performance when such scenarios occur again.
Code K-fold in Python
To code, KFold function from sklearn.model_selection package is used. You need to pass the number of splits required and whether to shuffle (True) the data points or not (False) to shuffle it and store it in a variable say kf. Then, call split function on kf and X as the input. The split function splits the index of the X and returns an iterator object. The iterator object is iterated using for loop and the integer index of train and test is printed.
from sklearn.model_selection import KFold kf = KFold(n_splits=4,shuffle=False)
kf.split(X)
print("Train: ", "TEST:") for train_index, test_index in kf.split(X): print(train_index, test_index)
Train: TEST: [1194 1195 1196 ... 4772 4773 4774] [ 0 1 2 ... 1191 1192 1193] [ 0 1 2 ... 4772 4773 4774] [1194 1195 1196 ... 2385 2386 2387] [ 0 1 2 ... 4772 4773 4774] [2388 2389 2390 ... 3579 3580 3581] [ 0 1 2 ... 3579 3580 3581] [3582 3583 3584 ... 4772 4773 4774]
The total dataset of 4775 points is divided into four different ways. For the first fold, the points 0 to 1193 are used as test dataset and the points 1194 to 4774 are used as train dataset and so on.
I’ll create four different models for each of the fold shown above and determine the accuracy for each of the models. Again, this will be done through a for loop, by calling the fit method to train the model and by calling accuracy_score to determine the accuracy of the model.
# Initialize the accuracy of the models to blank list. The accuracy of each model will be appended to this list accuracy_model = [] # Iterate over each train-test split for train_index, test_index in kf.split(X): # Split train-test X_train, X_test = X.iloc[train_index], X.iloc[test_index] y_train, y_test = y[train_index], y[test_index] # Train the model model = clf.fit(X_train, y_train) # Append to accuracy_model the accuracy of the model accuracy_model.append(accuracy_score(y_test, model.predict(X_test), normalize=True)*100) # Print the accuracy print(accuracy_model)
[50.502512562814076, 49.413735343383586, 51.75879396984925, 49.79044425817267]
Stability of the model
Let’s determine the variation and average accuracy of the model by calling the standard deviation and mean function from the numpy package.
np.std(accuracy_model)
0.8939494614206329
np.mean(accuracy_model)
50.3663715335549
The accuracy of the model is 50.36% +/- 0.89%. This is more likely to be the behaviour of the model in live trading.
Confusion Matrix
With the above accuracy, you got an idea about the accuracy of the model. But what is the model’s accuracy in predicting each label such as Buy and Sell? This can be determined by using the confusion matrix. In the above example, the confusion matrix will tell you the number of times the actual value was buy and predicted was also buy, actual value was buy but predicted was sell and so on.
# Import the pandas for creating a dataframe import pandas as pd # To calculate the confusion matrix from sklearn.metrics import confusion_matrix # To plot %matplotlib inline import matplotlib.pyplot as plt import seaborn as sn # Initialize the array to zero which will store the confusion matrix array = [[0,0],[0,0]] # For each train-test split: train, predict and compute the confusion matrix for train_index, test_index in kf.split(X): # Train test split X_train, X_test = X.iloc[train_index], X.iloc[test_index] y_train, y_test = y[train_index], y[test_index] # Train the model model = clf.fit(X_train, y_train) # Calculate the confusion matrix c = confusion_matrix(y_test, model.predict(X_test)) # Add the score to the previous confusion matrix of previous model array = array + c # Create a pandas dataframe that stores the output of confusion matrix df = pd.DataFrame(array, index = ['Buy', 'Sell'], columns = ['Buy', 'Sell']) # Plot the heatmap sn.heatmap(df, annot=True, cmap='Greens', fmt='g') plt.xlabel('Predicted') plt.ylabel('Actual') plt.show()
From the above confusion matrix, if you focus on the darker green zone (1306), that is when actual value was sell and model also predicted sell. Then, out of 2509 (1306+1203) times, the model was right 1306 times when it predicted the sell signal. That is an accuracy of 52%. From this, we can infer that the model is better in predicting the sell signal compared to the buy signal.
Time to say goodbye! I hope you enjoyed reading this blog. Do share your feedback, comments, and request for the blogs.
Cross validation is an important tool in the trader’s handbook as it helps the trader to know the effectiveness of their strategies. Now that you know the methodology of cross-validation, you should check the course on Artificial Intelligence and test the effectiveness of the models..
Suggested reads:
Working Of Neural Networks For Stock Price Prediction
The post Cross Validation In Machine Learning Trading Models appeared first on .
This post first appeared on Best Algo Trading Platforms Used In Indian Market, please read the originial post: here | https://www.blogarama.com/blogging-blogs/1287370-best-algo-trading-platforms-used-indian-market-blog/28800567-cross-validation-machine-learning-models | CC-MAIN-2019-09 | refinedweb | 2,338 | 64.71 |
Re: How to get the Bluetooth module working (JYMCU...)?
Posted: Fri Dec 05, 2014 10:13 pm
I continued in turbinreiters thread instead. better to keep it in one thread.
Online community discussing all things related to MicroPython
Code: Select all
import pyb def bt_tx(data): # Transmit data, wait, check for received data and print it print('\nTransmitting: ', data) n = uart.write(data_tx) pyb.delay(100) # Maybe not needed data_rx = uart.read() print('\tReceived: ', data_rx) pyb.delay(100) # Maybe not needed # rescue_mode = False rescue_mode = True sw = pyb.Switch() pyb.LED(1).off() pyb.LED(2).on() p_key = pyb.Pin('X1', pyb.Pin.OUT_PP) # AT mode can be initialised in two ways # 1: Key-pin low at power up => use configured rate # 2: Key-pin high at power up => use 38400 BPS if(rescue_mode): p_key.high() # AT commands to be sent at 38400 BPS uart = pyb.UART(1, 38400) else: p_key.low() # AT commands to be sent at configured BPS uart = pyb.UART(1, 9600) print('Disconnect and reconnect power to bluetooth module') print('Click switch') # Red LED on HC-05 blinks fast in normal mode, slow in rescue mode wait = True while(wait): if sw(): pyb.LED(1).on() pyb.LED(2).off() wait = False p_key.high() # High for normal AT-mode # Check if AT mode is working, module should respond with 'OK' data_tx = 'AT\r\n' bt_tx(data_tx) # Ask module for version data_tx = 'AT+VERSION?\r\n' bt_tx(data_tx) # Ask module for name data_tx = 'AT+NAME?\r\n' bt_tx(data_tx) # Set new module name data_tx = 'AT+NAME=MicroPython HC-05\r\n' bt_tx(data_tx) # Ask module for name data_tx = 'AT+NAME?\r\n' bt_tx(data_tx) | https://forum.micropython.org/viewtopic.php?f=2&t=429&start=10&view=print | CC-MAIN-2019-09 | refinedweb | 276 | 67.25 |
In previous versions of the AIRFacebook ANE (v1.0.3 and older), the only way to retrieve results of various async requests was with the use of the standard Flash event model. You added your desired event to the dispatcher, created corresponding handler, made the request, removed the event from the dispatcher and played around with the event object that you received. After all, that is what AS3 devs have been doing for years, until signals happened. All in all, nothing too wrong with that; except, it creates room for errors which in turn make the development slower. You have to know what event will be dispatched before making the request and you have to remove the event from the dispatcher so that your handler doesn’t receive result from a request you make later in other scope of your app.
So I thought about adding Function parameter to request methods that would serve as a callback. But the Function data type in AS3 doesn’t really give you any idea about the function’s signature so every request would involve checking the documentation to see what signature the callback should have. Since most of the AS3 IDEs provide great code completion and generation features, I decided to use interfaces to handle all the different request results. Thanks to these interfaces, you can either implement them in the class that makes the request or even create custom listener objects. Here is a quick look:
// Implements login listener so it can handle AIRFacebook's login response public class LoginScreen implements IAIRFacebookLoginListener { ... private function onLoginButtonTriggered():void { /* Assuming AIRFacebook is initialized */ // Passing 'this' as a listener AIRFacebook.loginWithReadPermissions( new <String>["birthday"], this ); } ... /* Implemented methods of 'IAIRFacebookLoginListener' */ public function onFacebookLoginSuccess( deniedPermissions:Vector.<String>, grantedPermissions:Vector.<String> ):void { // Do your stuff } public function onFacebookLoginCancel():void { // Do your stuff } public function onFacebookLoginError( errorMessage:String ):void { // Do your stuff } }
As you can see, it’s very simple to use the interface to implement login callbacks. You don’t have to worry about removing the listener (it’s used for that particular request only) and all the returned data is part of the defined method’s signature so there’s no need to explore any event object to see what it has to offer. And thanks to great IDE like IntelliJ IDEA all it takes is couple of keyboard taps to implement the appropriate listener. Also, you get a compile-time error checking. As of AIRFacebook v1.2 every request method accepts (optional) object that implements one of the listener interfaces. Of course, the standard events are still fully functional and available to use.
But, there is always a but… I should mention, there are cases where these listeners are bit of a drawback. Imagine that somewhere in your app you are working with Open Graph (for example, posting and getting user’s score). These are two different requests, yet they are handled by a single listener (IAIRFacebookOpenGraphListener – if implemented as in the example above). So unless you add some code inside your callbacks to check what data you’ve retrieved, you don’t know which request’s data you are currently working with. There are at least three solutions to this issue:
(1) Welcome back, events!
You still have the choice of using the good ol’ events and they’re probably the fastest way to solve this problem, since you can associate the requests with different handlers (as long as you make the next request after getting the result of the previous one).
(2) Control flag(s)
You could add a Boolean flag (isGetScoreQuery) and set it to true/false before making a request. That way you would know if the result is from the GET or the POST query (again, as long as the requests are sent one after another). If there are more requests, you could use an integer as a flag and use a switch statement to control the execution flow. Not the prettiest but gets the job done.
(3) Custom listener objects
If AS3 allowed for creating anonymous classes in Java like fashion this solution would be a lot simpler. Since we cannot do that it involves a bit more code and is probably not worth doing in most cases, unless you want to make several requests at the same time and still want to know which request the returned data corresponds to. So this is where custom listener object comes into place. This object is simply an instance created by our screen class (or whoever makes the Open Graph request) and is used as a listener instead of the screen. We could create a private class in our screen like this:
public class OpenGraphScreen { ... private function onGetScoreButtonTriggered():void { // Passing our custom object as a listener AIRFacebook.requestScores( new GetScoreListener( this ) ); } ... /* Called by our custom listener */ public function onGetScoreSuccess( jsonResponse:Object, rawResponse:String ):void { } /* Called by our custom listener */ public function onGetScoreError( errorMessage:String ):void { } } // OpenGraphScreen class end /* Inside OpenGraphScreen.as */ class GetScoreListener implements IAIRFacebookOpenGraphListener { private var mTarget:OpenGraphScreen; public function GetScoreListener( target:OpenGraphScreen ):void { mTarget = target; } /* Implemented methods of 'IAIRFacebookOpenGraphListener' */ public function onFacebookOpenGraphSuccess( jsonResponse:Object, rawResponse:String ):void { mTarget.onGetScoreSuccess( jsonResponse, rawResponse ); mTarget = null; } public function onFacebookOpenGraphError( errorMessage:String ):void { mTarget.onGetScoreError( errorMessage ); mTarget = null; } }
You’d create another class PostScoreListener and use it in the same way as the GetScoreListener.
So that was a quick look at the new listener API. You can check out the updated GitHub demo app to see more examples. | https://marpies.com/2015/09/using-airfacebook-listener-interfaces/ | CC-MAIN-2018-13 | refinedweb | 913 | 51.38 |
Linear Programming
Combinatorial Problem Solving (CPS)
Enric Rodrguez-Carbonell
min cT x min cT x
A1 x b1 A1 x b1
A2 x = b2 A2 x = b2
A3 x b3 A3 x b3
x Rn i I : xi Z
i 6 I : xi R
2 / 31
CPLEX Toolkit
CPLEX allows one to work in several ways. CPLEX is...
Java
C
C++ (Concert Technology)
...
3 / 31
Concert Technology
Two kinds of objects:
4 / 31
Creating the Environment: IloEnv
The class IloEnv constructs a CPLEX environment.
The environment is the first object created in an application.
To create an environment named env, you do this:
IloEnv env ;
5 / 31
Creating a Model: IloModel
After creating the environment, a Concert application is ready to create
one or more optimization models.
Objects of class IloModel define a complete model that can be later
passed to an IloCplex object.
To construct a modeling object named model, within an existing
environment named env, call:
IloModel model ( env );
6 / 31
Creating a Model: IloModel
After an IloModel object has been constructed, it can be populated with
objects of classes:
7 / 31
Creating a Model: IloModel
Modeling variables are constructed as objects of class IloNumVar, e.g.:
IloNumVar x ( env , 0 , 40 , ILOFLOAT );
8 / 31
Creating a Model: IloModel
After all the modeling variables have been constructed,
they can be used to build expressions,
which are used to define objects of classes IloObjective, IloRange.
To create obj of type IloObjective representing an objective function
(and direction of optimization):
IloObjective obj = IloMinimize ( env , x +2* y );
9 / 31
Creating a Model: IloModel
Actually in
model . add ( - x + 2* y + z <= 20);
10 / 31
Solving the Model: IloCplex
The class IloCplex solves a model.
After the optimization problem has been stored in an IloModel object
(say, model), it is time to create an IloCplex object (say, cplex) for
solving the problem:
IloCplex cplex ( model );
11 / 31
Solving the Model: IloCplex
More precise information about the outcome of the last call to the
method solve can be obtained by calling:
cplex . getStatus ();
12 / 31
Querying Results
Query methods access information about the solution.
Numbers in solution, etc. are of type IloNum
To query the solution value for a variable:
IloNum v = cplex . getValue ( x );
13 / 31
Querying Results
To get the values of the slacks of an array of constraints:
IloRangeArray c ( env );
...
IloNumArray v ( env );
cplex . getSlacks (v , c );
14 / 31
Querying Results
To get values of reduced costs of an array of variables:
IloNumVarArray x ( env );
...
IloNumArray v ( env );
cplex . getReducedCosts (v , x );
15 / 31
Querying Results
Output operator << is defined for type IloAlgorithm::Status returned
by getStatus, as well as for IloNum, IloNumVar, ...
<< is also defined for any array of elements
if the output operator is defined for the elements.
Default names are of the form IloNumVar(n)[..u] for variables, and
similarly for constraints, e.g.,
IloNumVar (1)[0..9] + IloNumVar (3)[0.. inf ] <= 20
16 / 31
Writing/Reading Models
CPLEX supports reading models from files and
writing models to files in several languages (e.g., LP format, MPS format)
To write the model to a file (say, model.lp):
cplex . exportModel ( " model . lp " );
IloCplex decides which file format to write based on the extension of the
file name (e.g., .lp is for LP format)
This may be useful, for example, for debugging
17 / 31
Languages for Linear Programs
MPS
Very old format ( age of punched cards!) by IBM
Has become industry standard over the years
Column-oriented
Not really human-readable nor comfortable for writing
All LP solvers support this language
LP
CPLEX specific file format
Row-oriented
Very readable, close to mathematical formulation
Supported by CPLEX, GUROBI, GLPK, LP SOLVE, ..
(which can translate from one format to the other!)
18 / 31
Example: Product Mix Problem
A company can produce 6 different products P1 , . . . , P6
Production requires labour, energy and machines, which are all limited
The company wants to maximize revenue
The next table describes the requirements of producing one unit of each
product, the corresponding revenue and the availability of resources:
P1 P2 P3 P4 P5 P6 Limit
Revenue 5 6 7 5 6 7
Machine 2 3 2 1 1 3 1050
Labour 2 1 3 1 3 2 1050
Energy 1 2 1 4 1 2 1080
19 / 31
Example: Product Mix Problem
MODEL:
xi = quantity of product Pi to be produced.
20 / 31
LP Format
\ Product-mix problem (LP format)
max
revenue: 5 x_1 + 6 x_2 + 7 x_3 + 5 x_4 + 6 x_5 + 7 x_6
subject to
end
21 / 31
MPS Format
* Product-mix problem (Fixed MPS format)
*
* Column indices
*00000000111111111122222222223333333333444444444455555555556666666666
*23456789012345678901234567890123456789012345678901234567890123456789
*
* mrevenue stands for -revenue
*
NAME PRODMIX
ROWS
N mrevenue
L machine
L labour
L energy
COLUMNS
x_1 mrevenue -5 machine 2
x_1 labour 2 energy 1
x_2 mrevenue -6 machine 3
x_2 labour 1 energy 2
x_3 mrevenue -7 machine 2
x_3 labour 3 energy 1
x_4 mrevenue -5 machine 1
x_4 labour 1 energy 4
x_5 mrevenue -6 machine 1
x_5 labour 3 energy 1
x_6 mrevenue -7 machine 3
x_6 labour 2 energy 2
RHS
RHS1 machine 1050 labour 1050
RHS1 energy 1080
ENDATA
22 / 31
LP Format
Intended for representing LPs of the form
min / max cT x
aTi x i bi (1 i m, i {, =, })
xu ( k , uk +)
23 / 31
LP Format
1. Objective function section
2. Constraints section
(a) Keyword subject to (or equivalently: s.t., st, such that)
(b) List of constraints, each in a different line
24 / 31
LP Format
3. Bounds section (optional)
(a) Keyword Bounds
(b) List of bounds, each in a different line
l <= x <= u: sets lower and upper bounds
l <= x : sets lower bound
x >= l : sets lower bound
x <= u : sets upper bound
x = f: sets a fixed value
x free : specifies a free variable
26 / 31
Example 1
Let us see a program for solving:
27 / 31
Example 1
# include < ilcplex / ilocplex .h >
ILOSTLBEGIN
int main () {
IloEnv env ;
IloModel model ( env );
IloNumVarArray x ( env );
x . add ( IloNumVar ( env , 0 , 40));
x . add ( IloNumVar ( env )); // default : between 0 and +
x . add ( IloNumVar ( env ));
model . add ( - x [0] + x [1] + x [2] <= 20);
model . add ( x [0] - 3 * x [1] + x [2] <= 30);
model . add ( IloMaximize ( env , x [0]+2* x [1]+3* x [2]));
IloCplex cplex ( model );
cplex . solve ();
cout << " Max = " << cplex . getObjValue () << endl ;
env . end ();
}
28 / 31
Example 2
Let us see a program for solving:
29 / 31
Example 2
# include < ilcplex / ilocplex .h >
ILOSTLBEGIN
int main () {
IloEnv env ;
IloModel model ( env );
IloNumVarArray x ( env );
x . add ( IloNumVar ( env , 0 , 40));
x . add ( IloNumVar ( env ));
x . add ( IloNumVar ( env ));
x . add ( IloNumVar ( env , 2 , 3 , ILOINT ));
model . add ( - x [0] + x [1] + x [2] + 10 * x [3] <= 20);
model . add ( x [0] - 3 * x [1] + x [2] <= 30);
model . add ( x [1] - 3.5* x [3] == 0);
model . add ( IloMaximize ( env , x [0]+2* x [1]+3* x [2]+ x [3]));
IloCplex cplex ( model ); cplex . solve ();
cout << " Max = " << cplex . getObjValue () << endl ;
env . end ();
}
30 / 31
More information
You can find complete documentation in the WWW at:
You can find a template for Makefile and the examples shown here at: erodri/webpage/cps/lab/lp/tutorial-cplex-code/tutorial-cplex-code.tgz
31 / 31 | https://tr.scribd.com/document/360814046/Cplex-tutorial | CC-MAIN-2019-30 | refinedweb | 1,207 | 60.14 |
# Programming as an endless educational pursuit
When one embarks on the journey to master the craft of programming, they come to the realisation that it has no finish line. No matter how good you are, there are still things to learn, solutions to explore.
Today, we’ll talk about the importance of remaining a lifelong student, language adoption trends according to StackOverflow and why programming itself might not be what you end up learning to become better.
[](https://habr.com/en/company/spbifmo/blog/501054/)
*[hackNY.org](https://www.flickr.com/photos/hackny/10165018516/) [CC-BY](https://creativecommons.org/licenses/by-sa/2.0/)*
The habit of sticking to what’s working and ignoring new tools can backfire. By doing that, you’re depriving yourself of an opportunity to be more efficient, and risk eventual [burnout](http://blog.braegger.pw/5-ways-to-burn-out-programming/). John Graham-Cumming of Cloudflare eloquently [notes](https://blog.jgc.org/2012/07/some-things-ive-learnt-about.html): “Some people get obsessed with a specific language and have to do everything in it. This is a mistake. There is not [sic] single greatest language for all tasks.” This might seem like an obvious piece of advice, but it’s nonetheless important. And the more experience you have under your belt, the harder it is to follow. John himself jokingly states that he’s not “young enough to know everything”.
Learn something new
-------------------
We spend a lot of time at our computers, which can be a good thing and a bad thing. It’s a good thing because of all the educational resources at our disposal. It’s a bad thing because, unless we spend this time wisely, it can lead to burnout. Doing too much of the same is not only boring, but potentially dangerous.
The right thing is to challenge yourself and keep your creative juices flowing. A study of StackOverflow data [found](https://stackoverflow.blog/2017/02/07/what-programming-languages-weekends/?cb=1) that programmers tend to use different languages and libraries during their time off. Which is, generally speaking, the right thing to do. Microsoft-related tags (C#, ASP.NET, SQL Server, Excel, VBA) drive the charts during the work week. The rest of the time, people are more interested in brand new languages (such as Swift), Node.js, C and C++. As tools become popular, they move from the second category to the first category.
For example, Scala and Ruby on Rails used to be ‘weekend languages’ a few years ago. Now, that they’re widely used, they lost the status of hobby project staples. Instead, people are more likely to spend their free time exploring game development frameworks.
> To help you explore things, a Google engineer created a [list of practical projects](https://github.com/karan/Projects) you can attempt in pretty much any language you’d want. From maths problems to working with graphics, it contains a variety of tasks that can help you become fluent in the language you’re studying. The GitHub repository linked above contains example solutions in various languages — most often, Java and Python.
Don’t be afraid to go extreme
-----------------------------
Each new programming language has something to teach us. Sometimes the sheer novelty of a solution can throw you for a loop, and demand you rise above your problem solving preconceptions. Take, for example, the [BANCStar](https://en.wikipedia.org/wiki/BANCStar_programming_language) programming language. Here’s what it looks like:
```
8607,,,1
11547,15475,22002,22002
1316,1629,1,1649
3001,1316,3,30078
11528,22052,22002,22002
9301,0,1528,1528
31568,10001,800,107
8560,,,1568
8550,210,,
3001,,,
3100,1316,3,30089
11547,15475,22002,22002
3001,1316,3,30089
3001,1317,3,10000
8400,,,
8550,700,801,
3001,,,
9301,0,522,522
3000,1284,3,10001
8500,,3,
8500,,5,
1547,,1,-2301
```
A security researcher by the name of Joe Loughry [shared](https://github.com/jloughry/BANCStar/blob/master/README.md) his story of working with this monster back in the year 1990. He was introduced to BANCStar on the first day of his new banking industry job, and it took him two weeks to get comfortable using the language. Back then, there was no StackOverflow, so he made do with what he had on hand: a dot-matrix printer, a set of highlighters and a binder for all the printouts.
This might sound like torture, but back then BANCStar was a legitimate solution for the banking sector. The sheer illegibility of its syntax, which only consists of numbers, commas, newline characters, and ‘minus’ signs, made it pretty secure. Company policy prohibited its staff from commenting the code in any way, so as to not compromise this.
According to Loughry, to this day there are no more than 10 people in the entire world capable of reading the source code provided above. Which is why he copied it verbatim from one of his old applications.
Compared to BANCStar, modern languages are a breeze to learn. But using a language strictly because of its perceived superiority is just as bad as always staying in your comfort zone. Languages are just tools. There should be no shame in admitting that they don’t fit and switching to something else. Even if it makes you ‘uncool’ in the eyes of the twitterverse.
Whichever way you eat a sandwich
--------------------------------
How you approach your studying is just as important as what you’re studying. Allen Downey, a computer science professor from the Olin College of Engineering, [remembers](https://blogs.scientificamerican.com/guest-blog/programming-as-a-way-of-thinking/) how, back in the day, students used to be taught a particular way of solving things with code.
First, they were asked to express their idea using natural language — pinpoint the particulars of the application they want to create. Then they were supposed to express this same idea in mathematical notation. If the math worked out, they would create a draft of the program using pseudocode. And only then they would be allowed to actually write the code. But, while this used to make sense in the age of punched cards, it might not be a good fit today. Modern high-level languages have the expressivity of natural languages, the precision of mathematical notation, and the abstraction of 1950s pseudocode.
> Nothing is stopping you from experimenting with your approach to programming. You can completely reverse this traditional process, and start writing code first thing. You can replace entire parts of your application with third-party libraries, and ‘reverse engineer’ them as you go along. The most important thing is to find something that keeps you excited and motivated.
Breadth over depth
------------------
It usually takes three to four years for any particular programmer to reach their ‘skill ceiling’. If they cannot become a ‘superstar coder’ in this time window, chances are, no amount of programming experience will help. So, if we can’t get better at programming by simply accumulating relevant experience, what can we do?
What separates the best from the rest?
Here’s how Jeff Atwood [interprets](https://blog.codinghorror.com/how-to-become-a-better-programmer-by-not-programming/) this: Being a well-educated programmer requires much more than a continuous expansion of your toolset, or being willing to broaden your mathematical horizons from time to time. Our coding ability is dependent on a multitude of skills that aren’t directly related to the act of programming. Accomplished software engineers know that coding is not the end all be all of their jobs. They study their users, pay attention to the business side of things, get to know the ins and outs of their industry.
*Feel free to share your take on this matter in the comments. Which languages/frameworks are you studying right now, and what for? What insights from other disciplines enhanced your programming ability, and how?*
---
**Further reading:**
* [Esoteric programming languages: a systematic approach](https://habr.com/en/company/spbifmo/blog/494280/)
* [All gain, no pain — learning with the Flashcard method](https://habr.com/en/company/spbifmo/blog/498748/)
* [Everything you always wanted to know about photographic memory, amnesia and false memories](https://habr.com/ru/company/spbifmo/blog/498082/)
* [Everything you always wanted to know about human memory (but were afraid to ask)](https://habr.com/en/company/spbifmo/blog/494988/)
--- | https://habr.com/ru/post/501054/ | null | null | 1,406 | 56.15 |
0
Total new question here - and I know a similar question has been asked before - but I've done a bit of work on this and I'm stuck, so I'd appreciate some help.
The exercise I'm stuck on is this:
Write a function that implements Euclid's method for finding a common factor of two numbers. It works like this:
1. You have two numbers, a and b, where a is larger than b
2. You repeat the following until b become zero
3. a is changed to the value of b
4. b is changed to the remainder when a (before the change) is divided by b (before the change)
5. you then return the last vaule of a
This is what I've come up with:
def fac(a,b): #defining the function that uses Euclid's method while b>0: a, b = b, a%b # changing the numbers a to b, and b to remainder of a/b return a a = input("Please define a number for 'a': ") #getting numbers a and b from user b = input("Please define a number for 'b': ") a,b = max(a,b),min(a,b) #making sure a>b euclid = fac(a,b) #running the function on a and b print euclid #printing the result
But it doesn't work and just prints b. I can't see why. Please help by explaining where the problem lies.
Thanks for your time.
Jim | https://www.daniweb.com/programming/software-development/threads/313465/sorry-to-ask-this-need-a-bit-of-help | CC-MAIN-2017-51 | refinedweb | 244 | 76.66 |
Can somebody please help me? Why is this recursive fuction only working on one of the nodes? It should return a node of a binary tree, and it does, but only one side (either left node or right node). Here is the function:
Need help badly!!!!Need help badly!!!!Code:Tree *searchProduct(Tree *T, char *name) { if(T == NULL) return (NULL); if(strcmp(T->name, name) == 0) return (T); T->rightchild = searchProduct(T->rightchild, name); T->leftchild = searchProduct(T->leftchild, name); } //And here is main: int main(int argc, char *argv) { Tree *BA = NULL; Tree *AB = build123(); BA = searchProduct(AB, "antenna"); printf(" %s \n", BA->name); return (0); } | http://forums.devshed.com/programming/939406-function-last-post.html | CC-MAIN-2018-05 | refinedweb | 108 | 72.97 |
Speeded-Up Robust Features¶
New in version 0.8: In version 0.8, some of the inner functions are now in mahotas.features.surf instead of mahotas.surf
Speeded-Up Robust Features (SURF) are a recent innovation in the local features family. There are two steps to this algorithm:
- Detection of interest points.
- Description of interest points.
The function
mahotas.features.surf.surf combines the two steps:
import numpy as np from mahotas.features import surf f = ... # input image spoints = surf.surf(f) print("Nr points: {}".format(len(spoints)))
Given the results, we can perform a simple clustering using, for example, milk (nowadays, scikit-learn would be a better choice):
try: import milk # spoints includes both the detection information (such as the position # and the scale) as well as the descriptor (i.e., what the area around # the point looks like). We only want to use the descriptor for # clustering. The descriptor starts at position 5: descrs = spoints[:,5:] # We use 5 colours just because if it was much larger, then the colours # would look too similar in the output. k = 5 values, _ = milk.kmeans(descrs, k) colors = np.array([(255-52*i,25+52*i,37**i % 101) for i in xrange(k)]) except: values = np.zeros(100) colors = [(255,0,0)]
So we are assigning different colours to each of the possible
The helper
surf.show_surf draws coloured polygons around the
interest points:
f2 = surf.show_surf(f, spoints[:100], values, colors) imshow(f2) show()
Running the above on a photo of luispedro, the author of mahotas yields:
from __future__ import print_function import numpy as np import mahotas as mh from mahotas.features import surf from pylab import * from os import path f = mh.demos.load('luispedro', as_grey=True) f = f.astype(np.uint8) spoints = surf.surf(f, 4, 6, 2) print("Nr points:", len(spoints)) try: import milk descrs = spoints[:,5:] k = 5 values, _ =milk.kmeans(descrs, k) colors = np.array([(255-52*i,25+52*i,37**i % 101) for i in range(k)]) except: values = np.zeros(100) colors = np.array([(255,0,0)]) f2 = surf.show_surf(f, spoints[:100], values, colors) imshow(f2) show()
(Source code, png, hires.png, pdf)
API Documentation¶
The
mahotas.features.surf module contains separate functions for all the steps in
the SURF pipeline.
mahotas.features.surf.
dense(f, spacing, scale={np.sqrt(spacing)}, is_integral=False, include_interest_point=False)
See also
surf
- function Find interest points and then compute descriptors
descriptors
- function Compute descriptors at user provided interest points
mahotas.features.surf.
integral(f, in_place=False, dtype=<type 'numpy.float64'>)
fi = integral(f, in_place=False, dtype=np.double):
Compute integral image
mahotas.features.surf.
surf(f, nr_octaves=4, nr_scales=6, initial_step_size=1, threshold=0.1, max_points=1024, descriptor_only=False)
points = surf(f, nr_octaves=4, nr_scales=6, initial_step_size=1, threshold=0.1, max_points=1024, descriptor_only=False):
Run SURF detection and descriptor computations
Speeded-Up Robust Features (SURF) are fast local features computed at automatically determined keypoints.
References
Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool “SURF: Speeded Up Robust Features”, Computer Vision and Image Understanding (CVIU), Vol. 110, No. 3, pp. 346–359, 2008 | http://mahotas.readthedocs.io/en/latest/surf.html | CC-MAIN-2017-47 | refinedweb | 524 | 53.17 |
Upgrading PostgreSQL 9.6 before EOL
You need to plan for the end-of-life (EOL) of PostgresSQL 9.6, announced by Amazon. As an AWS environment user, you need to check the version of PostgreSQL you use for Cloudera Data Warehouse environments. If your database version is still PostgreSQL 9.6, you need to upgrade to PostgreSQL 11.12.
You can initiate an upgrade of your database instance — either immediately or during your next maintenance window — to the Cloudera-recommended version of PostgreSQL 11.12 using the AWS Management Console or the AWS Command Line Interface. Follow the procedure below to perform the upgrade.
The upgrade process shuts down the database instance, performs the upgrade, and restarts the database instance. The database instance may be restarted multiple times during the upgrade process. While major version upgrades typically complete within the standard maintenance window, the duration of the upgrade depends on the number of objects within the database. To estimate the time required, take a snapshot of your database and test the upgrade.
- Go to the .
- Check the version of PostgreSQL used in your environment, and if it is 9.6.6, go to the next step to start the upgrade process.
- In CDP, go to your environment, and in a Database Catalog for that environment, create a Virtual Warehouse or use an existing one.
- Run some basic queries in Hive or Impala to see if your PostgreSQL 9.6.6 is alive and well.
show tables; use default; show tables; create table tbl1(col1 string, col2 string); show tables; describe tbl1; create table tbl2 as (select * from tbl1); describe tbl2; insert into table tbl1 values ("Hello", "World"); select * from tbl1;
- Go to the . Select DB Engine version 10.16 to upgrade Amazon RDS to 10.16.Amazon prevents a direct upgrade to 11.x unless you are on PostgreSQL 9.6.20 or higher.
- In CDP, rerun the basic queries in your Virtual Warehouse, and if all goes well, proceed to the next step.
- Look for errors, such as those shown below, in the metastore log.Errors in the metastore might look something like this:
<14>1 2021-07-31T00:52:38.223Z metastore-0.metastore-service.warehouse-1627669911-vl6x.svc.cluster.local metastore 1 0b245ec4-8419-4968-94bc-ee122960b1aa [mdc@18060 class="txn.TxnHandler" level="INFO" thread="pool-9-thread-200"] Non-retryable error in enqueueLockWithRetry(LockRequest(component:[LockComponent(type:SHARED_READ, level: DB, dbname:default, operationType:NO_TXN, isDynamicPartitionWrite:false)], txnid:79, user:hive, hostname:hiveserver2-0.hiveserver2-service.compute-1627670377-mbqx.svc. cluster.local, agentInfo:hive_20210731005238_4aa14bf0-4e46-448d-b6c7-cdc3ca4ec863, zeroWaitReadEnabled:false)) : Batch entry 0 INSERT INTO "HIVE_LOCKS" ( "HL_LOCK_EXT_ID", "HL_LOCK_INT_ID", "HL_TXNID", "HL_DB", "HL_TABLE", "HL_PARTITION", "HL_LOCK_STATE", "HL_LOCK_TYPE", "HL_LAST_HEARTBEAT", "HL_USER", "HL_HOST", "HL_AGENT_INFO") VALUES (4561258935320160815, 1, 79, 'default', NULL, NULL, 'w', 'r', 0, 'hive', 'hiveserver2-0.hiveserver2-service.compute-1627670377-mbqx.svc.cluster.local', 'hive_20210731005238_4aa14bf0-4e46-448d-b6c7-cdc3ca4ec863') was aborted: ERROR: index "hl_txnid_index" has wrong hash version^M Hint: Please REINDEX it. Call getNextException to see other errors in the batch. (SQLState=XX002, ErrorCode=0)
- Connect to the HiveServer pod or metastore pod, and using psql, connect to the RDS instance.For example,
psql -h env-kg.us-west-2.rds.amazonaws.com --u hive --d postgresLogin using the hostname from the AWS console. The postgres database password is stored in JCEKS file which is mounted using a secret volume inside the HiveServer pod or metastore pod. Note the namespace of pod and obtain the password.
Validate the upgrade to PostgreSQL 10.16
You need to connect to the postgres 10.16 database, and validate the upgrade.
- Connect to the PostgreSQL 10.16 database using the namespace of the pod and the password you obtained in the last procedure.
- On the Postgres command line, look at all the databases.For example, type \l.
- Fix any problematic indexes. Go to a database in your metastore named something likeFor example, go to a database in your metastore named warehouse-1629221321-pf2h-metastore.
\c warehouse-1629221321-pf2h-metastore
- Run the REINDEX command.
REINDEX INDEX hl_txnid_index;
- In CDP, rerun the basic queries in your Virtual Warehouse, and if all goes well, proceed to the next step.
- Upgrade the Amazon RDS version of PostgreSQL to 11.12, and rerun the basic queries.
Upgrade to PostgreSQL 11.12
- Go to the , and upgrade the Amazon RDS version to PostgreSQL 11.12.
- Rerun the basic queries in your Virtual Warehouse to validate the upgrade. | https://docs.cloudera.com/data-warehouse/cloud/aws-environments/topics/dw-aws-upgrade-postgres.html | CC-MAIN-2022-33 | refinedweb | 737 | 59.7 |
RollbackException WAS6.0 (2 messages)
I have a simple POJO part of an EAR deployed on server instance A and an EJB part of different EAR deployed on server instance B on the same machine. both talk to same database. pojo is calling a DAO within the same EAR and doing some insert/update functions and also the EJB on server instance B. I have all my operations within a UserTransaction. UT=(UT)ctx.lookup("java:comp/UserTransaction") UT.begin() DAO.update() if(xx) DAO.insert() call to session EJB which inturn calls a singleton class to start workflow process DAO.update() endif UT.commit() when UT.commit() is called RollBackException is thrown. Environment is WAS6.0 and Oracle 9i. Any idea what is causing this error?
- Posted by: rangababu chakravarthula
- Posted on: September 17 2006 21:03 EDT
Threaded Messages (2)
- Re: RollbackException WAS6.0 by Bhagvan Kommadi on September 17 2006 22:02 EDT
- Re: RollbackException WAS6.0 by rangababu chakravarthula on September 19 2006 11:54 EDT
Re: RollbackException WAS6.0[ Go to top ]
Looks like you are attempting do a transaction whose boundary spans between two j2ee server instances. technically it is possible. details below : short answer in both server instances you might want to use distributed two phase commit protocol (XA) Bhagvan K
- Posted by: Bhagvan Kommadi
- Posted on: September 17 2006 22:02 EDT
- in response to rangababu chakravarthula
Re: RollbackException WAS6.0[ Go to top ]
Thank you. We enabled XA drivers on both servers and it worked.
- Posted by: rangababu chakravarthula
- Posted on: September 19 2006 11:54 EDT
- in response to Bhagvan Kommadi | http://www.theserverside.com/discussions/thread.tss?thread_id=42232 | CC-MAIN-2015-32 | refinedweb | 271 | 59.6 |
Opposite of the Pull Up Field refactoring is push down field. Again, this is a pretty straight forward refactoring without much description needed
1: public abstract class Task
2: {
3: protected string _resolution;
4: }
5:
6: public class BugTask : Task
7: {
8: }
9:
10: public class FeatureTask : Task
11: {
12: }
In this example, we have a string field that is only used by one derived class, and thus can be pushed down as no other classes are using it. It’s important to do this refactoring at the moment the base field is no longer used by other derived classes. The longer it sits the more prone it is for someone to simply not touch the field and leave it be.
1: public abstract class Task
2: {
3: }
4:
5: public class BugTask : Task
6: {
7: private string _resolution;
8: }
9:
10: public class FeatureTask : Task
11: {
12: }
This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post. | https://lostechies.com/seanchambers/2009/08/06/refactoring-day-6-push-down-field/ | CC-MAIN-2017-26 | refinedweb | 170 | 59.77 |
Betrand Le Roy blogged about the released the Microsoft ASP.NET Ajax Road Map
which describes some of the new proposed features of ASP.NET AJAX. One of the topics in this document centered around working with data on the client which is something I have been anticipating for quite a while. Up until now working with data on the client has been a mixed bag of solutions that never seemed to completely gel (remember the xml-script stuff) and approaching the problem with UI Templates, bi-directional data binding and new “mixed mode” controls that work with data on both the client and the server seems like an approach that finally gels.
UI Templates
Templates have been around for quite a long time in ASP.NET and moving this concept to the client makes life much easier. I can remember building up HTML fragments on the server and injecting them into a div using div.innerHTML which was always fun during data changes. A template approach (see below) simplifies this dramatically. The {{ ‘products/’ + id }} syntax which basically says put the value of the id property into this expression will take a little getting use to but is similar enough with other markup syntax like XAML that it shouldn’t be to hard to pick up. The associated JavaScript code adds a behavior to the template that associates the data, template and element to facilitate repeated data binding.
<div id=”repeater1”></div> <div id=”template1” class=”sys-template”> <h2><a href=”{{ ‘products/’ + id }}”>{{name}}</a></h2> <p>{{description}}</p> </div> <script type=”text/javascript”> Sys.Application.add_initialize(function() { $create(Sys.UI.DataView, { template: $get(“template1”), data: myData }, {}, {}, $get(“repeater1”)); } </script>
There are other examples in the roadmap that show how to do this all declaratively by including various xml namespaces. I like this approach better since its closer to the way XAML works which for someone who moves between the two often helps keep my mind thinking consistently.
Data Binding
I am excited to see a new approach to client-side data binding in this new roadmap. In the early SDRs I thought the xml-script stuff was odd and didn’t feel that the approach would be a viable one. I am glad to see this has been revisited. I hope this approach will limit the use of update panels for partial page refreshes and possibly be incorporated into the ASP.NET MVC stuff to provide a clean way to do more work on the client. The HTML fragment below demonstrates the binding syntax {Binding flight, mode=twoway} which is identical to how XAML does it. This type of binding allows for bidirectional binding which is an absolute must when working with client-side data. I am glossing over a lot here so read the roadmap for a lot more information on how all of this code works.
<body xmlns:sys=.UI.DatePicker”>
<input type=”text” sys:id=”{{ ‘airport’ + $index }}” sys:attach=”ac,wm” ac:serviceUrl=”airportList.asmx” ac:minimumPrefixLength=”{{1}}” wm:text=”Type the name of an airport” value=”{Binding airport, mode=twoWay}” /> <input type=”text” sys:id=”{{ ‘flight’ + $index }}” value=”{Binding flight, mode=twoWay}” /> <input type=”text” sys:id=”{{ ‘date’ + $index }}” sys:attach=”dp” dp:lowerBound=”{{ new Date(1970, 4, 21) }}” dp:upperBound=”{{ new Date(2050, 1, 1) }}” value=”{Binding date, mode=twoWay}” /> </div>
Client Data Sources
The roadmap also talks about support for something called “live binding” where changes to data automatically propagate to update the rendered UI.
To support this Microsoft expects to implement a Client Data Source that can:
- specify a source of data, such as an ADO.NET Data Service.
- request data from the source.
- cache data.
- save changes back to source.
- Expose methods such as insertRow.
- provide collection-change events on cached data.
- Client-Side and Server-Side Data as One
if they can pull this off the client development will be totally awesome!
Client Data and Server Data
I am also glad to see that the client data approach is combined with a server data approach. Many times a pure client-side approach requires a developer to go get data from the server after the page has been rendered. This has always seemed like a inefficient approach. In the early days of ASP.NET AJAX having a combined client/server data solution was one thing I had mentioned in the SDRs. It seems the ClientDataSource, ClientDataSourceExtender and the ClientDataView server controls will solve this problem for us providing the ability to work with data from both locations using a clean approach.
Summary
I am really excited about what is coming out of the ASP.NET Team in this area and looking forward to working with the bits. With Silverlight all the rage I am glad to see that we still haven’t forgotten that for real “reach” scenarios HTML and JavaScript are still going to be needed. | http://blogs.interknowlogy.com/2008/08/12/asp-net-ajax-roadmap-and-client-side-binding/ | CC-MAIN-2015-40 | refinedweb | 816 | 61.06 |
Package: matlab.net.http.io
Superclasses:
handle,
matlab.mixin.Heterogeneous
ContentProvider for HTTP message payloads
A ContentProvider supplies data for an HTTP
RequestMessage while the message is being sent. A simple provider converts
data from a MATLAB® type to a byte stream. More complex providers can stream data to the server,
obtaining or generating the data at the same time it is being sent, which avoids the need to
have all the data in memory before the start of the message.
Normally, when sending data to a web service (typically in a PUT or POST request), you
would create a
RequestMessage and insert data in the form of a
MessageBody object in the
RequestMessage.Body property.
When you send that message using
RequestMessage.send, MATLAB converts that data into a byte stream to be sent to the server, converting it
based on the Content-Type of the message and the type of data in
Body.Data. See
MessageBody.Data for these
conversion rules.
Instead of inserting a
MessageBody object into the
RequestMessage.Body property, you can create a
ContentProvider object and insert that instead. Then, when you send the
message, MATLAB calls methods in the
ContentProvider to obtain buffers of data to
send, while the message is being sent.
Whether you insert a
MessageBody or a
ContentProvider into
the message, the call to
RequestMessage.send does not return (that is, it is
blocked) until the entire message has been sent and a response has been received, or an error
has occurred. But with a
ContentProvider, MATLAB makes periodic callbacks into the provider to obtain buffers of data to send,
during the time send is blocked. In these callbacks, your
ContentProvider can
obtain data from any source such as a file, a MATLAB array, a hardware sensor, a MATLAB function, etc. The provider's job is to convert that data to a byte stream, in
the form of uint8 buffers, that can be sent to the web.
ContentProvider is an abstract class designed for class authors to subclass
with their own data generator or converter, or you can use (or subclass) one of the
MATLAB providers that generate the data for you from various sources, without writing a
subclass. These providers have options that give you more flexible control over how data is
obtained and converted, compared to the automatic conversions that occur when you insert data
directly into a
MessageBody. Use one of the
ContentProvider
subclasses:
Even if you do not need to stream data, using one of these providers can simplify the
process of sending certain types of content, as they convert data from an internal form into a
uint8 stream. For example,
FormProvider lets you send form
responses to a server, where you can conveniently express the data as an array of
QueryParameter objects.
MultipartFormProvider lets you send
multipart form responses, simplifying the creation of responses to multipart forms. To use any
ContentProvider, you need to understand the type of content that the server
expects you to send.
The
matlab.net.http.io.ContentProvider class is a
handle class.
The simplest possible
ContentProvider need only implement a
getData method to provide buffers of data as MATLAB requests them. To use your provider, insert it into in the
Body property of the
RequestMessage. In this example,
the third argument to the
RequestMessage constructor, a
MyProvider object, goes into the
Body:
provider = MyProvider; req = matlab.net.http.RequestMessage('put', headers, provider); resp = req.send(uri);
Here is an example a
MyProvider class that reads from a file name
passed in as an argument to the constructor and sends it to the web. For good measure, we
close the file at the end or when this provider is deleted.
classdef MyProvider < matlab.net.http.io.ContentProvider properties FileID double end methods function obj = MyProvider(name) obj.FileID = fopen(name); end function [data, stop] = getData(obj, length) [data, len] = fread(obj.FileID, length, '*uint8'); stop = len < length; if (stop) fclose(obj.FileID); obj.FileID = []; end end function delete(obj) if ~isempty(obj.FileID) fclose(obj.FileID); obj.FileID = []; end end end end
MATLAB calls a provider's
complete method when it is forming a new
message to send. The purpose is to allow the provider to prepare for a new message and add
any required header fields to the message. MATLAB calls a provider's
start method when it is time to send the
data, but before the first call to
getData..
A provider can be restartable and/or reusable. Restartable means that the provider is
able to resend the same message multiple times, with the same data stream each time
MATLAB calls
start, even if the previous use did not end in a normal
completion. This behavior is needed because the server can redirect a message to a different
server, which means the data needs to be retransmitted. In that case MATLAB calls
start without calling
complete again.
MATLAB calls the
restartable method to determine whether a provider
can be restarted. If false, MATLAB throws an exception if it needs to call
start on a provider
that has already been started, if there was no intervening call to
complete
(which happens only on a new message).
Reusable means that the provider can be reused for a different (or the same) message,
each time MATLAB calls its
complete method. MATLAB calls the
reusable method to determine whether a provider can
be reused. If
false, then MATLAB throws an exception if it needs to call
complete on a
provider that has already been started. If a provider is reusable, then the assumption is
that the next call to
start should succeed, even if the provider is
restartable.
ContentProvider returns
false for both
restartable and
reusable, so if you are extending this
base class directly with a restartable or reusable provider, you should override one or both
of these methods to return
true. All concrete subclasses of
ContentProvider in the
matlab.net.http.io package are
both restartable and reusable, so they return true for these methods. If you are extending
one of those subclasses with a provider that is not reusable or restartable, override one or
both of those methods to return false.
The
MyProvider class in this example is not restartable or reusable,
because the provider closes the file at the end of the message. To make it reusable, the
fopen call should take place in the
complete method
instead of the constructor, thereby restoring the provider's state back to what it was
before it was used for a message.
classdef MyProvider < matlab.net.http.io.ContentProvider properties FileID double Name string end methods function obj = MyProvider(name) obj.Name = name; end function [data, stop] = getData(obj, length) ...as above... end function complete(obj, uri) obj.FileID = fopen(name); obj.complete@matlab.net.http.io.ContentProvider(); end function tf = reusable(~) tf = true; end function delete(obj) ...as above... end end end
To make the provider restartable, add
restartable and
start methods and issue an
fseek in the
start method to "rewind" the file:
function start(obj) obj.start@matlab.net.http.io.ContentProvider(); fseek(obj.FileID, 0, -1); end function tf = restartable(~) tf = true; end
When you call
complete or
send on a
RequestMessage that contains a
ContentProvider in its body,
MATLAB sets the
Request property in the provider to the
RequestMessage in which the provider was placed and the
Header property to the headers in the
Request,
before adding automatic fields. It then calls the following methods in the provider, in this
order:
complete - called on message completion, which usually happens once
per message, when you call
RequestMessage.send or
RequestMessage.complete. The provider is expected to set its
Header property to any header fields to be added to the message
specific to the provider. If MATLAB calls this method a subsequent time, the provider should assume it is
being used for a new message. Most providers need to implement this method to add their
headers and then, if they are not a direct subclass of this abstract class, they should
call their superclass complete to invoke any additional default behavior. MATLAB does not call
complete more than once in a provider,
unless its reusable method returns true. This abstract class is not reusable by default,
but all concrete providers in the
matlab.net.http.io package are
reusable.
preferredBufferSize/
expectedContentLength - called
from
RequestMessage.send, sometime after
complete,
before a call to
start. Most providers need not implement these
methods, as the default behavior is appropriate. However, providers can override this to
support the
force argument.
After return from these methods, MATLAB sends the header of the
RequestMessage to the server. When it
is time to send the body, MATLAB calls these methods.
start - called from
RequestMessage.send, sometime
after calling the previous methods, when MATLAB has determined that the server is ready to receive the body of the request
message. If MATLAB calls this a subsequent time, without an intervening complete, the
provider should assume it is being asked to resend the body of the same message (with
the same headers) once again. MATLAB does not call start more than once since the last call to
complete, unless the provider's
restartable method
returns
true. This abstract class is not restartable by default, but
all concrete providers in the
matlab.net.http.io package, are
restartable.
getData - called multiple times after the call to
start, while
RequestMessage.send is blocked, each
time MATLAB determines that the server is ready for a new buffer of data. The method
must return a
uint8 vector of data. The provider signals the end of
the data by returning a
stop indicator. All providers must implement
this method.
After
getData returns a
stop indicator, MATLAB ends the request message and awaits a response from the server.
A
ContentProvider that is inserted into a
RequestMessage.Body can delegate to one or more other providers to
provide all or some of the data for the message. For example, a
MultipartProvider creates a message with multiple parts, each of which are
provided by various other providers specified to the
MultipartProvider
constructor. In this case,
MultipartProvider is the delegator, and the other
providers are the delegates, each one being called in turn to provide its own header fields
and its portion of the data.
A provider delegates to another by calling
delegateTo, which sets
CurrentDelegate to the delegate and the delegate's
MyDelegator to the current provider (that is, the delegator), and
then calls the delegate's
complete and
start methods and
returns a
GetDataFcn function handle. Then the delegator's
getData method calls the delegate's
GetDataFcn to
obtain the data, possibly altering it before returning it to MATLAB. Providers generally do not have to check whether they are delegates, or who
delegated to them.
ContentConsumer |
FileProvider |
FormProvider |
ImageProvider |
JSONProvider |
MessageBody |
MultipartFormProvider |
MultipartProvider |
QueryParameter |
RequestMessage |
StringProvider | https://de.mathworks.com/help/matlab/ref/matlab.net.http.io.contentprovider-class.html | CC-MAIN-2020-05 | refinedweb | 1,809 | 61.56 |
TestBells 70-642 TS: Windows Server 2008 Network Infrastructure Configuring
• QUESTION NO: 313 • • Your network contains a server named DC1 that has the DHCP Server server role installed. • You discover the following warning message in the Event log on DC1: “There were orphaned • Entries deleted in the configuration due to the deletion of a class and option definition. Please • Recheck the server configuration.” • • You need to resolve the warning message. • What should you do? •
• • • • • • • • • • • • •
• QUESTION NO: 314 • • Your network contains an Active Directory domain. The domain contains four client computers. • The client computers are configured as shown in the following table. • Your company plans to implement DirectAccess. • You need to identify which client computers can use DirectAccess. • Which client computers should you identify? (Each correct answer presents part of the solution. Choose two.) • • A. Computer2 • B. Computer3 • C. Computer4 • D. Computer1 • • Answer: B,C
• QUESTION NO: 315 • • Your network contains a server that has the Network Policy Server (NPS) role service installed. • You need to configure a network policy that will apply to wireless clients only. • Which condition should you configure? • • A. NAS port Type • B. Service Type • C. MS-Service Class • D. Framed Protocol • E. NAS Identifier • • Answer: A
• QUESTION NO: 316 • • Your printing infrastructure is configured as shown in the following table. • You need to ensure that print jobs submitted by the members of Group1 print before queued print jobs submitted by the members of Group2. • What should you do? • • A. Modify the permissions assigned to Group2_Print. • B. Change the priority of Group2_Print to 10. • C. Change the priority of Group1_Print to 10. • D. Configure Group1_Print to begin printing immediately. • E. Configure Group2_Print to begin printing after the last page is spooled. • • Answer: B
• QUESTION NO: 317 HOTSPOT • • Your network contains a server named Server1 that runs Windows Server 2008 R2. • On Server1, you share a folder named Share1. Users report that when they try to open some of the folders in Share1, they receive an "Access is Denied" error message. • You need to ensure that when the users connect to Share1, they only see the files and the folders to which they are assigned permissions. Which administrative tool should you use to achieve this task? To answer, select the appropriate tool m the answer area. • • Answer: • • Explanation: • • Select “Share and Storage Management”. •
• • •
QUESTION NO: 318
•
There are shared printers in each building. Active Directory sites and Active Directory subnets
•
exist for each office. Each user has a laptop that runs Windows 7. The users frequently travel between the office buildings.
• • •
Your company has five office buildings in the same city. Each building has its own IP subnet.
You plan to publish all of the shared printers in Active Directory and to specify the Location attribute of each shared printer. You need to ensure that the users can browse for shared printers based on the location of the printer.
•
The solution must ensure that when the users attempt to add printers by using the Add Printer wizard, the users' current location is used automatically.
•
Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)
•
• A. From the properties of each subnet object, set a value for the Location attribute. • B. From a Group Policy object (GPO), enable the Allow pruning of published printers setting. • C. From the properties of each print server computer account, set a value for the Location attribute. • D. From a Group Policy object (GPO), enable the Pre-populate printer search location text sitting. • E. From the properties of each Windows 7 computer account, set a value for the Location attribute. • • Answer: A,D
• • • • •
QUESTION NO: 320 Your network contains an Active Directory domain named contoso.com. In the contoso.com domain you deploy a client computer named test. IT.lab.contoso.com that runs Windows 7
• You need to prevent the client computer from performing DNS suffix devolution. What should you do? • • A. Run netsh.exe and specify the namespace context. • B. Run dnslint.exe and specify the /ad parameter. • C. Modify the local Group Policy. • D. Run dnscmd.exe and specify the /config parameter. • • Answer: C
• • •
QUESTION NO: 321
•
The network contains a server named serverl.contoso.com.From a computer named Computer1 that runs Windows 7, you successfully resolve serverl.contoso.com to an IP address.You change the IP address of serverl.contoso.com.
•
From Computer1, you discover that server1.contoso.com still resolves to the old IP address. You successfully connect to server1.contoso.com by using the new IP address.
•
You need to ensure that you can immediately resolve serverl.contoso.com to the new IP address. What should you do on Computer1?
• • • • • • •
Your network contains a DNS zone for contoso.com.All servers register their host names in DNS by using dynamic updates.
A. Run ipconfig.exe and specify the /flushdns parameter. B. Run netsh.exe and specify the dnsclient context. C. Restart the Peer Name Resolution Protocol (PNRP) service. D. Run dnscacheugc.exe. Answer: A
• • • •
• • • • • • • • • •
QUESTION NO: 322? A. Netcfg B. Active Directory Users and Computers C. User account control settings D. Authorization manager Answer: B
• For Complete real exam in just $39 go on • | https://issuu.com/testbells.com/docs/testbells_70-642_pdf | CC-MAIN-2017-09 | refinedweb | 864 | 60.82 |
Provided by: manpages-dev_5.10-1ubuntu1_all
NAME
stime - set time
SYNOPSIS
#include <time.h> int stime(const time_t *t); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): stime(): Since glibc 2.19: _DEFAULT_SOURCE Glibc 2.19 and earlier: _SVID_SOURCE
DESCRIPTION
NOTE:.
NOTES
Starting with glibc 2.31, this function is no longer available to newly linked applications and is no longer declared in <time.h>.
SEE ALSO
date(1), settimeofday(2), capabilities(7)
COLOPHON
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.ubuntu.com/manpages/impish/en/man2/stime.2.html | CC-MAIN-2022-33 | refinedweb | 109 | 61.93 |
Hello, Is there better documentation for ghc-pkg than just "help"?? Vasili On Thu, Apr 10, 2008 at 9:36 PM, Galchin, Vasili <vigalchin at gmail.com> wrote: > Hi Philip, > > Before I got your email, I deregistered unix-2.3.0.0 which made my > unix-2.2.0.0 namespace changes visible. However, deregistering seems to made > other things worse, e.g. runhaskell Setup.hs configure gives an error > message "unknown parameter package: unix-2.3.0.0". Sigh .. how do I get back > to where i was in order to do a "hide"? > > Kind regards, Vasili > > > On Thu, Apr 10, 2008 at 8:22 PM, Philip Weaver <philip.weaver at gmail.com> > wrote: > > > 2008/4/10 Galchin, Vasili <vigalchin at gmail.com>: > > > Hello, > > > > > > I doing work using Linux. The wrong version (for me) of the > > unix > > > package seems to be visible. I see possibilities to use ghc-pkg to > > suppress > > > the unix package that I don't want(2.3.0.0) but that seems dangerious. > > > Details are below . What should I do? > > > > If you don't want to use it, then it's safe to hide it: > > > > ghc-pkg hide unix-2.3.0.0 > > > > You can always unhide it later. > > > > You can also tell ghc to use a specific version of a package: > > > > ghc -package unix-2.2.0.0 > > > > Of course, you'll need to make sure unix-2.2.0.0 is registered with > > ghc-pkg. > > > > > > > > Regards, vasili > > > > > > > > > > > > When I do: > > > > > > > ghci > > > :m System.Posix > > > > > > I am getting the wrong version of the Unix package. I know this to be > > true > > > because I did > > > ghc-pkg latest unix > > > > > > and got unix-2.3.0.0 > > > > > >. > > > > > > _______________________________________________ > > > Haskell-Cafe mailing list > > > Haskell-Cafe at haskell.org > > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: | http://www.haskell.org/pipermail/haskell-cafe/2008-April/041608.html | CC-MAIN-2014-23 | refinedweb | 299 | 79.26 |
How can my program have 2 languages?
Hi! In my program i have an option at the preferences and you can change the language to English->Greek or Greek->English. I have a bool that when the language is Greek it is true and when it is English it is false. So what i am doing is at every message box or dialog i first check if the bool is greek or english and if it is true ( greek ) i translate the dialog to greek or if it is a messagebox the text is at greek.. So i am sure that this isn't the correct way to do that.. Can you tell me what is the correct way to provide my program with more than the the english language?
I am using Ubuntu.
There's a good overview at
Qt have good integrated system for it.
See "QTranslator":
- valandil211 last edited by")@
Also, you might want to re-think your design for switching. What if your application becomes a best-seller, and you'd like to expand to Turkey? Or to Italy? Even if in the UI you keep the choice simple, I'd make sure it is easy to add other languages as well in the rest of your application.
[quote author="Joey Dumont" date="1309262146"")@ [/quote]
That's what am i using..
[quote author="Vass" date="1309261862"]Qt have good integrated system for it.
See "QTranslator":[/quote]
Could i have some tips at this? I don't know nothing about QTranslator.. Any example with a simple layer saying "Hello", i don't know something more than just a Class Reference :/
EDIT: I am now reading Qt Linguist Manual. I hope it will help me..
The following "FAQ": contains an example that can be useful.
I just created my first translation file.. I will try to do it my own.. I will check the FAQ later.. Thanks :)
- valandil211 last edited by
If you consider your problem as solved, could you please the thread title and add [SOLVED].
Thanks!
You should read documentations carefully and you will have no problem.
In case that you couldn't managed to do the stuff, do these:
1- In your qt project file (.pro) add this line:
@TRANSLATIONS += program_gr.ts@
Of course names and number of translations are optional.
2- start lupdate tool (which is an executable installed with Qt SDK) given your project file name. for example:
@
lupdate ./program.pro
@
this scans your source code tree and determines translatable strings, then generates a XML-based translation file. in above example generates program_gr.ts.
3- Now you can perform actual translation! open your translation file with Qt Linguist and translate strings. then save the file and exit. It's easy !
4- Now that you have translated strings, you should make binary translation file. just call lrealease and give your ts file name:
@
lrealease program_gr.ts
@
this will generate profram_gr.qm that you can load in your program.
5- when application starts, load your qm file using QTranslator class. in a widget-based application it may look like this:
@
#include <QtGui/QApplication>
#include <QTranslator>
#include "mainwindow.h"
int main(int argc, char argv[])
{
QApplication a(argc, argv);
QTranslator translator;
translator->load(a.applicationDirPath()+"/program_gr.qm"); // or other place that you put your .qm file
a.installTranslator(translator);
MainWindow w;
w.show();
return a.exec();
}
@
note that you can load translations dynamically and use them whenever you need. but you should be careful about calling translation method for all of dialogs.
Basically i saw a tutorial here ( ). It is the same with yours except that i can't understant what the guy is saying at Indonesia language..
Also at step 5 i have this
@QTranslator translator;
translator.load("program_gr");
a.installTranslator(&translator);@
Ok so i create the gm file. BUT. As i said my program is for Ubuntu so i will make a deb file ( like setup.exe files at Windows.. ).. How can i provide the greek translation file and how after the program is installed users can translate the app to greek? ( Install my greek translation file so they can see the app translated at greek )
Ok, it looks like an "Installation and Deployment" problem...
In linux directories used for configuration files are:
/etc/program and /home/user_name/.program and /usr/share/program/
Due to linux file system standards I suggest put your translation files in /usr/share/program/translations.
Ok thanks for the info! I will try it.. When everything is ok i will edit my post to [SOLVED] :D
The translations at /usr/share/program/translations must be at .ts format or .qm format?
[quote author="Leon" date="1309285305"]The translations at /usr/share/program/translations must be at .ts format or .qm format?[/quote]
.qm
.ts format for developers (translation source)
.qm format for end users (translation binary)
[quote author="Leon" date="1309285305"]The translations at /usr/share/program/translations must be at .ts format or .qm format?[/quote]
You need only qm files in runtime. ts files are used to translate. at runtime you want to load translated data.
Also notice that there is no magic with /usr/share/program/translations. that was just a suggestion. you could put your translations in every other location...
Ok thanks guys.. I am working on it..
soroush i know it is a suggestion :P
- mlong Moderators last edited by
The .qm files can also be included as resources, too.
I am thinking of having english greek dutch and french language at my program.. Should i have a combobox with this 4 languages only ( using the resource file) or should i check for file existences at the path that i have my translations and then add them to the combobox?
Second way sounds better - this allow your users adding new languages for your app without re-compilation.
of course if your public .ts file.
Yes but who would do that? I think i will go with the first one and if anyone translate my app i will add the language at another version.. :)
Hello again! What do you suggest? After the language has been changed ( at a combobox probably ) instantly everything change to the language you selected with "this way": or change the language after you restart the application?
What I did was this:
1- Create a proxy subclass of QDialog named ProxyDialog wich have only one method: retranslateUI()
2- Subclass all dialogs from ProxyDialog
3- When you need to translate UI, just iterate over children of type ProxyDialog* and call retranslate UI for all of them. this is possible using findChildren function.
So you suggest that i should translate everything instantly?
Yes. I'm not sure if there is a better way or not, but I looked around a lot and couldn't fount anything.
This works well for my applications.
You don't have to restart your application to see translation results. All open dialogs will be translated on-the-fly.
Ok then, thanks again! | https://forum.qt.io/topic/7075/how-can-my-program-have-2-languages/3 | CC-MAIN-2019-43 | refinedweb | 1,163 | 67.96 |
public class Counter { static int count=0; void func1() { count++; System.out.println(count); } public static void main(String[] args) { Counter c=new Counter(); c.func1(); } }
964980 wrote:You read somewhere (don't know where) that non-static member variable can only be used by a non-static method. A static member variable belongs to the class, i.e. all objects of the class.
I read somewhere(don't know where) that static variable can only be used by a static method. But in the sample code below even a non-static function is able to use the static variable.
I read somewhere(don't know where) that static variable can only be used by a static method.No you didn't. You misunderstood, or you made it up, or you got it back to front. You've proven that this imaginary statement is incorrect. Not a real question. | https://community.oracle.com/message/11020682 | CC-MAIN-2017-43 | refinedweb | 149 | 77.43 |
I am running this code:
public class testttt {
public static void main(String[] args){
ArrayList<StringBuffer> listOne = new ArrayList <StringBuffer>();
listOne.add(new StringBuffer("One"));
listOne.add(new StringBuffer("Two"));
listOne.add(new StringBuffer("Three"));
ArrayList <StringBuffer> listTwo = new ArrayList <StringBuffer>(listOne);
listOne.add(new StringBuffer("Four"));
for (StringBuffer str : listTwo) {
str.append("2");
}
System.out.println("List One: " + listOne);
System.out.println("List Two: " + listTwo);
}
}
List One: [One2, Two2, Three2, Four]
List Two: [One2, Two2, Three2]
By using the
listOne for the
listTwo construction, you are saying: "please copy those elements from the first list into the second list".
And then of course, java is doing "call-by-value". This means: "copying" doesn't mean the creation of new StringBuffers. It means that both lists hold references to the same StringBuffer objects.
Thus when you iterate the second list, and modify members of the second list, you see the effects on the first list as well.
So, the "real" answer is: always understand the concepts you are using; the "real" message here isn't the explanation; but the fact that one core part of being a programmer is to be very precise about the code you write, and to really understand each and every tiny bit of statement your put in your code. Everything has a certain meaning; and if you don't know them, your code will keep "surprising" you. | https://codedump.io/share/XeDsl2qWwhV7/1/aliasing-with-stringbuffer | CC-MAIN-2016-50 | refinedweb | 232 | 64 |
This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.
*On Wed Apr 30, 2003 at 11:32:38AM -0400, Stephen Frost (sfrost@snowman.net) wrote: > * Carl B. Constantine (cconstan@csc.UVic.CA) wrote: > > I found that if I eliminated the $CFLAGS and $CPPFLAGS environemnt > > variables, it compiles on Sparc. But the funny thing is, I can use those > > variables successfully on Solaris 8 for Intel without problems. > > I'm currently making an attempt to compile gcc as 64bit on Solaris 9. > Should be fun to see what happens... I get the impression it's not > going to pan out in the end. :) > > Stephen I tried that as well. It seems you can't compile gcc itself as a 64bit app. It includes a file called libelf.h which has this pragma in it: #if defined(_ILP32) && (_FILE_OFFSET_BITS != 32) #error "large files are not supported by libelf" #endif At least you can't use -D_FILE_OFFSET_BITS = 64 in your CPPFLAGS. This is really odd because I'm sure I was able to use that on Solaris x86. *shrug* -- Carl B. Constantine University of Victoria Programmer Analyst UNIX System Administrator Victoria, BC, Canada cconstan@csc.uvic.ca ELW A220, 721-8753 | http://gcc.gnu.org/ml/gcc-help/2003-04/msg00274.html | crawl-003 | refinedweb | 207 | 77.94 |
Quickstart: Files, Media and Binary Data
Make your app handle files
Anvil has built-in support for uploading, storing, downloading, and manipulating files and other binary data.
Follow this quickstart to load files into your app, access their contents and properties, and display an image file on the page.
Create an app
Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.
Add a FileLoader component
You will see your app in the centre of the screen. On the right is the Toolbox, which contains components to drag-and-drop.
Drop a FileLoader
into the page.
Print the properties of your files
Now scroll to the bottom of the Properties Panel. There is a list of events for this FileLoader. Click the blue arrows next to ‘change’.
You will be taken to the Code View. The
file_loader_1_change method
runs when a file is loaded into the FileLoader:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" pass
There is a Python object named
file that represents whatever
file the user loads in. It is an Anvil
Media object.
Add some print statements to output the properties and contents of the file:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" print(f"The file's name is: {file.name}") print(f"The number of bytes in the file is: {file.length}") print(f"The file's content type is: {file.content_type}") print(f"The file's contents are: '{file.get_bytes()}'")
Run your app
Now click the ‘Run’ button at the top of the screen.
You’ll see your app running. Click the ‘upload’ button - you will get a file selection dialog.
Upload a short text file. Here’s what happens if you upload a file containing the text
Anvil represents files as Media objects:
Display an image file
Stop the app and go back to the Design View of the Form Editor.
Drag-and-drop an Image
component onto the page and change its
display_mode to
original_size in the Properties Panel:
Go back to the code view and modify the
file_loader_1_change event handler to this:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" self.image_1.source = file
Run your app again and upload an image file. Your image will be displayed in the app:
Copy the example app
Click on the button below to clone a finished version of this app into your account.
Next up
Want more depth on this subject?
Read more about Files, Media and Binary Data to see what else you can do with Media Objects.
Media objects are a powerful way to handle binary data: Anvil supports storing, downloading, emailing, displaying as images, streaming into Server Modules, saving as temporary files in Server Modules, and more.
Want another quickstart?
Every quickstart is on the Quickstarts page. | https://anvil.works/docs/media/quickstart.html | CC-MAIN-2020-29 | refinedweb | 493 | 72.66 |
This document covers how to set up and run profiling tools by capturing a profile and using it to identify and analyze program performance on Cloud TPU in TensorFlow's TensorBoard console. The document also describes how to continuously monitor your TPU job on the command line (see Monitoring your job).
Prerequisites
Before you can use the Cloud TPU profiling tools described in this guide, you must complete the following:
- Creating Cloud TPU resources
- Installing cloud_tpu_profiler
- Capturing a profile (static) or Monitoring a profile (streaming).
Using Cloud TPU tools in TensorBoard
TensorBoard is a suite of tools designed to present TensorFlow data visually. We have provided a set of Cloud TPU profiling tools that you can access from TensorBoard after you install the Cloud TPU profiler plugin. The plugin supports performance visualization for an Cloud TPU nodes of all sizes.
The Cloud TPU tool selector becomes available under the Profile tab on the TensorBoard menu bar only after you have collected trace information from a running TensorFlow model.
The following sections contains instructions on how to set up your compute environment, run your model and capture a Cloud TPU profile, and run TensorBoard from a VM command line so you can use the tools. For details on how to invoke TensorBoard from your code, see the TensorBoard programming guides.
Creating Cloud TPU resources
The quick start instructions for Cloud TPU describe how to create a Compute Engine VM and Cloud TPU resources.
If you plan to continue with the procedures in this guide immediately after you create your resources, do not perform the clean up section of those instructions. When you have finished running your model and are done using your resources, follow the clean up instructions step to avoid incurring unwanted charges.
Running cloud_tpu_profiler
You run
cloud-tpu-profiler 1.15.0rc1 to provide a
Cloud TPU profiling plugin in TensorBoard and a script,
capture-tpu-profile. You can run the script to either capture a profile that
can be viewed in TensorBoard or to monitor your TPU jobs on the command line
(see Monitoring your job).
In TensorBoard, the Profile tab appears after you run a model and then run capture profile (trace) information while the model is running.
To check your profiler version, use
pip. If you do not have the latest
version, use the second command to install it:
(vm)$ pip freeze | grep cloud-tpu-profiler (vm)$ pip install --upgrade "cloud-tpu-profiler>=1.15.0rc1"
You also must set the
PATH environment variable as follows:
(vm)$ export PATH="$PATH:`python -m site --user-base`/bin"
About capture_tpu_profile
When you use
capture_tpu_profile to capture a profile, a .tracetable file
is saved to your Google Cloud Storage bucket. The file contains a large number
of trace events that can be viewed in both trace viewer and
streaming trace viewer in TensorBoard.
You capture a profile, or trace data, by running your model, executing
capture_tpu_profile, and then starting up TensorBoard before the model
stops running. For example:
(vm)$ capture_tpu_profile --tpu=$TPU_NAME --logdir=${MODEL_DIR}
The parameters are set up when you run the model and have the following meanings:
--tpu=$TPU_NAME- This is the name assigned when you created your Cloud TPU. If you used
ctpu upto start your Compute Engine VM and Cloud TPU it defaults to your username. If you used
gcloudor the Cloud Console to set up your VM and TPU, it is the name you specified when you created them.
--logdir=${MODEL_DIR}- This is a Cloud Storage location where your model and checkpoints are stored. The model directory is usually defined as
export STORAGE_BUCKET=gs://[YOUR-BUCKET-NAME] export MODEL_DIR=${STORAGE_BUCKET}/OUTPUT DIRECTORYFor example, if you are running the MNIST model, the output directory might be defined as:
export STORAGE_BUCKET=gs://[YOUR-BUCKET-NAME] export MODEL_DIR=${STORAGE_BUCKET}/mnist
As the model runs, the Cloud TPU service account creates a directory (object) and writes data to your Compute Engine bucket. You must set permissions for that account on the bucket before you run your model.
By default,
capture_tpu_profile captures a 2-second trace. You can set the
trace duration with the
duration_ms command-line option or in your program
when you run your model.
Capturing a profile
The steps in this section describe how to capture a profile by running your
model, executing
capture_tpu_profile, and then starting up TensorBoard before
the model stops running. Running TensorBoard as described here provides access
to all of the Profile tools except for streaming trace viewer.
If you prefer to monitor your TPU jobs on the command line, see Monitoring your job.
The MNIST tutorial is used as the model in this example.
Run ctpu up.
Go to the Cloud Console Dashboard (Home) then select Compute Engine > TPUs.
Click on the Cloud TPU you created.
Locate the Cloud TPU service account name and copy it, for example:
service-11111111118@cloud-tpu.iam.myserviceaccount.com
In the Resources panel on the Dashboard click on Cloud Storage. The storage bucket list appears or you are prompted to create a bucket. If you haven't yet created a storage bucket, click CREATE BUCKET at the top of the page and create one in the same region as your TPU.
Click the checkbox of the storage bucket you want to use. Be sure the bucket is in the same region in which you created your Cloud TPU.
With your storage bucket selected in the list, select Show Info Panel, and then select Edit bucket permissions.
Paste your TPU service account name into the add members field for that bucket
Select Storage Legacy and then select the Storage Legacy Bucket Reader, Writer, and Owner permissions:
In your VM shell, use
pipto check your TensorBoard version.
(vm)$ pip freeze | grep tensorboard
If your TensorBoard version is lower than 2.1, upgrade to the latest version.
(vm)$ pip install --upgrade -U "tensorboard>=2.1"
(vm)$ pip freeze | grep tensorflow (vm)$ pip install --upgrade -U "tensorflow>=2.1"
If you have not already done so, set the
PATHenvironment variable:
(vm)$ export PATH="$PATH:`python -m site --user-base`/bin"
Follow the MNIST tutorial to set up and execute an MNIST training job, for example:
(vm)$ python /usr/share/models/official/mnist/mnist_tpu.py \ --tpu=$TPU_NAME \ --data_dir=${STORAGE_BUCKET}/data \ --model_dir=${MODEL_DIR} \ --use_tpu=True \ --iterations=500 \ --train_steps=5000
While the job is running, open a new Cloud Shell and run
ctpu up, specifying your non-default TPU name if you used one. After you log in to your VM, set up the following environmental variables as shown in previous steps: STORAGE_BUCKET, MODEL_DIR.
While the job is running, open a 3rd Cloud Shell and ssh to your VM (replace $vm in the command with your VM name).
gcloud compute ssh $vm --ssh-flag=-L6006:localhost:6006
After you log in, set up the following environmental variables as shown in previous steps:TPU_NAME, STORAGE_BUCKET, MODEL_DIR.
In the 2nd Cloud Shell, run
capture_tpu_profileto capture a .tracetable file.
(vm)$ capture_tpu_profile --tpu=$TPU_NAME --logdir=${MODEL_DIR}
In the 3rd Cloud Shell, run TensorBoard and point it to the model directory:
(vm)$ tensorboard --logdir=${MODEL_DIR} &
Click the Web preview button in the 2nd Cloud Shell and open port 8080 to view the TensorBoard output.
Graphs
TensorBoard provides a number of visualizations, or graphs, of your model and its performance. Use the graphs together with the profiling tools to fine tune your models and improve their performance on Cloud TPU.
XLA structure graph
During model compilation, before the model is run, TensorFlow generates
an (XLA)
graph that will be run on the Cloud TPU. The data for the graph
is stored in the
MODEL_DIR directory. You can view this graph without running
capture_tpu_profile.
To view a model's XLA structure graph, select the Graphs tab in TensorBoard. The default selection for Color is Structure.
A single node in the structure graph represents an XLA instruction. For example, for a TensorFlow add op named x/y/z that is mapped (or lowered) to XLA shows as x/y/z/add in the graph.
An XLA graph displays information on how a Cloud TPU will execute a particular model. The graph also provides the shapes of inputs and outputs for various operations. Once you capture a profile of your model, you can use the XLA graph along with trace viewer or streaming trace viewer to gain insight into where most of the time is being spent.
Notes:
- Some nodes do not have TensorFlow namespaces because not all XLA instructions (such as those injected by the XLA compiler) have corresponding TensorFlow operations.
- The TensorFlow program structure is incorporated in the XLA graph where possible. However, because the XLA program running on Cloud TPU is highly optimized, its graph structure might be quite different from that of the original TensorFlow program.
- A special XLA instruction called fusion can merge multiple instructions from different TensorFlow operations into a single computation. The TensorFlow operation corresponding to the root instruction in the fusion is used as the namespace of the fusion.
Prerequisites
- Configure your model to write the model graph data to a file by setting the
model_dirproperty of the tf.estimator API or the TPUEstimator.
- Remove any manual assignments in your code to GPUs or CPUs for operations that you intend to run on the Cloud TPU. When used with the TPU Compatibility option, the compatibility checker skips any operation explicitly assigned to non-TPUs., created when you ran
capture_tpu_profile, appears in
TensorBoard only after you have captured some model data.
- Step time averaged over all sampled steps
- Percentage of time the Host was idle
- Percentage of time the TPU was idle
- Percentage utilization of the TPU matrix units
Step-time graph. Displays a graph of device step time (in milliseconds) over all the steps sampled. The blue area corresponds to the portion of the step time the TPUs were sitting idle waiting for input data from the host. The orange area shows how much of time the Cloud TPU was actually working.
Top 10 TensorFlow operations on TPU. Displays the TensorFlow operations that consumed the most time. Clicking the Show table button displays a table like the following:
When a TensorFlow program reads data from a file it begins at the top of the TensorFlow graph in a pipelined manner. The read process is divided into multiple data processing stages connected in series, where the output of one stage is the input to the next one. This system of reading input pipeline. Use the input pipeline analyzer to understand where the input pipeline is inefficient.
Input pipeline dashboard
To open the input pipeline analyzer, select Profile, then select input_pipeline_analyzer from the Tools dropdown.
The dashboard contains three sections:
- Summary. Summarizes the overall input pipeline with information on whether your application is input bound and, if so, by how much.
- Device-side analysis. Displays detailed, device-side analysis results, including the device step-time and the range of device time spent waiting for input data across cores at each step.
- Host-side analysis. Shows a detailed analysis on the host side, including a breakdown of input processing time on the host.
Input pipeline summary
Section 1
Section 2 details the device-side analysis, providing insights on time spent on the device versus on the host and how much device time was spent waiting for input data from the host.
- Step time plotted against step number. Displays a graph of device step time (in milliseconds) over all the steps sampled. The blue area corresponds to the part of the step time Cloud TPUs sat idle waiting for input data from the host. The orange area shows how much of time the Cloud TPU was actually working.
- Step time statistics. Reports the average, standard deviation, and range ([minimum, maximum]) of the device step time.
- Device time across cores spent waiting for input data, by step number. Displays a line chart showing the amount of device time (expressed as a percentage of total device step time) spent waiting for input data processing. Since the fraction of time spent varies from core to core, the range of fractions for each core is also plotted for each step. Since the time a step takes is determined by the slowest core, you want the range to be as small as possible.
- Fraction of time waiting for input data. Reports the average, standard deviation and the range ([minimum, maximum]) of the fraction of time spent in device waiting for the input data normalized to the total device step time.
Host-side analysis
Section 3 shows the details of host-side analysis, reporting a breakdown of the input processing time (the time spent on Dataset API operations) operations, such as image decompression.
- Enqueuing data to be transferred to device Time spent putting data into an infeed queue before transferring the data to the device.
To see the statistics for individual input operations and their categories broken down by execution time, click the "Show Input Op statistics" button.
A source data table like the following appears:
Each table entry contains the following information:
- Input Op. Shows the TensorFlow op name of the input operation.
- Count. Shows the total number of instances for the operation executed during the profiling period.
- Total Time (in ms). Shows the accumulative sum of time spent on each of those instances.
- Total Time %. Shows the total time spent on an operation as a fraction of the total time spent in input processing.
- Total Self Time (in ms). Shows the accumulative sum of the self time spent on each of those instances. The self time here measures the time spent inside the function body, excluding the time spent in the function it calls. For example, the
Iterator::PaddedBatch::Filter::ForeverRepeat::Mapis called by
Iterator::PaddedBatch::Filter, therefore its total self time is excluded from the total self time of the latter.
- Total Self Time %. Shows the total self time as a fraction of the total time spent on input processing.
- Category. Shows the processing category of the input operation.
Op profile
Op profile (
op_profile) is a Cloud TPU tool that displays the
performance statistics of XLA
operations executed during a profiling period. collects the percentage used of the Cloud TPU computational potential and provides suggestions for optimization.
- Control panel. Contains a settings slider that controls the number of ops displayed in the Op table and a toggle that sets the Op table to list the ops that comprise the top 90% of the total execution time.
- Op table. Lists the top TensorFlow operation categories associated with the XLA ops by the total amount of time, expressed as a percentage of Cloud TPU usage, that all operations in the category took to execute.
- Op details cards. Details about the op that appear when you hover over an op in the table..
- Horizontal Bar. Shows the time distribution across categories.
- hover over a table entry, a card appears on the left displaying details about the XLA op or the operation category. A typical card looks like this:
- Name. Shows the highlighted XLA operation name.
- Category. Shows the operation category.
- FLOPS utilization. Displays FLOPS utilization as a percentage of total FLOPS possible.
- Expression. Shows the XLA expression containing the operation.
- Memory Utilization. Displays the peak memory used by your program as a percentage of total possible.
- to multiply the batch times the feature (16 by 3) then divide the result by the padding, 128 and then by 8.).
Latency of send and recv channels chart
This chart provides details about the send and recv communication channels. Hovering over a bar in this chart displays the send and recv links on the topology graph above. and click on the Profile tab at the top of the screen.:
The Timeline pane contains the following elements:
- Top bar. Contains various auxiliary controls.
- Time axis. Shows time relative to the beginning of the trace.
- Section and track labels. Each section contains multiple tracks and has a triangle on the left that you can click to expand and collapse the section. There is one section for every processing element in the system.
- Tool selector. Contains various tools for interacting with the trace viewer.
- explictly 1.15.0rc1.
To find the IP address for a Cloud TPU host on the Cloud Console, open the TPUs page and look at the displayed table for the name of the Cloud TPU whose trace you want to view.
The Internal IP column for each Cloud TPU contains an IP address,
[TPU_IP].
In your VM, run TensorBoard as follows:
(vm)$ tensorboard --logdir=${MODEL_DIR} --master_tpu_unsecure_channel=[TPU_IP]
The
trace_viewer in the command with your VM name):
gcloud compute ssh $vm --ssh-flag=-L6006:localhost:6006
In the new Cloud Shell, run
capture_tpu_profilewith. | https://cloud.google.com/tpu/docs/cloud-tpu-tools?hl=zh-TW | CC-MAIN-2020-29 | refinedweb | 2,777 | 53.41 |
JSON stands for JavaScript Object Notation. Most developers use it for building endpoints for their web applications. Once you have created an API with endpoints then you can use it in many applications like web v bucks generator applications, mobile apps e.t.c. But while coding you can get the error like module ‘json’ has no attribute ‘loads‘. If you are getting this error then this post is for you.
In this entire tutorial, you will learn how to solve this AttributeError in a simple way.
Cause of AttributeError: module ‘json’ has no attribute ‘loads’
The main cause for getting this error is when you use the same name for your project file and the Python default module. To parse JSON data in python you have to use the JSON module. But there is a conflict between your current directory file name JSON with the JSON module.
When I will run the below lines of code then I will get the module ‘json’ has no attribute ‘loads’ error as the filename for the code written is “json.py”.
import json jsonData = """{"name":"Rob","age":35}""" data = json.loads(jsonData) print(data)
Output
Solution for the module ‘json’ has no attribute ‘loads’ Error
The solution for the AttributeError is very simple. The error was coming because v bucks generator you were using the same file name “json.py” as the default module JSON. It was conflicting. So to remove the error you have to remove or rename the filename for your current directory.
Now if I run the same above code then I will not get the error.
import json jsonData = """{"name":"Rob","age":35}""" data = json.loads(jsonData) print(data)
Output
Conclusion
Most of the time you get Json AttributeError when you are using the same file name as the JSON module. The above AttributeError was an example of it. Even if the problem persists then you v bucks generator have to again reinstall the json module to remove the error.
I hope the above solution has worked for you. If you have any doubts or suggestions then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox. | https://gmailemail-login.email/module-json-has-no-attribute-loads-solved/ | CC-MAIN-2022-33 | refinedweb | 374 | 73.27 |
I want to build a midi controller with 24 10k pots and 24 digital buttons, I have tried several that didn't work, then I found these two examples. I have tested these codes and each work but they are for only 1 button and 1 pot. My question is, how can I expand each to 24 and then combine them into one sketch?
[CODE/*
This is an example of the "Analog" class of the MIDI_controller library.
Connect a potentiometer to analog pin A0. This will be the MIDI channel volume of channel 1.
Map it in your DAW or DJ software.
Written by Pieter P, 08-09-2017
*/
#include <MIDI_Controller.h> // Include the library
// Create a new instance of the class 'Analog', called 'potentiometer', on pin A0,
// that sends MIDI messages with controller 7 (channel volume) on channel 1
Analog potentiometer(A0, MIDI_CC::Channel_Volume, 1);
void setup() {}
void loop() {
// Refresh the MIDI controller (check whether the potentiometer's input has changed since last time, if so, send the new value over MIDI)
MIDI_Controller.refresh();
}][/CODE]
Code:/* This is an example of the "Digital" class of the MIDI_controller library. Connect a push buttons to digital pin 2. Connect the other pin of the button to the ground, a pull-up resistor is not necessary, because the internal one will be used. This button will play MIDI note C4 when pressed. Map it in your DAW or DJ software. Written by tttapa, 08/09/2017 */ #include <MIDI_Controller.h> // Include the library const uint8_t velocity = 0b1111111; // Maximum velocity (0b1111111 = 0x7F = 127) const uint8_t C4 = 60; // Note number 60 is defined as middle C in the MIDI specification // Create a new instance of the class 'Digital', called 'button', on pin 2, that sends MIDI messages with note 'C4' (60) on channel 1, with velocity 127 Digital button(2, C4, 1, velocity); void setup() {} void loop() { // Refresh the button (check whether the button's state has changed since last time, if so, send it over MIDI) MIDI_Controller.refresh(); } | https://forum.pjrc.com/threads/56935-midi-controller?s=419c7ae6179fef6db1753a5eb6b63703&p=210380&viewfull=1 | CC-MAIN-2019-43 | refinedweb | 334 | 59.74 |
Avro schema not properly resolved on data file read.
----------------------------------------------------
Key: AVRO-677
URL:
Project: Avro
Issue Type: Bug
Components: java
Affects Versions: 1.4.0
Reporter: Patrick Linehan
Attachments: schema_test.tar.gz
Based on the "schema resolution and record names" thread:
When reading records from a data file of type namespace1.Record1 using a specific reader of
type namespace2.Record2, reading succeeds even though schema resolution should fail. Instead,
this should require the use of aliases.
I'll be attaching a code example shortly.
--
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online. | http://mail-archives.apache.org/mod_mbox/avro-dev/201010.mbox/%3C3281319.554881286310932659.JavaMail.jira@thor%3E | CC-MAIN-2017-51 | refinedweb | 105 | 70.09 |
boolean send_data(){ boolean end_file = false; char buffer; if (sd.begin(chipSelect, SPI_HALF_SPEED)){ if (myfile.open(filename, O_READ)){ altsoft.println ("sending data"); buffer = myfile.read (); do{ Serial1.print (buffer); //Starts to send data if (Serial1.available ()){ byte inchar = Serial1.read (); altsoft.println (inchar); //debug print if (inchar == XOFF){ altsoft.println ("off"); //debug print do { inchar = Serial1.read (); } while (inchar != XON); delay (10); } } buffer = myfile.read(); } while(buffer >= 0); myfile.close (); Serial1.println ("+++"); } } return (end_file); }
3898911,-692374,121001,202528,194,15,0,03898911,-692374,121001,202528,194,15,0,03898911,-692374,121001,202529,194,15,0,03898911,-692374,121001,202529,194,15,0,03898911,-692374,121001,202530,194,15,0,03898911,-692374,121001,202530,194,10,0 missing characters (one complete line)3898911,-692374,121001,202531,194,15,0,03898910,-692374,121001,202532,194,15,0,03898910,-692374,121001,202532,194,15,0,03898910,-692374,121001,202533,194,15,0,03898910,-692374,121001,202533,194,15,0,03898910,-692374,121001,202534,194,15,0,03898910,-692374,121001,202534,194,15,0,03898910,-692374,121001,202535,194,15,0,03898910,-692374,121001,202535,194,15,0,03898910,-692374,121001,202536,194,15,0,03898910,-692374,121001,202536,194,15,0,03898910,-692375,121001,202537,194,15,0,03898910,-692375,121001,202537,194,15,0,03898910,-692375,121001,202538,194,15,0,03898910,-692375,121001,202538,194,15,0,03898910,-692375,121001,202539,194,15,0,03898910,-692375,121001,202539,194,15,0,0
char buffer;
but in every upload data is only lost in as many place as xoff's are send by the gsm module so I supposse that that data lost are related to my code.
Due to the caracteristics of the gprs communication the data transfer could be variable so a flow control system should not be silly because gprs speed may vary from as few as 8 kbs to 80kbs.
I guess I missed the relationship between the xoff and the missing data.
If you use the hardware serial port to talk to the GPRS, data is buffered, and the Arduino will simply feed it data as fast as it can, making the actual speed of the GPRS irrelevant.
PeterH I will try your approach, thanks!! But perhaps few things would change because the xoff is send by the module when its buffer still have free 63 bytes. Just now I realized that perhaps I detect the xoff character and stops the transmission from the sd card but the tx buffer of the hardware serial remains sending the characters stored and perhaps this is the cause of the missed characters. Perhaps the best solution would be to implement the xon/xoff flow control in the hardware serial library but I think that would be very difficult to my limited knowledge | http://forum.arduino.cc/index.php?topic=141819.msg1064756 | CC-MAIN-2015-40 | refinedweb | 461 | 65.62 |
NAME
kldload - load KLD files into the kernel
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <sys/param.h> #include <sys/linker.h> int kldload(const char *file);
DESCRIPTION
The kldload() system call loads a kld file into the kernel using the kernel linker.
RETURN VALUES
The kldload() system call returns the fileid of the kld file which was loaded into the kernel. If an error occurs, kldload() will return -1 and set errno to indicate the error.
ERRORS.
SEE ALSO
kldfind(2), kldfirstmod(2), kldnext(2), kldstat(2), kldsym(2), kldunload(2), modfind(2), modfnext(2), modnext(2), modstat(2), kld(4), kldload(8)
HISTORY
The kld interface first appeared in FreeBSD 3.0. | http://manpages.ubuntu.com/manpages/hardy/en/man2/kldload.2.html | CC-MAIN-2015-06 | refinedweb | 115 | 55.03 |
-------------------------------------------------------------------------------------
* I'm rewriting PoseMan 2.0 from scratch (python) working fine in Maya 2011 and new Qt interface.
More info, screens, wish list, etc... at poseman facebook page and cgtalk thread
-------------------------------------------------------------------------------------
PoseMan
Pose manager for Maya
Follow PoseMan at FACEBOOK
- New Feature: Create and Open characters at/from any path like regular software. No more charcters attached at maya projecst directory. Easy to share characters and poses :)
- New Feature: Drag And Drop poses to REORDER
- New Feature: Drag And Drop poses to trash icon to DELETE (like shelf)
- New Feature: Delete Sections and Poses are renamed to name.deleted
- Share/Move: Easy to share poses, just copy and paste PoseMan directory or character and sections directory, etc..
- Mix pose slider: Mix character to mix poses!
- Camera Preset: Store 5 camera presets per character to easy create pose thumbnail
- Reference: Works with differentes namespaces
- Bug fixed when apply pose with referecing scenes.
- Dock feature removed (too much buggy)
PoseMan - Feature screen
Camera presets to easy thumbnail capturing - Feature screen
Please use the Feature Requests to give me ideas.
Please use the Support Forum if you have any questions or problems.
Please rate and review in the Review section. | https://ec2-34-231-130-161.compute-1.amazonaws.com/maya/script/poseman-pose-manager-for-maya | CC-MAIN-2022-33 | refinedweb | 197 | 63.7 |
Results 1 to 1 of 1
Thread: iOS 4 keyboard shortcuts
iOS 4 keyboard shortcuts
- Member Since
- Jun 23, 2010
- 1
I love that I can now pair my wireless keyboard to my iPhone 3GS running iOS 4. I've been enjoying typing e-mails and SMS messages much faster than I am usually able to with the touchscreen.
My question: is there a keystroke combination that will send a SMS text message when I've finished composing it? Lacking this, I'm stuck having to touch the "Send" button on the iPhone screen after typing the message itself out on the wireless keyboard. (I know, I know. Woe is me.)
NB: ⌘-S on the keyboard works to send an e-mail composed in the Mail app, but unfortunately has no effect when composing an SMS text message. Pressing the keyboard's return key simply produces a hard return (as you'd expect).
Thanks, all!
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Similar Threads
shortcuts keyboardBy hollander95 in forum OS X - Operating SystemReplies: 3Last Post: 05-29-2015, 02:22 PM
Can you do iOS style Keyboard Shortcuts in Mountain Lion?By Rperez414 in forum Switcher HangoutReplies: 2Last Post: 02-14-2013, 07:26 PM
Keyboard shortcuts wireless keyboardBy nickcp in forum Other Hardware and PeripheralsReplies: 2Last Post: 12-21-2009, 06:59 PM
Keyboard ShortcutsBy johnnyrocket135 in forum Switcher HangoutReplies: 2Last Post: 07-30-2007, 11:29 PM | http://www.mac-forums.com/forums/ios-apps/206154-ios-4-keyboard-shortcuts.html | CC-MAIN-2017-22 | refinedweb | 251 | 67.08 |
import "github.com/facebookgo/atomicfile"
Package atomicfile provides the ability to write a file with an eventual rename on Close (using os.Rename). This allows for a file to always be in a consistent state and never represent an in-progress write.
NOTE: `os.Rename` may not be atomic on your operating system.
File behaves like os.File, but does an atomic rename operation at Close.
New creates a new temporary file that will replace the file at the given path when Closed.
Abort closes the file and removes it instead of replacing the configured file. This is useful if after starting to write to the file you decide you don't want it anymore.
Close the file replacing the configured file.
Package atomicfile imports 3 packages (graph) and is imported by 14 packages. Updated 2017-07-26. Refresh now. Tools for package owners. | https://godoc.org/github.com/facebookgo/atomicfile?utm_source=recordnotfound.com | CC-MAIN-2020-34 | refinedweb | 144 | 59.09 |
Haskell 98 Tutorial
Embed Size (px)
DESCRIPTIONA gentle introduction to haskell 98: Paul Hudak, John Peterson, Joseph Fasel
TRANSCRIPT
<ul><li><p>A Gentle Introduction to Haskell 98</p><p>Paul Hudak</p><p>Yale University</p><p>Department of Computer Science</p><p>John Peterson</p><p>Yale University</p><p>Department of Computer Science</p><p>Joseph H. Fasel</p><p>University of California</p><p>Los Alamos National Laboratory</p><p>October, 1999</p><p>Copyright c 1999 Paul Hudak, John Peterson and Joseph Fasel</p><p>Permission is hereby granted, free of charge, to any person obtaining a copy of \A GentleIntroduction to Haskell" (the Text), to deal in the Text without restriction, including withoutlimitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copiesof the Text, and to permit persons to whom the Text is furnished to do so, subject to the followingcondition: The above copyright notice and this permission notice shall be included in all copies orsubstantial portions of the Text.</p><p>1 Introduction</p><p>Our purpose in writing this tutorial is not to teach programming, nor even to teach functionalprogramming. Rather, it is intended to serve as a supplement to the Haskell Report [4], which isotherwise a rather dense technical exposition. Our goal is to provide a gentle introduction to Haskellfor someone who has experience with at least one other language, preferably a functional language(even if only an \almost-functional" language such as ML or Scheme). If the reader wishes to learnmore about the functional programming style, we highly recommend Bird's text Introduction toFunctional Programming [1] or Davie's An Introduction to Functional Programming Systems UsingHaskell [2]. For a useful survey of functional programming languages and techniques, includingsome of the language design principles used in Haskell, see [3].</p><p>The Haskell language has evolved signicantly since its birth in 1987. This tutorial deals withHaskell 98. Older versions of the language are now obsolete; Haskell users are encouraged to useHaskell 98. There are also many extensions to Haskell 98 that have been widely implemented.These are not yet a formal part of the Haskell language and are not covered in this tutorial.</p><p>Our general strategy for introducing language features is this: motivate the idea, dene someterms, give some examples, and then point to the Report for details. We suggest, however, that thereader completely ignore the details until the Gentle Introduction has been completely read. On the</p><p>1</p></li><li><p>2 2 VALUES, TYPES, AND OTHER GOODIES</p><p>other hand, Haskell's Standard Prelude (in Appendix A of the Report and the standard libraries(found in the Library Report [5]) contain lots of useful examples of Haskell code; we encourage athorough reading once this tutorial is completed. This will not only give the reader a feel for whatreal Haskell code looks like, but will also familiarize her with Haskell's standard set of predenedfunctions and types.</p><p>Finally, the Haskell web site,, has a wealth of information about theHaskell language and its implementations.</p><p> theReport remains the authoritative source for details (references such as \x2.1" refer to sections inthe Report).]</p><p>Haskell is a typeful programming language:1 types are pervasive, and the newcomer is best obecoming well aware of the full power and complexity of Haskell's type system from the outset. Forthose whose only experience is with relatively \untypeful" languages such as Perl, Tcl, or Scheme,this may be a dicult adjustment; for those familiar with Java, C, Modula, or even ML, theadjustment should be easier but still not insignicant, since Haskell's type system is dierent andsomewhat richer than most. In any case, \typeful programming" is part of the Haskell programmingexperience, and cannot be avoided.</p><p>2 Values, Types, and Other Goodies</p><p>Because Haskell is a purely functional language, all computations are done via the evaluation ofexpressions (syntactic terms) to yield values (abstract entities that we regard as answers). Everyvalue has an associated type. (Intuitively, we can think of types as sets of values.) Examplesof expressions include atomic values such as the integer 5, the character 'a', and the function\x -> x+1, as well as structured values such as the list [1,2,3] and the pair ('b',4).</p><p>Just as expressions denote values, type expressions are syntactic terms that denote type values(or just types). Examples of type expressions include the atomic types Integer (innite-precisionintegers), Char (characters), Integer->Integer (functions mapping Integer to Integer), as wellas the structured types [Integer] (homogeneous lists of integers) and (Char,Integer) (character,integer pairs).</p><p>All Haskell values are \rst-class"|they may be passed as arguments to functions, returned asresults, placed in data structures, etc. Haskell types, on the other hand, are not rst-class. Typesin a sense describe values, and the association of a value with its type is called a typing. Using theexamples of values and types above, we write typings as follows:</p><p>5 :: Integer</p><p>'a' :: Char</p><p>inc :: Integer -> Integer</p><p>[1,2,3] :: [Integer]</p><p>('b',4) :: (Char,Integer)1Coined by Luca Cardelli.</p></li><li><p>2.1 Polymorphic Types 3</p><p>The \::" can be read \has type."</p><p>Functions in Haskell are normally dened by a series of equations. For example, the functioninc can be dened by the single equation:</p><p>inc n = n+1</p><p>An equation is an example of a declaration. Another kind of declaration is a type signature decla-ration (x4.4.1), with which we can declare an explicit typing for inc:</p><p>inc :: Integer -> Integer</p><p>We will have much more to say about function denitions in Section 3.</p><p>For pedagogical purposes, when we wish to indicate that an expression e1 evaluates, or \re-duces," to another expression or value e2, we will write:</p><p>e1 ) e2</p><p>For example, note that:</p><p>inc (inc 3) ) 5</p><p>Haskell's static type system denes the formal relationship between types and values (x4.1.3).The static type system ensures that Haskell programs are type safe; that is, that the programmer hasnot nds many program errors at compile time, aids the user in reasoning aboutprograms, and also permits a compiler to generate more ecient code (for example, no run-timetype tags or tests are required).</p><p>The type system also ensures that user-supplied type signatures are correct. In fact, Haskell'stype system is powerful enough to allow us to avoid writing any type signatures at all;2 we saythat the type system infers the correct types for us. Nevertheless, judicious placement of typesignatures such as that we gave for inc is a good idea, since type signatures are a very eectiveform of documentation and help bring programming errors to light.</p><p>[The reader will note that we have capitalized identiers that denote specic types, such asInteger and Char, but not identiers that denote values, such as inc. This is not just a convention:it is enforced by Haskell's lexical syntax. In fact, the case of the other characters matters, too: foo,fOo, and fOO are all distinct identiers.]</p><p>2.1 Polymorphic Types</p><p>Haskell also incorporates polymorphic types|types that are universally quantied in some wayover all types. Polymorphic type expressions essentially describe families of types. For example,(8a)[a] is the family of types consisting of, for every type a, the type of lists of a. Lists of</p><p>2With a few exceptions to be described later.</p></li><li><p>4 2 VALUES, TYPES, AND OTHER GOODIES</p><p>integers (e.g. [1,2,3]), lists of characters (['a','b','c']), even lists of lists of integers, etc., areall members of this family. (Note, however, that [2,'b'] is not a valid example, since there is nosingle type that contains both 2 and 'b'.)</p><p>[Identiers such as a above are called type variables, and are uncapitalized to distinguish themfrom specic types such as Int. Furthermore, since Haskell has only universally quantied types,there is no need to explicitly write out the symbol for universal quantication, and thus we sim-ply write [a] in the example above. In other words, all type variables are implicitly universallyquantied.]</p><p>Lists are a commonly used data structure in functional languages, and are a good vehicle forexplaining the principles of polymorphism. The list [1,2,3] in Haskell is actually shorthand forthe list 1:(2:(3:[])), where [] is the empty list and : is the inx operator that adds its rstargument to the front of its second argument (a list).3 Since : is right associative, we can alsowrite this list as 1:2:3:[].</p><p>As an example of a user-dened function that operates on lists, consider the problem of countingthe number of elements in a list:</p><p>length :: [a] -> Integer</p><p>length [] = 0</p><p>length (x:xs) = 1 + length xs</p><p>This denition is almost self-explanatory. We can read the equations as saying: \The length of theempty list is 0, and the length of a list whose rst element is x and remainder is xs is 1 plus thelength of xs." (Note the naming convention used here; xs is the plural of x, and should be readthat way.)</p><p>Although intuitive, this example highlights an important aspect of Haskell that is yet to beexplained: pattern matching. The left-hand sides of the equations contain patterns such as [] andx:xs. In a function application these patterns are matched against actual parameters in a fairlyintuitive way ([] only matches the empty list, and x:xs will successfully match any list with at leastone element, binding x to the rst element and xs to the rest of the list). If the match succeeds,the right-hand side is evaluated and returned as the result of the application. If it fails, the nextequation is tried, and if all equations fail, an error results.</p><p>Dening functions by pattern matching is quite common in Haskell, and the user should becomefamiliar with the various kinds of patterns that are allowed; we will return to this issue in Section 4.</p><p>The length function is also an example of a polymorphic function. It can be applied to a listcontaining elements of any type, for example [Integer], [Char], or [[Integer]].</p><p>length [1,2,3] ) 3length ['a','b','c'] ) 3length [[1],[2],[3]] ) 3</p><p>Here are two other useful polymorphic functions on lists that will be used later. Function headreturns the rst element of a list, function tail returns all but the rst.</p><p>3: and [] are like Lisp's cons and nil, respectively.</p></li><li><p>2.2 User-Dened Types 5</p><p>head :: [a] -> a</p><p>head (x:xs) = x</p><p>tail :: [a] -> [a]</p><p>tail (x:xs) = xs</p><p>Unlike length, these functions are not dened for all possible values of their argument. A runtimeerror occurs when these functions are applied to an empty list.</p><p>With polymorphic types, we nd that some types are in a sense strictly more general thanothers in the sense that the set of values they dene is larger. For example, the type [a] is moregeneral than [Char]. In other words, the latter type can be derived from the former by a suitablesubstitution for a. With regard to this generalization ordering, Haskell's type system possesses twoimportant properties: First, every well-typed expression is guaranteed to have a unique principaltype (explained below), and second, the principal type can be inferred automatically (x4.1.3). Incomparison to a monomorphically typed language such as C, the reader will nd that polymorphismimproves expressiveness, and type inference lessens the burden of types on the programmer.</p><p>An expression's or function's principal type is the least general type that, intuitively, \containsall instances of the expression". For example, the principal type of head is [a]->a; [b]->a, a->a,or even a are correct types, but too general, whereas something like [Integer]->Integer is toospecic. The existence of unique principal types is the hallmark feature of the Hindley-Milner typesystem, which forms the basis of the type systems of Haskell, ML, Miranda,4 and several other(mostly functional) languages.</p><p>2.2 User-Dened Types</p><p>We can dene our own types in Haskell using a data declaration, which we introduce via a seriesof examples (x4.2.1).</p><p>An important predened type in Haskell is that of truth values:</p><p>data Bool = False | True</p><p>The type being dened here is Bool, and it has exactly two values: True and False. Type Bool isan example of a (nullary) type constructor, and True and False are (also nullary) data constructors(or just constructors, for short).</p><p>Similarly, we might wish to dene a color type:</p><p>data Color = Red | Green | Blue | Indigo | Violet</p><p>Both Bool and Color are examples of enumerated types, since they consist of a nite number ofnullary data constructors.</p><p>Here is an example of a type with just one data constructor:</p><p>data Point a = Pt a a</p><p>Because of the single constructor, a type like Point is often called a tuple type, since it is essentially</p><p>4\Miranda" is a trademark of Research Software, Ltd.</p></li><li><p>6 2 VALUES, TYPES, AND OTHER GOODIES</p><p>just a cartesian product (in this case binary) of other types.5 In contrast, multi-constructor types,such as Bool and Color, are called (disjoint) union or sum types.</p><p>More importantly, however, Point is an example of a polymorphic type: for any type t, itdenes the type of cartesian points that use t as the coordinate type. The Point type can now beseen clearly as a unary type constructor, since from the type t it constructs a new type Point t.(In the same sense, using the list example given earlier, [] is also a type constructor. Given anytype t we can \apply" [] to yield a new type [t]. The Haskell syntax allows [] t to be writtenas [t]. Similarly, -> is a type constructor: given two types t and u, t->u is the type of functionsmapping elements of type t to elements of type u.)</p><p>Note that the type of the binary data constructor Pt is a -> a -> Point a, and thus thefollowing typings are valid:</p><p>Pt 2.0 3.0 :: Point Float</p><p>Pt 'a' 'b' :: Point Char</p><p>Pt True False :: Point Bool</p><p>On the other hand, an expression such as Pt 'a' 1 is ill-typed because 'a' and 1 are of dierenttypes.</p><p>It is important to distinguish between applying a data constructor to yield a value, and applyinga type constructor to yield a type; the former happens at run-time and is how we compute thingsin Haskell, whereas the latter happens at compile-time and is part of the type system's process ofensuring type safety.</p><p>[Type constructors such as Point and data constructors such as Pt are in separate namespaces.This allows the same name to be used for both a type constructor and data constructor, as in thefollowing:</p><p>data Point a = Point a a</p><p>While this may seem a little confusing at rst, it serves to make the link between a type and itsdata constructor mo...</p></li></ul>
Recommended
View more >
?· Programación funcional básica con HASKELL 98 ... Evaluación perezosa 1.4. ... Técnicas de programación…
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using
Haskell 98 Language and Libraries The Revised Report The Haskell 98 Language 1 ... In September of 1987 a meeting was held at the conference on Functional Programming Languages and Computer ... (the latest at that | https://vdocuments.net/haskell-98-tutorial.html | CC-MAIN-2019-51 | refinedweb | 2,699 | 50.26 |
A simple demo to start with:
1. Process 1: lock a region, write a record, pause
2. Process 2: attempt to lock the same region
3. Allow Process 1 to release the lock
4. Process 2 continues
Converting the code was easy (I thought), but no matter what I did I always found the region was locked for the second process - the lock was not being released.
I blame the documentation, and possibly the implementation.
What is not obvious is that the current file position must be reset to the original locking position before the lock gets released. The write (of course) advances the current file position, so by the time we do the unlock we are unlocking a region for which we don't have the lock in the first place! Wouldn't it be better if msvcrt.locking returned a lock object, saving the file position? Anyway, here is my completed demo:
"""
lock_w.py
Run two copies, each in its own terminal session.
Allow one to write a number of records, then switch
to the other showing that it blocks on the same record.
Switch back and release the lock, and show that the
blocked process proceeds.
Also run with lock_r to demonstrate interaction with
read locks.
Default filename is rlock.dat
Clive Darke QA
"""
import msvcrt
import os
import sys
import time
from datetime import datetime
REC_LIM = 20
if len(sys.argv) < 2:
pFilename = "rlock.dat"
else:
pFilename = sys.argv[1]
fh = open(pFilename, "w")
# Do only once
Record = dict()
Record['Pid'] = os.getpid()
for i in range(REC_LIM):
Record['Text'] = "Record number %02d" % i
Record['Time'] = datetime.now().strftime("%H:%M:%S")
# Get the size of the area to be locked
line = str(Record) + "\n"
# Get the current start position
start_pos = fh.tell()
print "Getting lock for",Record['Text']
msvcrt.locking(fh.fileno(), msvcrt.LK_RLCK, len(line)+1)
fh.write(line) # This advances the current position
raw_input("Written record %02d, clear the lock?" % i)
# Save the end position
end_pos = fh.tell()
# Reset the current position before releasing the lock
fh.seek(start_pos)
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, len(line)+1)
# Go back to the end of the written record
fh.seek(end_pos)
fh.close()
1 comment:
You have just saved me hours of trying to figure out what @#$%! was going wrong with my lock-write-unlock tests from yesterday. Thanks for putting this online! | http://darkeside.blogspot.com/2010/11/python-msvcrtlocking-trials-and.html | CC-MAIN-2019-18 | refinedweb | 399 | 76.93 |
Decided to write a quick and short post on using ipython notebooks as I came across this just today and found it to be extremely useful. If you already used ipython then I think ipython notebooks will be super quick to pick up. The idea behind the ipython notebooks is that they’re an ipython session in the browser that you can save and share with others. Then within that session you can easily edit the existing session so you can undo parts of it that you didn’t want to share and the final product is a clean session of python code that you were attempting to show someone else how something works.
The nice thing about ipython notebook is that if you’re already using ipython then you already have it installed and ready to go:
> ipython notebook ...
The previous command will open your browser on an ipython session and you can start writing into the Web UI the same expressions you’d do in ipython on the command line like so:
import random data = [ random.randint(1,1000) for _ in range(0, 10) ] print data
Once you’ve filled in a slot on the screen you can hit Ctrl+Enter or go to the top and press the play button to have your code intepreted and the result rendered in the ipytho notebook. For the above you’d have something like so:
Now you can save the above session and share it with a colleague with ease. Just click on the File -> Download as and pick your option. You can start to see just how useful this is when you share your ipynb file with another pythonista and actually share a piece of executable code that can be used to iterate on an idea within the ipython shell.
For a more interesting example make sure to pip install the vincent library and then have a look at the vincent session from within your own ipython notebook session by starting that session in a directory that contains the ipynb file. If the previous loading worked correctly you’ll be looking at a similar session to the following one:
| http://rlgomes.github.io/work/python/ipython/awesome/notebooks/2014/07/06/10.42-using-ipython-notebooks.html | CC-MAIN-2017-26 | refinedweb | 361 | 67.32 |
This MathML characters are used
to name operators or identifiers that in traditional notation render the
same as other symbols, such as
ⅆ,
ⅇ, or
ⅈ, or
operators that usually render invisibly, such as
,
&InvisiblePlus;, Characters, Entities and Fonts..2 Children versus Arguments, and the attribute value notations and conventions described in Section 2.1..7.
For example,
<mtd> </mtd>
is treated as if it were
<mtd> <mrow> </mrow> </mtd>
and
is treated as if it were dicussed below.
The overall directionality for a formula, basically
the direction of the Layout Schemata, is specified by
the
dir attribute on the containing
math element
(see Section 2.5. ')'., cal codepoints U+2135-U+2138 (ALEF SYMBOL, BET SYMBOL, GIMEL SYMBOL, DALET SYMBOL) should be used. These are strong left-to-right.
MathML provides support for both automatic and manual (forced)
linebreaking of expressions, to break excessively long
expressions into several lines.
All such linebreaks take place within
mrow
(including inferred
mrow; See Section 3.1.3.1 Inferred mrows),
or
mfenced.
The breaks themselves take place at operators (
mo),
and also, for backwards compatibility, at
mspace.
linewrapping possibily.
Indentation — determines the indentation of the
line following a linebreak, including indenting so that the next line aligns with some point in a previous line.
These attributes can be set on
mo and
mspace elements or inherited from
mstyle or
math elements.
The details about the attributes are given in Section 3.2.5.8 Rendering Rules for Linebreaking..
If the next line is not the last line, and if the indentingstyle uses information about the linebreak point to determine how much to indent, then the amount of room left for linebreaking on the next line (ie, tokens elements times the number of,
mglyph and
mline.
The width of these elemnts depend upon their attribute values.
MathML characters can be either represented directly as Unicode character data, or indirectly via numeric or character entity references. See Chapter 6 Characters, Entities and Fonts for a discussion of the advantages and disadvantages of numeric character references versus entity references, and [Entities] for a full list of the entity names available.
New mathematical ,
mglyph and
mline). next section discusses the
mathvariant attribute in
more detail, and a complete technical description of the corresponding
characters is given in Section 6.5 Mathematical Alphanumeric Symbols.
MathML includes four mathematics style attributes.
These attributes are valid on all presentation token elements
,
and on no other elements except
mstyle.
The attributes are:
(See Section 2.1.4 Using CSS with MathML and Appendix C Sample CSS Style Sheet for MathML for further discussion and a sample CSS style sheet. When CSS is not available, it is up to the internal style mechanism of the rendering application to visually distinguish the different logical classes.., or
in the last resort, the deprecated style attributes of MathML 1 could be
used.
Token elements also permit
id,
xref,
class and
style
attributes for compatibility with style sheet
mechanisms, as described in Section 2.1 are deprecated in MathML 2 and
should render in a normal weight font, and
should render in a normal weight sans serif font. In the example.1.3.3 CSS-compatible attributes).
The
mathcolor (and deprecated
color) attribute controls the color in which the
content of tokens is rendered. Additionally, when inherited from
mstyle or from a MathML expression's rendering
environment, it controls the color of all other drawing by MathML
elements, including the lines or radical signs that can be drawn by
mfrac,
mtable, or
msqrt.
The values of
mathcolor,
color,
mathbackground, and
background can be specified
as a string consisting of "#" followed without intervening whitespace
by either 1-digit or 2-digit hexadecimal values for the red, green,
and blue components, respectively, of the desired color. The same number of digits must be used for each
component. No whitespace is allowed between the '#' and the
hexadecimal values. The hexadecimal digits are not
case-sensitive. The possible 1-digit values range from 0 (component
not present) to F (component fully present), and the possible 2-digit
values range from 00 (component not present) to FF (component fully
present), with the 1-digit value x being equivalent to the
2-digit value xx (rather than x0).
These attributes can also be specified as an
html-color-name, which is defined below. Additionally, the keyword "transparent" may
be used for the
background attribute.
The color syntax described above is a subset of the syntax of the
color and
background-color
properties of CSS. The
background-color syntax
is in turn a subset of the full CSS
background
property syntax, which also permits specification of (for example)
background images with optional repeats. The more general attribute name
background is used in MathML to facilitate possible
extensions to the attribute's scope in future versions of MathML.
Color values on either attribute can also be specified as an
html-color-name, that is, as:.5 Mathematical Alphanumeric Symbols and Section 3.2.1.1 Alphanumeric symbol
characters) the value of the
mathvariant attribute should be resolved first,
including the special defaulting behavior described above..5 Operator, Fence, Separator or Accent
(mo).
Miscellaneous text that should be treated as a "term" can also be
represented by an
mi element, as in:
When an
mi is used in such exceptional
situations, explicitly setting the
fontstyle attribute
may give better results than the default behavior of some
renderers.
The names of symbolic constants should be represented as
mi elements:
Use of special entity references for such constants can simplify the interpretation of MathML presentation elements. See Chapter 6 Characters, Entitiesalone
Many mathematical numbers should be represented using presentation
elements other than
mn alone; this includes
complex numbers, ratios of numbers shown as fractions, and
names of numeric constants. Examples of MathML representations of
such numbers include:.
Because of the large number of operators allowed on
mo elements,
the listing is broken into the three subsections below..
h-unit represents a unit of horizontal
length, and
v-unit represents a unit of vertical
length (see
Section 2.1.3.2 Attributes with units).
namedspace is one of
"veryverythinmathspace",
"verythinmathspace",
"thinmathspace",
"mediummathspace",
"thickmathspace",
"verythickmathspace", or
"veryverythickmathspace".
Similarly,
namedbreakstyle is one of
"lbprefix",
"lbpostfix",
"lbopen",
"lbclose",
"lbseparator", or
"lbbinary".
These values can be set by using the
mstyle element
as is further discussed in Section 3.3.4 Style Change (mstyle).
<=.
The following attributes affect when a linebreak does or does not occur, and the amount of vertical space used before the next line when a linebreak does occur.
The meanings of these attributes are given in Section 3.2.5.8.1 Linebreaking Attributes.
The following attributes.
The meanings of these attributes are given in Section 3.2.5.8.3 Linebreaking Indentation Attributes.)
[0,1)
f(x,y)
Certain operators that are "invisible" in traditional
mathematical notation should be represented using specific entity
references within
mo elements, rather than simply
by nothing. The entity references used for these "invisible
operators" are:
The MathML representations of the examples in the above table are: of length (i.e. number of arguments) greater than
one (ignoring all space-like arguments (see Section 3.2.7 Space (mspace)) in the
determination of both the length and the first argument), the prefix form
is used;
if it is the last argument in an
mrow of
length greater than one (ignoring all space-like arguments), the postfix
form is used;
in all other cases, including when the operator is not part of an Semantic Annotations),.
The
linebreak attribute is used to give a linebreaking
hint to a visual renderer.
The default value is
"auto", which indicates that a renderer should use
its default linebreaking algorithm to determine whether to break or not break at this operator.
The value "newline" is used to force a linebreak.
The others values only affect automatic linebreaking.
For automatic linebreaking,
"nobreak" forbids a break,
"goodbreak" suggests a good position for a break,
while "goodbreak" suggests a poor position for a break.
Note that values on adjacent
mo and
mspace elements do
not interact; a "nobreak" on an
mspace will
not, in itself, inhibit a break on an adjacent
mo element.
The
lineleading attribute specifies the amount of vertical space to use after the linebreak.
This can be a fixed amount of space such as
2pt.
If a percentage is given, the renderer is free choose the amount of the space it uses for leading.
For tall lines, it is often clearer to use more leading around them than if the lines are not tall.
A value of "100%" means to use the renderer's default amount of space;
a value of "200%" means that twice the defalt amount should be used
and "50%" means to use half of the space.
The default amount of space to use is left to the renderer to decide.
The
linebreakstyle attribute specifies whether to break before
or after certain operators:
"before" means to break before the operator, placing it at the beginning of the new line;
"after" means to break after the operator, placing it at the end of the broken line;
"duplicate" means to duplicate the operator, placing it both at the end of the broken line and at the beginning of the new line.
linebreakstyle may also be a
namedbreakstyle, which is one of
"lbprefix",
"lbpostfix",
"lbopen",
"lbclose",
"lbseparator", or
"lbbinary".
Ultimately, these values are one of "before", "after", or "duplicate".
namedbreakstyle values can be set by using the
mstyle or
math element
as is further discussed in Section 3.3.4 Style Change (mstyle).
By setting a
namedbreakstyle value in an
mstyle element, all operators that occur within that element and have that break style will break relative to the operator
identically. "lbbinary" is likely to be the most commonly changed value.
The
linebreakmultchar specifies what to display when a break
occurs at an operator. For example, to display
a center dot if a linebreak occurs at this point, the following could be used:
<mo linebreakmultchar ="·<!--MIDDLE DOT-->"> <!--INVISIBLE TIMES--> </mo>
Note: the only use case for displaying a different character when linebreaking that was found was to make an invisible times operator visible. If other uses cases are found, subsequent versions of MathML may generalize this attribute to be a characteristic of the operator that is looked up in the operator dictionary.
There are several attributes that that element.
They may also appear on any ancestor of the
math element, if permitted by
the containing document, to provide defaults for all contained
math elements.
In such cases, the attributes would be in the MathML namespace.
The attributes
indentstyle and
indentoffset work together to
determine the amount of indentation to use on the new line after a linebreak.
The
indentoffset attribute is applied after
indentstyle to alter the
indentation (either to the left or to the right) by a fixed amount.
These two attributes apply to all lines, possibly excepting the first and last lines.
The pair
indentstylefirst and
indentoffsetfirst applies to the
first line.
The pair
indentstylelast and
indentoffsetlast applies to the
last line, if there is more than one line.
"indentstyle" and "indentoffset" are the defaults for the first and last variants,
so that they inherit the current values used for the center lines.
The legal values of indentstyle are:
The value used for indenting is determined at the point of the linebreak.
For the first line, the value used for indentation is the value of
indentstylefirst
inherited by first element that is rendered.
This means that for
indentstylefirst to be used, it must be set on an
mstyle element or other legal element that encloses the first element that is rendered.
With the exception of "center"
and "right", all of the above values result in a zero width indent for the first line.
Note that for
indentoffset,
indentoffsetfirst
and
indentoffsetlast, font relative values such as
3em
refer to the font in effect at the point of use, not at the point of declaration.
For example, if
indentoffset='2em' is specified on the
math
element, the indentation will be 2 ems from the font in effect at the linebreak,
rather than the font in effect at the
math element.
In practice, however, these will almost always be the same.
A render may ignore the values of the
indentstyle and
indentoffset
attributes if they result in a line in which the remaining width is too
small to usefully display the expression or if they result in a line in
which the remaining width exceeds the available linewrapping width.
If
indentstyle,
indentstylefirst, or
indentstylelast
is "id", then the value of
indenttarget is used to find the ID
value to use for alignment. If the value of
indenttarget is not a valid ID,
or if the ID is not present, then "auto" is used to determine indenting.
The values of
id must be unique within the scope of the entire document.
MathML generators that create id values should take care to create unique values.
"id"s can occur in any MathML element, including invisible elements
inside of an
mphantom. However, the "id" must occur in the
expression or document before it is referenced. It is permissible
for the "id" value may be inside another
math element prior
to the current point of reference. This allows for inter-expression alignment.
However, the "id" may not be visible to or usable by MathML renderers;
in those cases, renderers should treat it as not being present and "auto"
should be used to determine linebreaking.
Note that there is only one
indenttarget attribute; its value is shared by
indentstyle and
indentstylelast. This means that it is not possible
to use different values for "id" for the first and last line for automatic
linebreaking without using the
indenttarget
attribute on all possible break points. However, because you can
specify its value at a forced break, it is possible to use different
values for manual linebreaking..".
The above should render as
as opposed to the default rendering
.
Note that each parenthesis is sized independently; if only one of
them had
maxsize="1", they would render with different
sizes..
If
symmetric="true",
then the maximum of the height and depth is used to determine the size,
before application of the
minsize or
maxsize attributes.
The preceding rules also apply in situations where the
mrow element.
If a stretchy operator is a direct sub-expression of an
munder,
mover, or
munderover element, or if it is the sole direct
sub-expression of an
mtd element in some column of a
table, then it start
∑,
∏," or conveying meaning in Section 3.3.6 Adjust Space Around Content (mpadded).
In some cases, text embedded in mathematics could be more appropriately
represented using
mo or
mi elements.
For example, the expression 'there exists
such that f(x) <1' is equivalent to
and could be represented as:.
mspace elements accept the attributes described
in Section 3.2.2 Mathematics style attributes common to token
elements,
but note that
mathvariant and
mathcolor have no effect.
mathsize only affects the interpretation of units in sizing
attributes (see Section 2.1.3.2 Attributes with units).
Additionally, it accepts the attributes described in
Section 3.2.5.2.3 Indentation attributes and the attributes listed below.
"h-unit" and "v-unit" represent units of horizontal or vertical length, respectively (see Section 2.1.3.2 Attributes with units).
The "spacing" attribute is a
string-valued variable whose default value is the empty string
(""). The spacing attribute specifies that the width of the space is
the same as the length of the attribute value in the current font, as
if the text had been the content of and
mtext element.
The total width of a
mspace is given by the sum
of both the "width" and "spacing"
attributes. The "spacing" attribute does not affect the height or depth
of the
mspace.
The
linebreak attribute is used to give a linebreaking
hint to a visual renderer.
It behaves identically to the
linebreak of
mo.
The default value is
"auto", which indicates that a renderer should use
whatever default linebreaking algorithm it would normally use.
The meanings of the other values are described in Section 3.2.5.8.1 Linebreaking Attributes.
The value "indentingnewline" was defined in MathML2 for
mspace;
it is now deprecated. Its meaning is the same as
newline, which is compatible with its earlier use when no other linebreaking attributes are specified.
The spacing that normally follows an operator is not used at the end of a line. Similarly, the space that normally preceeds an operator is not used at the beginning of a line..
<mspace spacing="00"/> <mspace spacing="×<!--MULTIPLICATION SIGN-->000,00"/> <mspace height="3ex" depth="2ex"/> <mrow> <mi>a</mi> <mo id="firstop">+</mo> <mi>b</mi> <mspace linebreak="newline" indentto=
&.
Like all token elements,
ms does trim and
collapse whitespace in its content according to the rules of
Section 2.1.5 Collapsing Whitespace in Input, so whitespace intended to remain in
the content should be encoded as described in that section.
ms elements accept the attributes listed in
Section 3.2.2 Mathematics style attributes common to token
elements, and additionally:
In visual renderers, the content of an
ms
element is typically rendered with no extra spacing added around the
string, and the quote characters at the beginning and the end of the
string. By default, the left and right quote characters are both the
standard double quote character
". However,
these characters can be changed with the
lquote and
rquote attributes respectively
(which should be interpreted as opening and
closing quotes, respectively). \"".
mglyph)
The
mglyph element provides a mechanism
for displaying images to represent non-standard symbols.
It is generally used as the content of
mi or
mo
elements.
mglyph elements accept the attributes listed in
Section 3.2.2 Mathematics style attributes common to token
elements, but note that
mathvariant and
mathcolor have no effect.
mathsize only affects the interpretation of units in sizing
attributes (see Section 2.1.3.2 Attributes with units).
The background color,
mathbackground, should show through
if the specified image has transparency.
mglyph also accepts the additional attributes listed here.
The
alt attribute provides an alternate name
for the glyph. If the specified image can't be found or displayed,
the renderer may use this name in a warning message or some unknown glyph notation.
The name might also be used by an audio renderer or symbol processing
system and should be chosen to be descriptive.
The
src attribute specifies the location of the image resource;
it may be a URI relative to the base-uri of the source of the MathML, if any.
Examples of widely recognized image formats include GIF, JPEG and PNG; However,
it may be advisable to omit the extension from the
src uri, so
that a user agent may use content-negotiation to choose the most appropriate format.
The
src uniquely identifies the
mglyph; two
mglyphs
with the same values for
src should
be considered identical by applications that must determine whether
two characters/glyphs are identical. The
alt
attribute should not be part of the identity test.
The
width and
height attributes specify
the desired size of the glyph. They are both optional. If neither are given,
the renderer should render the image at its natural size. If only one is
given, the renderer should respect that dimension and choose the other dimension
so as to preserve the aspect ratio of the image.
By default, the bottom of the image aligns to the
current baseline. The
valign attribute specifies the alignment
point within the image. A positive value of
valign
shifts the bottom of the image below the current baseline, while
a negative value will raise it above the baseline., they were required ttributes; they are now optional attributes.
If both a
src and
fontfamily attribute are present, the
fontfamily attribute is ignored.
The
fontfamily and
index attributes named a font
and position within that font.
mline
mline draws a horizontal line.
The length and width of the line are specified as attributes.
mline elements accept the attributes listed in
Section 3.2.2 Mathematics style attributes common to token
elements, but note that
mathvariant
has no effect.
mathsize only affects the interpretation of units in sizing
attributes (see Section 2.1.3.2 Attributes with units).
The
linethickness attribute specifies how thick the line should be
drawn.
The
spacing attribute specifies that the length of
the line is the same as the length of the attribute value in the
current font.
The
length attribute specifies the length of the
line using a specification that is the same as the
width attribute
of
mspace ., in a context with LTR directionality,
or right torows),
although the control of linebreaking is effected through attributes
on other elements (See Section 3.1.6 Linebreaking of Expressions).
mrow elements accept the attributes listed in
Section 2.1.4 Attributes Shared by all MathML Elements
and the
dir attribute as described in Section 3.1.5.1 Overall Directionality of Mathematics Formulas.of leading operator has an infix or
prefix form (perhaps inferred), the following operator has an infix or
postfix form, and the operators are listed in the same group of
entries in the operator dictionary provided in Appendix:
The proper encoding of (x, y) furnishes a less obvious
example of nesting
mrows: elements accept the attributes listed below
in addition to those listed in Section 2.1.4 Attributes Shared by all MathML Elements.:
In a RTL directionality context,
the numerator leads (on the right) and the demonator follows (on the left).
In this case, the diagonal line slants upwards going from right to left.
Although this format is an established convention, it is not universally
followed; for situations where a forward slash is desired in a RTL context,
alternative markup, such as an
mo within an
mrow should be used.).).
msqrt and
mroot elements accept the attributes listed in
Section 2.1).)
Note that in a RTL directionality, the surd begins
on the right, rather than the left, along with the index in the case
of
mroot..
Other attributes, such as
linethickness on
mfrac, have default values that are not normally
inherited. That is, if the
linethickness attribute
is not set on the start tag,
when
lspace is set with
mstyle, it applies only to
the
mo element and not
mpadded. 2.1.4 Attributes Shared by all MathML Elements. Section 2.5.2 The Top-Level
math Element..1.1.
Color and background attributes are discussed in Section 3.2.2.2 Color-related attributes..
The spacing between operators is often one of a small number of
potential values. MathML names these values and allows their values to
be changed. Because the default values for spacing around operators
that are given in the operator dictionary Appendix B Operator Dictionary
are defined using these named spaces, changing their values will produce
tighter or looser spacing. These values can be used anywhere a
h-unit or
v-unit unit is
allowed. See Section 2.1.
When an expression is broken at an operator, the break will occur before or after the operator, or the operater will be duplicated on both lines. The breaking is typically similar for classes of operators, such as separators and prefix operators. MathML gives these classes a name so that the default behavior for each class can be easily changed. In practice, it is likely that only "lbbinary" will be changed. See Section 2.1.3.2 Attributes with units.
The predefined
namedbreakstyles are:
"lbprefix",
"lbpostfix",
"lbopen",
"lbclose",
"lbseparator", or
"lbbinary".
The default values for these are given in the table in
Section 3.3.4.2 Attributes.
merror)
The
merror element displays its contents as an
"error message". This might be done, for example, by displaying the
contents in red, flashing the contents, or changing the background
color. The contents can be any expression or expression sequence.
merror accepts any number of arguments; if
this number is not 1, its contents are treated as a single "inferred
mrow" as described in.
mstyle>merror elements accept the attributes listed in
Section 2.1.4 Attributes Shared by all MathML
Note that the preprocessor's input is not, in this case, valid MathML, but the error message it outputs is valid MathML.
mpadded)
An
mpadded element renders the same as its. While the name of the element
reflects the use of
mpadded to add "padding", or extra
space, around its content, by adding negative "padding" it is
possible to cause).
mpadded elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.
(The pseudo-unit syntax symbol is described below.)
These attributes modify the size and position of
the "bounding box" of the
mpadded element. The
typographical layout parameters defined by these attributes are
described.1.1.3.2 Attributes with units, not including
%. The possible
pseudo-units are the keywords
width,
advancewidth,
lspace,
height, and
depth; they each represent the
length of the same-named dimension of the
mpadded element's
content (not of the
mpadded element itself). The lengths
represented by h-unit or v-unit are
described in Section 2.1 ... </mpadded> <mpadded width="100%"> ... </mpadded> <mpadded width="100% width"> ... </mpadded> <mpadded width="1 width"> ... </mpadded> <mpadded width="1.0 width"> ... </mpadded> <mpadded> ... </mpadded>
See Appendix, and an advance width that determines the natural
placement of the next typographical element following it. The advance
width, like the positioning point, is generally at a fixed location
relative to the visual bounding box.
The size of the bounding box and the relative location of the
positioning point for the
mpadded element are defined by its
size and positioning attributes. The child content of the
mpadded element is always rendered with its natural
positioning point coinciding with the positioning point of the
mpadded elements. Thus, by using the size and position
attributes of
mpadded to expand or shrink its bounding box, the visual
effect is to pad or clip the child content.
The
width attribute refers to the horizontal
width of the natural visual bounding box of the
mpadded
element's content. Note that decreasing the width will cause clipping
to take place when rendering the child content. For example, setting
the width to 0 would entirely suppress the rendering of the child
content. clipping of of MathML
renderers might be still more productive, in the long run.
MathML elements that permit "negative spacing", namely
mspace,
mpadded, and
mtext,.
If such constructs are used in spite of this warning, they should
be enclosed in a
semantics element that also
provides an additional MathML expression that can be interpreted in a
standard way.
For example, the MathML expression.
mphantom elements accept the attributes listed in
Section 2.1.4 Attributes Shared by all MathML Elements..
There is one situation where the preceding rule
and
<mfenced> <mi>x</mi> <mi>y</mi> </mfenced>
renders as "(x, y)"
and is equivalent to 2.1.1.5 Collapsing Whitespace in Input.)
In value of
separators is a sequence of zero or more
separator characters (or entity references), optionally separated by
whitespace. Each
sep#i consists of exactly
one character or entity reference. Thus,
separators=",;"
is equivalent to
separators=" , ; "...
menclose elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.. For example,
notation="circle horizontalstrike" should
result in circle around the contents of
menclose with a
horizontal line through the contents.
When
notation has the value "longdiv",
the contents are drawn enclosed by a long division symbol. A complete
example of long division is accomplished by also using
mtable
and
malign. "madruwb" should generate an enclosure representing an Arabic factorial (`madruwb' is the transliteration of the Arabic مضروب for factorial). For example
should be rendered under
mstyle (Section 3.3.4 Style Change (mstyle)).:
msub)
msub elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.
The
subscriptshift attribute specifies the minimum
amount to shift the baseline of subscript down.
v-unit represents a unit of vertical length (see Section 2.1)
msup elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.
The
superscriptshift attribute specifies the
minimum amount to shift the baseline of superscript up.
v-unit represents a unit of vertical length (see Section 2.1 as shown here
versus the staggered positioning of nested scripts as shown here
.
The syntax for the
msubsup element is:
<msubsup> base subscript superscript </msubsup>
msubsup elements accept the attributes listed
below in addition to those specified in Section 2.1.1).)under)
munder elements accept the attributes listed
below in addition to those specified in Section 2.1over)
mover elements accept the attributes listed
below in addition to those specified in Section 2.1underover)
The syntax for the
munderover element is:
<munderover> base underscript overscript </munderover>
munderover elements accept the attributes listed
below in addition to those specified in Section 2.1,
mmultiscripts. This element allows the
representation of any number of vertically-aligned pairs of subscripts
and superscripts, attached to one base expression. It supports both
postscripts (to the right of the base in visual notation) and
prescripts (to the left of the base in visual notation). given elements
mprescripts and
none are only allowed as direct sub-expressions. (These attributes are inherited by
every element through its rendering environment, but can be set explicitly
only on
mstyle; see Section 3.3.4 Style Change somewhat similar to tables, the alignment issues for representing some two-dimensioal layouts in elemenatary such as
addition and multiplication differ in some important ways.
mcolumn is used for tabular elementary math notations.
See Section 3.7 Elementary Math for a discussion about elementary math notations.
In addition to the table elements mentiond and 3 deprecate the inference
of
mtr and
mtd elements;
mtr and
mtd elements
must be used inside of
mtable and
mtr respectively..
mtable elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.
Note that the default value for each of
rowlines,
columnlines and
frame is the literal string
"none", meaning that the default is to render no lines,
rather than that there is no default.
As described in Section 2.1 math
element. When the value is "auto", the MathML
renderer should calculate the table width from its contents using
whatever layout algorithm it chooses..
In those attributes' syntaxes, h-unit or
v-unit represents a unit of horizontal or vertical
length, respectively (see Section 2.1.3.2 Attributes with units). The units shown in the
attributes' default values (
em or
ex) are
typically used.. on the right with
mtd
elements when they are shorter than other rows in a table.
mtr elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathMLors start tag..
mtd elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements..-argument
mtd element;
an
mstyle element; the table cells that are divided into alignment groups, every
element in their content must be part of exactly one alignment group,
except Several MarkupsAttributes
malignmark elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.Attributes
maligngroup elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements. application that.
mcolumn
mcolumn is typically used to layout numbers that are
aligned on each digit. This is common in many elementary math notations such as 2D addition and multiplication.
Inside an
mcolumn, the character inside of the token elements
mi,
mn,
mo, and
mtext each occupy a column.
The width of a column is the maximum of the widths of each character in that column.
If a child of
mcolumn is not one of the token elements listed above, then that element is considered to be a single digit wide.
The exceptions to this are
mspace,
mline,
mstyle and
mrow.
mspace and
mline have the amount of space specifed by them and do not participate in the computation of the width of a column.
The width rule should be applied (recursively) to the child of
mstyle.
For
mrow, the width is the sum of the widths of each child.
Inside of a
mcolumn,
mrow does not perform automatic spacing or linebreaking.
If there is no character in a column, its width is taken to be the width of a 0 in the current language (in many fonts, all
digits have the same width).
If a child is too small or to large to fit within a column, the
columnalign attribute controls whether it is left, center, or right aligned.
The width of a
mcolumn is the sum of the widths of all of the columns; no spacing should be added between columns.
The baseline of the
mcolumn is specifed by the
align attribute.
mcolumn elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML Elements.
The
justify attribute specifies whether the row
is to be left justified or right justified.
The
columnalign attribute specifies
how the entries in each column should be aligned if they are bigger or smaller than the column width. The specification for
columnalign is the same as
columnalign in mtable.
See Section 3.5.1 Table or Matrix
(mtable) for the full specification of the attribute value.
If an element is too large to fit within a column, the
columnalign attribute controls its alignment with respect to that column and any excess overflows into the surrounding columns. This
excess does not participate in the column width calculation. In these cases, authors should take care to avoid collisions
between column overflows.
The
align attribute specifies where to align the
mcolumn with respect to its environment. Its specification is the same as that
for
mtable's
align attribute.
See Section 3.5.1 Table or Matrix
(mtable) for the full specification of the attribute value
The MathML for this is:
Here is an example with the operator on the right. Placing the operator on the right is standard in the Netherlands and some other countries.
Because the default alignment is placed to the right of number, the numbers align properly and none of the rows need to be shifted.
Here is an example of subtraction where there is a borrow with multiple digits in a single column and a cross out. The borrowed amount is underlined (the example is from a Swedish source):
Here is how it can be done with
mcolumn:
Note that because
menclose is not one of the listed elements above,
it is considered to be a single digit wide so that its use does not
make that column wider. If it is too wide, it overflows into the other
columns.
Notice also that the combining long solidus ( / ) is used
rather than
menclose. This is done because it logically keeps
the number 57 as a single number in an
mn. An
menclose can be used, but the use of combining characters is
recommended for the above reason. U+20E5 can be used for a reverse
strike out, along with other overlay characters. If more than one
character should be included in the cross out (as opposed to multiple
characters that are individually crossed out), then
menclose
should be used.
Carries and borrows are typically reduced in size, but the
computation of their size is based on the number of digits as
specified above, and the digit size is taken as the size of a digit in
effect at the
mcolumn. If there is more than one carry, it
may be more convenient to wrap all of the carries in a single
mstyle as shown below:
Here is a bigger example that illustrates using various values besides digits as the "spacing" attribute's value.
This example has multiple rows of carries. It also (somewhat artificially) includes ","s as digit separators. The encoding includes these separators in the spacing attribute value, along non-ASCII values.
maction)
There are many ways in which it might be desirable to make mathematical content active. Adding a link to a MathML sub-expression is one basic kind of interactivity. See Section 7.3.1 Mixing.
maction elements accept the attributes listed
below in addition to those specified in Section 2.1.4 Attributes Shared by all MathML.
Since a MathML application is not
required to recognize any particular
actiontypes, an
application can be in MathML conformance Section 2.5.2 The Top-Level
math Element,.
foreseeable,
non-standard attributes from another namespace are being used to pass
additional information to renderers that support them, without violating the MathML DTD (see
Section 2.3.3 Attributes for unspecified data). The
my:color attribute
changes the color of the characters in the presentation, while the
my:background attribute changes the color of the background
behind the characters.
Mathematics used in the lower grades tends to be tabular in nature. However, the specific notation used varies among countries much more than it does for higher level math. Furthermore, elementary math often presents examples in some intermediate step and MathML must be able to capture these intermediate or intentionally missing partial forms.
The elements needed for elementary math are presented elsewhere in this chapter. In this section, examples are given of how these elements can be used to display various notations used for elementary mathematics.
Two-dimensional addition, subtraction, and multiplication typically
involve numbers, carrries/borrows, lines, and the sign of the
operation.
These are supported by MathML inside of
mcolumn.
Lines are drawn using
mline
and alignment is achieved via padding each line with
mspace.
The notation used for long division varies considerably among countries. Many notations share the common characteristics of aligning intermediate results and drawing lines for the operands to be subtracted. The line that is drawn various in length depending upon the notation.
The position of the divisor varies, as does the location of the quotient, remainder, and intermediate terms.
The US method for long division is
The MathML for this is:
The French method for long division is
The MathML for this is:over,
munder, and
mline. The MathML for the preceeding examples above is given below.
<mover align="right"> <mn> 0.3333 </mn> <mline spacing="3"/> </mover>
<mover align="right"> <mn> 0.142857 </mn> <mline spacing="142857"/> </mover>
<munder align="right"> <mn> 0.142857 </mn> <mline spacing="142857"/> </munder >
<mover align="right" diff="add"> <mn> 0.142857 </mn> <mrow> <mo>.</mo> <mspace spacing="4285"/> <mo>.</mo> </mrow> </mover>="MathML-presentation" must be used and presentation
MathML processors should use this value for the presentation.
See Section 5.1 Semantic Annotations for more details about the
semantics and
annotation-xml elements. | http://www.w3.org/TR/2008/WD-MathML3-20081117/chapter3.xml | CC-MAIN-2015-32 | refinedweb | 6,519 | 55.03 |
Into The Labyrinth With x3dom
Today I will talk about x3dom, pronounced Xfreedom. It's a new set of HTML elements to render 3D scenes declaratively. To explore X3Dom, I'll take my marble maze project (a 2d labyrinth where you can move the ball by tilting your device) and render it in 3D.
What Is X3Dom?
x3dom is a recommended standard still in discussion. It allows drawing 3d in the browser using tags. Think
svg, but in 3 dimensions. What's great about x3dom is it's declarative.
For example, to display an interactive cube that you can rotate with the mouse, you just need the following code:
<x3d width="500px" height="400px"> <scene> <shape> <appearance> <material diffuseColor="1 0 0"></material> </appearance> <box></box> </shape> </scene> </x3d>
Here is the same with webGl. That's 234 hard to read lines of code, with matrix manipulation, ArrayBuffer, a mathematic formula to rotate the cube, and more...
The x3dom specification is far from complete. But yet there is already an open source project to try it now. Add the following
<script> tag to your HTML, and it will automatically process any
x3dom tags.
<script type="text/javascript" src="" ></script>
X3Dom and React
My Marble Maze project was done with React. Is it possible to render
x3dom elements in React? React can render any element, but restricts the lowercase elements to the HTML specification. So React does not recognize the
x3dom tags and fills the console with warnings. To silence these warnings, I needed to use the
is prop. Basically, it tells React that an element does exist:
<x3d is="x3d">
Additionally, the x3dom library parses the page for any
<x3d> root element on load. To mount a
<x3d> element later, I had to tell x3dom to reload:
window.x3dom.reload()
Note that once the
<x3d> root is detected, it's possible to change its children, and the change will be automatically taken into account. I only needed to reload when adding a
<x3d> root.
Rendering a Maze
My marble maze implementation generates random mazes using the
generate-maze npm package. It uses eller's algorithm.
The maze structure is a 2d matrix of the following object:
{ x: 4, // Horizontal position, integer y: 7, // Vertical position, integer top: false, // is top wall blocked, boolean left: false, // is left wall blocked, boolean bottom: true, // is bottom wall blocked, boolean right: true, // is right wall blocked, boolean }
In the previous implementation, I used a simple div for each object. And I used the style border to display walls based on the top, bottom, left, and right boolean.
{ maze.map(row => row.map(({ x, y, top, left, bottom, right }) => { return ( <div key={`${x}-${y}`} style={{ position: 'absolute', top: y * cellSize, left: x * cellSize, width: cellSize, height: cellSize, borderTop: top ? '2px black solid' : 'none', borderLeft: left ? '2px black solid' : 'none', borderBottom: bottom ? '2px black solid' : 'none', borderRight: right ? '2px black solid' : 'none', boxSizing: 'border-box', }} /> ); }), ); }
Maze Walls
I chose to render a
<box> for each wall. I created a
Box React component for that purpose:
import React from 'react'; const Box = ({ x, y, texture, width, height, depth }) => { return ( <transform is="transform" translation={`${x} ${y}`}> <shape is="shape"> <appearance is="appearance"> <imageTexture scale="false" is="imageTexture" url={texture} /> </appearance> <box is="box" size={`${width},${height},${depth}`}></box> </shape> </transform> ); };
<transform>allows placing the shape. You can translate, rotate, and scale the children of the
<transform>tag. Here I need to translate.
<shape>allows to group a geometry (like box, sphere, cylinder etc...) with its appearance (material or texture).
<appearance>holds the texture of the box.
<imageTexture>allows loading the image to use as the texture for the box.
<box>defines the box geometry. I specify the
sizehere.
To place the wall, I iterated on the maze array, and placed different boxes based on the direction booleans.
<group is="group"> {maze.map(row => row.map(({ x, y, top, left, bottom, right }) => { return ( <> {top && ( <Box x={x + 0.5} y={-y} width={1} height={0.1} depth={1} texture={wood} /> )} {bottom && ( <Box x={x + 0.5} y={-y - 1} width={1} height={0.1} depth={1} texture={wood} /> )} {left && ( <Box x={x} y={-y - 0.5} width={0.1} height={1} depth={1} texture={wood} /> )} {right && ( <Box x={x + 1} y={-y - 0.5} width={0.1} height={1} depth={1} texture={wood} /> )} </> ); }), )} </group>
Maze Ground
I also needed to render the ground. I used a
<plane> instead of a
<box>, but the principle is the same.
import React from 'react'; const Ground = ({ x = 0, y = 0, z = 0, width, height, texture }) => { return ( <transform is="transform" translation={`${x},${y},${z}`}> <shape is="shape"> <appearance is="appearance"> <imageTexture is="imageTexture" url={texture} /> </appearance> <plane is="plane" lit size={`${width},${height}`}></plane> </shape> </transform> ); };
Marble Madness
Same for the marble, for which I used a
<sphere>.
import React from 'react'; const Marble = ({ x = 0, y = 0, z = 0, radius, texture }) => { return ( <transform is="transform" translation={`${x},${y},${z}`}> <shape is="shape"> <appearance is="appearance"> <imageTexture is="imageTexture" url={texture} /> </appearance> <sphere is="sphere" lit solid radius={radius}></sphere> </shape> </transform> ); };
Rendering A Hole In 3D
For the hole, I did not find a way to drill holes into the plane. Instead, I rendered a small cylinder on top of the plane for each hole. Here is the cylinder component:
import React from 'react'; const Cylinder = ({ x = 0, y = 0, z = 0, rotation, radius, height, diffuseColor, }) => { return ( <transform is="transform" translation={`${x},${y},${z}`} rotation={rotation} > <shape is="shape"> <appearance is="appearance"> <material is="material" diffuseColor={diffuseColor} ></material> </appearance> <cylinder is="cylinder" radius={radius} solid height={height} lit /> </shape> </transform> ); };
By default, the cylinder appeared perpendicular to the plane. So I needed to rotate it by 90° on the X-axis for it to become parallel. From the x3dom documentation, rotation transformations work as follows:
Name Type Default Value Description rotation SFRotation 0,0,1,0 The rotation field specifies a rotation of the coordinate system.
Not really helpful is it? Ok so there are four digits, but what do they represent? Angle for x, y, z-axis? What about the fourth value? What is the unit, degree, or radian?
To be honest, I struggled to find the answer, and this the edutechwiki.unige.ch site saved me. The answer is actually pretty clever.
The format is
x y z angle, where
angle is the rotation in radian. And
x
y and
z can be 0 or 1 and indicates the rotation axis.
So to rotate by 90° on the x-axis I did
1 0 0 Math.PI/2.
And that's all there is to do to render the maze.
Watch What Happens
To admire the labyrinth in all its 3d glory, I needed to determine a point of view with the
<viewpoint> tag.
<viewpoint> allows defining from which point I view the scene. By default, the origin coordinates of the scene are
(0,0,0), which corresponds to the center of the screen.
To render the labyrinth, I chose to have the origin correspond to the top left corner of the labyrinth. This way, I had the same origin as in the 2d version. So now I needed to move the viewpoint to the center of the labyrinth, and up the z-axis a little.
To use
<viewpoint>:
<viewpoint is="viewpoint" centerOfRotation={`${width / 200},${-height / 200},0`} isActive position={`${width / 200},${-height / 200},13`} ></viewpoint>
isActiveallows specifying that this viewpoint is currently used
centerOfRotationsets the coordinates of the point the view will rotate around - here, the center of the labyrinth
positionallows placing the coordinate of the user view - here, above the center of the labyrinth
By default, the scene in x3dom is interactive and allows the user to rotate, translate, and zoom into it. The default interactivity mode is
examine, and other modes are
walk,
fly,
helicopter,
look at,
turn table, and
game. Each interactivity mode has its own controls, see the navigation documentation if you are interested.
In my case, I did not want any interaction. To change the type, I added the
navigationInfo tag.
<navigationInfo is="navigationInfo" type="none"></navigationInfo>
Where
type is the mode we want. Since I wanted a fixed view on the labyrinth, I chose
none.
Here Comes The Sun
By default, the scene is uniformly lit, with no shadow. There are several ways to add a source of light:
- pointlight emits light equally in all directions. Like a sun.
- spotlight emits light in a direction and constrains the light at a specific angle. Like a torchlight.
- directionallight emits light in a given direction without any attenuation.
After trying different tags and values, I ended up using a directional light.
<directionallight is="directionlight" id="directional" direction="0.5 0.5 -1" on="TRUE" intensity="1.0" shadowintensity="0.4" shadowcascades="1" shadowfiltersize="16" shadowmapsize="512" color="1,1,1" znear="-1" zfar="-1" shadowsplitfactor="1" shadowsplitoffset="0.1" ></directionallight>
Rotating the Labyrinth
After rendering a full labyrinth in 3d, I looked for a way to tilt it along with the phone inclination.
The
<transform> tag applies the transformation to the
<group> tag, too. So I needed to apply an x and y rotation based on the x and y acceleration from the
devicemotion event (see my previous article for details). An arbitrary acceleration/100 gives a good result.
I also set the center of the transformation to be the center of the labyrinth.
<transform is="transform" rotation={`0 1 0 ${xAcceleration / 100}`} center={`${width / 200},${-height / 200},0`} > <transform is="transform" rotation={`1 0 0 ${yAcceleration / 100}`} center={`${width / 200},${-height / 200},0`} > <group is="group"> { // the rest of the labyrinth } </group> </tansform> <transform>
Here I needed two
<transform> tags to apply the x and y rotation.
Conclusion
I was surprised to be able to render the full wooden labyrinth in 3D in under a day - and in less than 200 lines of code. I loved the declarative approach of x3dom. It really makes 3D rendering much simpler in my opinion: describe what you want and let the browser do the rendering job. It's the same approach as react-three-fiber, which uses threejs under the hood. I can't wait for x3dom to become an actual standard.
The complete code to display the labyrinth game in 3d is available on GitHub. Feel free to test it, and please give me your feedback! | https://marmelab.com/blog/2020/10/16/into-the-labyrinth-with-x3dom.html | CC-MAIN-2022-27 | refinedweb | 1,731 | 56.25 |
Contents tagged with .NET
Review of Excellent Book: Linq in Action
.
Do .NET 2.0 SP1 Binaries Fail Without SP1?:.
Function to Load Enum-Typed Properties from Database
Here's a nice library function useful when loading enum-typed properties from your database:
public static T ToEnum<T>(int typeValue) {
return (T)Enum.ToObject(typeof(T), typeValue);
}
Garbage Collection Information -- Must Read for .NET Devs
Probably one of the best information sources about .net garbage collection:.
Atlanta Cutting Edge .NET User Group Meeting
The Atlanta Cutting Edge .NET User Group is meeting Monday, March 5, 2007, at 6:00pm in the Microsoft offices in Alpharetta. Paul Lockwood will be talking about advanced production debugging and Eric Engler will be talking about the ASP.NET AJAX framework. Eric promises it will be about much more than the UpdatePanel, which seems to be the extent of most such talks.
LINQ to SQL "Real" Example App Available
The Atlanta Code Camp was today, so I finally got to give my LINQ and O/R Mapping talk that I've been preparing.
I tried to have minimal slides so that I could do a deep dive into real code, but I still went a little too long. The slides look great on my own PC, and in fact they're mostly some I stole straight from other LINQ presentions. But the overhead I was using made the text nearly unreadable for some reason, which made me take longer on the slides. It also made some of the standard VS color syntax unreadable, with the work-around being to select that code. I small the same problem with another speaker in the same room, so I guess it was the projector, but very frustrating.
In the end I still got to hopefully show a fair amount of LINQ to SQL, but I had really hoped to show more. I also made sure I gave a glimpse at SqlMetal and LINQ to Entities, but both of those were meant to be just glimpses. Finally, I briefly demoed my new "real" example application written with LINQ to SQL which is included in my download. This example shows off my own POCO objects with an external XML Mapping file, instead of the ugly code gen with attributes. Its also a "real" app that consumes the LINQ to SQL with WinForms grids, drop-down filtering, and create, update, and delete.
Note that it assumes the May 2006 CTP, but I'll update it to the next one when it comes out, hopefully next month. Its also nearly identical to my existing "real" example app downloads that I have for my own ORMapper and NHibernate.
Breaking News: Future Version of .NET Framework to Run on the Mac
Atlanta Code Camp 2007 Registration is Open
Registration for Atlanta Code Camp 2007 on January 20th is now open. Space is limited and fills up fast, so do NOT delay registering -- it's free. Thanks to Jim Wooley for putting this together this year.
I'll be presenting a session titled "Linq and O/R Mapping" that will be lots of real code and very little powerpoint. If you've seen the standard Linq sessions already, or even if not, but you've been wanting more then this is for you. I'm not going to waste any time on Linq to Objects or Xml, although those are cool in their right -- I will focus purely on Linq to Sql, and to a lesser extend Linq to Entities or Datasets. Do you want to see a real application built using Linq to Sql? That's what I plan to do, and I'll do it several ways so you can experience the possibilities. For instance, should we use SqlMetal, the GUI Designer, or do our own thing with xml mappings instead of attributes? What if you want to include some relationships, use some stored procs, and even some inheritance? We shall cover all of those possibilities and more -- you will NOT be disappointed since this will not be just another slide deck or sample series based on what's already available. In fact, I would actually challenge you to find any other "real" sample that includes all of these with xml mappings, but you won't find it since it doesn't exist. I hope you get that I'm excited about this, as these technologies have definitely matured past my initial criticisms. And even if you can't make it for some reason, I'll post at least some version of my sample app after the event is over for all to see.
VS 2005 Service Pack 1 Available -- Go Get It Now
If you haven't heard it already, VS 2005 Service Pack 1 is out and can be downloaded here. It contains over 2200 bug fixes according to Scott Guthrie, as well as making Web Application Projects standard once again. Also according to Scott, the install time can vary significantly depending on what you have installed, and is especially very long if you have C++ installed. My own experience was that it took about an hour to install on my system, although that actually involved what I can only describe as two 1/2 hour installs. Yes, maybe it was a fluke due to something on my system, but it installed once and said it was done, and then kept going with another install, including the exact same couple of dialogs, before finally asking to reboot. Maybe your experience will be different, but in the end I suppose what matters the most is that our VS 2005 experience will now be improved every day. | http://weblogs.asp.net/pwilson/Tags/.NET | CC-MAIN-2015-48 | refinedweb | 944 | 68.7 |
Estimates spin-image descriptors in the given input points. More...
#include <pcl/features/spin_image.h>
Estimates spin-image descriptors in the given input points.
This class represents spin image descriptor. Spin image is a histogram of point locations summed along the bins of the image. A 2D accumulator indexed by a and b is created. Next, the coordinates (a, b) are computed for a vertex in the surface mesh that is within the support of the spin image (explained below). The bin indexed by (a, b) in the accumulator is then incremented; bilinear interpolation is used to smooth the contribution of the vertex. This procedure is repeated for all vertices within the support of the spin image. The resulting accumulator can be thought of as an image; dark areas in the image correspond to bins that contain many projected points. As long as the size of the bins in the accumulator is greater than the median distance between vertices in the mesh (the definition of mesh resolution), the position of individual vertices will be averaged out during spin image generation.
With the default paramters, pcl::Histogram<153> is a good choice for PointOutT. Of course the dimension of this descriptor must change to match the number of bins set by the parameters.
For further information please see:
The class also implements radial spin images and spin-images in angular domain (or both).
Definition at line 88 of file spin_image.h.
Definition at line 92 of file spin_image.h.
Definition at line 108 of file spin_image.h.
Definition at line 110 of file spin_image.h.
Definition at line 109 of file spin_image.h.
Definition at line 104 of file spin_image.h.
Definition at line 106 of file spin_image.h.
Definition at line 105 of file spin_image.h.
Definition at line 102 of file spin_image.h.
Definition at line 91 of file spin_image.h.
Constructs empty spin image estimator.
Definition at line 54 of file spin_image.hpp.
References pcl::Feature< PointInT, PointOutT >::feature_name_.
Empty destructor.
Definition at line 126 of file spin_image.h.
Estimate the Spin Image descriptors at a set of points given by setInputWithNormals() using the surface in setSearchSurfaceWithNormals() and the spatial locator.
Implements pcl::Feature< PointInT, PointOutT >.
Definition at line 324 of file spin_image.hpp.
References pcl::PointCloud< T >::points.
Computes a spin-image for the point of the scan.
Definition at line 69 of file spin_image.hpp.
initializes computations specific to spin-image.
Reimplemented from pcl::Feature< PointInT, PointOutT >.
Definition at line 239 of file spin_image.hpp.
References pcl::Feature< PointInT, PointOutT >::deinitCompute().
Sets/unsets flag for angular spin-image domain.
Angular spin-image differs from the vanilla one in the way that not the points are collected in the bins but the angles between their normals and the normal to the reference point. For further information please see Endres, F., Plagemann, C., Stachniss, C., & Burgard, W. (2009). Unsupervised Discovery of Object Classes from Range Data using Latent Dirichlet Allocation. In Robotics: Science and Systems. Seattle, USA.
Definition at line 231 of file spin_image.h.
Sets spin-image resolution.
Definition at line 133 of file spin_image.h.
Provide a pointer to the input dataset that contains the point normals of the input XYZ dataset given by setInputCloud.
Definition at line 178 of file spin_image.h.
Sets array of vectors as rotation axes for input points.
Useful e.g. when one wants to use tangents instead of normals as rotation axes
Definition at line 203 of file spin_image.h.
Sets minimal points count for spin image computation.
Definition at line 162 of file spin_image.h.
Sets/unsets flag for radial spin-image structure.
Instead of rectangular coordinate system for reference frame polar coordinates are used. Binning is done depending on the distance and inclination angle from the reference point
Definition at line 241 of file spin_image.h.
Sets single vector a rotation axis for all input points.
It could be useful e.g. when the vertical axis is known.
Definition at line 189 of file spin_image.h.
Sets the maximum angle for the point normal to get to support region.
Definition at line 145 of file spin_image.h.
Sets input normals as rotation axes (default setting).
Definition at line 213 of file spin_image.h. | http://docs.pointclouds.org/1.7.1/classpcl_1_1_spin_image_estimation.html | CC-MAIN-2019-47 | refinedweb | 705 | 52.26 |
TrakEM2
TrakEM2 is an ImageJ plugin for morphological data mining, three-dimensional modeling and image stitching, registration, editing and annotation.
See TrakEM2 snapshots for an overview.
Contents
- 1 Features
- 2 TrakEM2 in Fiji
- 3 Documentation
- 4 Running fiji for heavy-duty, memory-intensive, high-performance TrakEM2 tasks
- 5 Preparing TrakEM2 for best performance
- 6 How much RAM should I allocate to the JVM for Fiji to run TrakEM2?
- 7 Examples
Features
- Segmentation: manually draw areas across stacks, and sketch structures with balls and pipes. Skeletonize entire neuronal arborizations and represent synapses with relational connector objects.
-.
- Writing plugins.
Preparing TrakEM2 for best performance
For fastest browsing through layers
Right-click on the canvas and choose "Display - Properties...". Then make sure that:
- "snapshots mode" is set to "Disabled", or at most to "Outlines".
- "Prepaint" is not checked, so that it is disabled.
For importing large collections of images and editing them immediately afterwards
The goal is to avoid generating mipmaps multiple times, which may be very time consuming.
Right-click on the canvas and choose "Display - Properties...". Then make sure that:
- "enable mipmaps" is not checked, so that it is disabled.
Beware that you will not be able to browse quickly through layers while importing, given that mipmaps will not be generated.
Now to correct the contrast, first re-enable mipmaps by going again to "Display - Properties..." and checking the "enable mipmaps" checkbox. Then you have two general (non-exclusive) options:
A. Use the built-in commands from the right-click menu, such as:
- "Adjust images - Enhance contrast layer-wise"
- "Adjust images - Set min and max layer-wise"
B. Create a preprocessor script and set it to all images. For example, a beanshell script to run CLAHE on each image. In the script, the patch and imp variables exist automatically, and represent the Patch instance and the ImagePlus instance that the Patch wraps, respectively.
import ij.IJ; IJ.run(imp, "Enhance Local Contrast (CLAHE)", "blocksize=127" + " histogram=256 maximum=3 mask=*None* fast_(less_accurate)");
To set the script to all images, save the above to a file named "whatever.bsh" (notice the filename extension ".bsh") and then right-click on the TrakEM2 canvas and choose "Script - Set preprocessor script layer-wise", and choose the whole range of layers. This will set the script to every image of every layer, and trigger mipmap regeneration for every image. When TrakEM2 loads the image, the script will run on the image before TrakEM2 ever sees its contents.
The preprocessor script gives you maximum power: do whatever you want with the image. For example, normalize the image relative to a known good mean and standard deviation for your data set.
For regenerating mipmaps the fastest possible
The default generation of mipmaps is done with are averaging, and is pretty fast. Still, you may want to consider parallelizing it: go to "Project - Properties...", and set the mipmap threads to the number of cores in your machine, for example 12.
Stop reading if you are satisfied with the default quality of scaled images in TrakEM2.
If you choose to generate mipmaps using Gaussians, go to "Project - Properties...", and set the mipmaps mode to "Gaussian". Then, you must take care of the following:
In TrakEM2 0.9a and later, the mipmaps machinery can use a multi-threaded Gaussian implementation now present in the latest ImageJ. This means that now there are two sets of threads:
- The set of threads, where each thread regenerates the mipmap pyramid of a single image.
- The set of threads that performs Gaussian blurring for downsampling, for each scaling iteration in the generation of the mipmap pyramid.
If your machine has 12 cores, the default settings will use 1 thread for mipmaps and 12 threads for gaussian blurring. This may not fit your data properties: you may end up waiting long times for mipmap generation if your images are small.
Two strategies are possible for accelerating Gaussian-based generation of mipmaps:
- Strategy A: your data consists of large images (over 4000x4000). Right-click on the TrakEM2 display and choose "Project - Properties...", and set the mipmap threads to 1 (the default). Now, mipmaps will be regenerated for one single image at a time, using 12 threads (given 12 cores) for computing the Gaussians.
- Strategy B: your data consists of small images (smaller than 4000x4000). Go to the Fiji window and select "Edit - Options - Memory & Threads...", and set the number of threads to 1. Then, go to "Project - Properties...", and set the mipmap threads to 12. Now, mipmaps will be regenerated for 12 images at a time (given 12 cores), using a single thread for each to compute the Gaussians.
Use strategy A as well if your computer has little RAM, or if access to the images is slow and contentious (such as if the data lives in a USB hard drive). That's why the default is one single thread for generating mipmaps.
If you change the method for generating mipmaps to a non-Gaussian method, the above situation does not occur. Set the number of threads for regenerating mipmaps to the number of cores, or less if your computer doesn't have much RAM.
How much RAM should I allocate to the JVM for Fiji to run TrakEM2?
Use a computer that follows this rule of thumb: take the largest single 2D image in your dataset, then multiply its size by 10, and make sure that every core of your CPU has at least that much RAM available to it.
For example, for a 4096x4096 16-bit image you will need at least 335 Mb per core, so at least 5.4 Gb of RAM for 16 cores. 8 Gb would likely work better. 32 Gb will be a pleasure to use.
As for a graphics card buy the largest you can afford, both in computing power and in internal memory.
Examples
| https://imagej.net/index.php?title=TrakEM2&oldid=12408 | CC-MAIN-2019-35 | refinedweb | 977 | 63.7 |
This C++ Program demonstrates implementation of Set_Union in STL.
Here is source code of the C++ Program to demonstrate Set_Union in STL. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Implement Set_Union in Stl
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10);
vector<int>::iterator it;
sort (first, first + 5);
sort (second, second + 5);
it = set_union (first, first + 5, second, second + 5, v.begin());
v.resize(it - v.begin());
cout << "The union has " << (v.size()) << " elements: "<<endl;
for (it = v.begin(); it != v.end(); ++it)
cout<< *it<<" ";
cout <<endl;
return 0;
}
$ g++ set_union.cpp $ a.out The union has 8 elements: 5 10 15 20 25 30 40 50 ------------------ (program exited with code: 0) Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs. | http://www.sanfoundry.com/cpp-program-implement-set-union-stl/ | CC-MAIN-2018-09 | refinedweb | 175 | 64.3 |
One of the biggest steps after learning how to program devices and sensors with Arduino is to make your device “Internet Enabled.”
That way if you want to create a custom prototype with network capabilities, you can collect and publish data from the cloud, your home, and practically anywhere.
WiFi connectivity is also important if you want to add voice control, like Siri, to an Arduino device.
In this article, I’ll show you the steps to connect an ESP8266 controller to WiFi so that you can add Internet connectivity to custom prototypes.
Connect the ESP8266 to the Internet
This tutorial is intended for more Intermediate learners. We won’t be covering the basics of Arduino in this tutorial.
If you don’t have a foundation in electronics, coding, and Arduino, I recommend taking a look at my Arduino for Beginners course and learning those skills first.
However, if you’ve already built a project using the ESP8266 and can’t quite get it “online” for monitoring or cloud access, then this tutorial will guide you through that process.
Hardware You’ll Need
You’ll need some basic hardware for this project. I recommend using the Wemos D1 Mini or NodeMCU as your WiFi-enabled chip.
The Arduino Kit and Sensors are optional. We won’t get into specifics on how to wire a circuit or publish and collect data from the Internet in this article.
However, we have an online Special Topics Robotics Course that covers these topics in more detail. You can sign up for that course, here.
The purpose of this tutorial is to show you the three steps on how to take an Arduino controller and get it connected to your home network (and WWW) so that you can use it as an IoT device.
We won’t cover how to add the ESP8266 to the Boards Manager or basic configuration in this tutorial. If you haven’t programmed an ESP8266 (NodeMCU or Wemos D1 Mini) then I recommend checking out our getting started guide before reading this tutorial.
Step 1. Setup the Arduino IDE for ESP8266
First, use the Arduino Board Manager to configure the ESP8266. More detailed instructions are available below:
Once you have the board configured, include the ESP8266WiFi header.
#include <ESP8266WiFi.h>
Next, create two global variables to store your network SSID and password. This is your WiFi Network’s name and password, respectively.
/*ADD YOUR PASSWORD BELOW*/ const char *ssid = SECRET_SSID; const char *password = SECRET_PASS;
For example, if I wanted to connect to the network, LearnRoboticsWIFI and the password is RoboticsR0ck$ (not real btw), then you’d write the following lines:
/*ADD YOUR PASSWORD BELOW*/ const char *ssid = LearnRoboticsWIFI; const char *password = RoboticsR0ck$;
Then, initialize a WiFiClient called client.
WiFiClient client;
Now that we have our globals taken care of, we can write a method that connects the controller to the WiFi network we defined using the SSID and password above.
Step 2. Connect the ESP8266 to your WiFi Network (SSID)
The next step is to create a
connectToWiFi() method. We can use the Serial Monitor to print out messages as we attempt to connect to our WiFi Network.
/* * Connect your controller to WiFi */ void connectToWiFi() { //Connect to WiFi Network Serial.println(); Serial.println(); Serial.print("Connecting to WiFi"); Serial.println("..."); WiFi.begin(ssid, password); int retries = 0; while ((WiFi.status() != WL_CONNECTED) && (retries < 15)) { retries++; delay(500); Serial.print("."); } if (retries > 14) { Serial.println(F("WiFi connection FAILED")); } if (WiFi.status() == WL_CONNECTED) { Serial.println(F("WiFi connected!")); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } Serial.println(F("Setup ready")); }
This code will try to connect to the network 15 times. If it can’t connect, then it will fail and print out a failure message in the Serial Monitor.
Otherwise, you’ll see that the controller is connected.
After the method is written, don’t forget to call it within your setup() routine. We only want to run the
connectToWiFi() method once.
/* * call connectToWifi() in setup() */ void setup(){ //...other setup code here... connectToWiFi(); }
And that’s it! Once you have this code added to your sketch, you can test it out.
BECOME A LEARN ROBOTICS INSIDER!
Give me 1 week in your inbox, and I'll send you my best technical tips to help you build robots!
You have Successfully Subscribed!
Step 3. Test the ESP8266 Network WiFi Connection
Before testing this program, ensure that you’ve added the correct network SSID (name) and password.
Then, upload your full sketch (with the WiFi connection code from Steps 1 and 2) to your ESP8266.
Next, open the Serial Monitor and watch the initialization happen. You should see a few lines that say “Connecting to WiFi.”
The controller will attempt to connect 15 times. If it fails, you’ll see the message “WiFi connection FAILED.”
Ideally, you’ll see a series of messages print out on the Serial Monitor:
- “WiFi connected!”
- “IP address: ” plus the assigned IP address from your router
- and “Setup ready”
Once you see the “Setup ready” message, you’re ready to start using your ESP8266 on WiFi. You can also access (or ping) your device at the IP address that it was assigned from the router.
What can you do with a WiFi-enabled Arduino?
The best part about connecting an ESP8266 to WiFi is that you can now use these projects on your internal (home) network or send data to a cloud service.
This is useful for remotely monitoring sensors or devices, making IoT projects, and for custom home automation systems.
After you add your ESP8266 to the internet, the possibilities on what you can build, track, and create, become endless.
Looking for Arduino projects to make?
Here are some of our most popular IoT projects you can try:
- Bored? Here are 17 Internet of Things Project Ideas
- Home Automation Ideas (You can do today)
- Home Automation using Google Assistant & ESP8266
- Control iRobot Roomba with Siri (Tutorial)
- Add Voice Control to Arduino Projects using Siri
If you enjoyed this article, please share it with a friend! You can also support our online publication when you buy. | https://www.learnrobotics.org/blog/connect-esp8266-wifi/ | CC-MAIN-2020-40 | refinedweb | 1,019 | 64.1 |
In character recognition, the distance between two edges of a stroke, measured perpendicular to the stroke centerline is called the stroke width. Take a look at the below image. The length of lines marked in Red gives the stroke width of the character.
There are quite a few ways to identify the stroke width, In this article I will talk about the one based on distance transform. Distance transform when applied to a binary image gives us an image where each pixel represents it’s distance from the nearest 0 value pixel.
As you can visually calculate, the stroke width in case of the above image is 6. The value at the center in the DT image is 3 that’s because the pixel is 3 units away from the closest 0 value pixel. So we can conclude that given a binary image, the stroke width is the mean of center pixels multipied by 2. And now to find the center pixels we can skeletonize the image which will give use a boolean mask with center pixles marked as True.
Once we have boolean mask, we can easily pick the values of center pixels from the DT image. Python code that does all of this is given below:
from skimage.io import imread from skimage.color import rgb2gray from skimage.filters import threshold_otsu from scipy.ndimage.morphology import distance_transform_edt from skimage.morphology import skeletonize import numpy as np # load the image img = imread("") # convert the image to grayscale gray = rgb2gray(img) # thresholding the image to binary threshold = threshold_otsu(gray) binary_image = gray > threshold # add some padding to the image to # avoid wrong distance calculations for corner pixels padded_image = np.pad(binary_image, 2) # find the distance transform distances = distance_transform_edt(padded_image) # skeletonize the image to find the center pixels skeleton = skeletonize(padded_image) # find the center pixel distances center_pixel_distances = distances[skeleton] # get the stroke width, twice the average of center pixel distances stroke_width = np.mean(center_pixel_distances) * 2 print(stroke_width) # show the image plt.figure(figsize=(10,10)) plt.imshow(padded_image, cmap="gray")
References: | https://muthu.co/stroke-width-identification-algorithm-for-text-like-regions/ | CC-MAIN-2020-40 | refinedweb | 339 | 54.73 |
How to query Web3.Storage
In this how-to guide, you'll learn how to query Web3.Storage for information about your files.
When you store a file with Web3.Storage, you receive a content identifier (CID) that you can use to retrieve the file. However, this CID can also be used to query the service for more details about how the data is stored on the decentralized storage networks that Web3.Storage uses under the hood.
This guide will show you how to use Web3.Storage's JavaScript client library or Go client library to get information about content stored on the network. To follow along, you'll need the API token from your Web3.Storage account. If you already have an account and a token, read on. If not, have a look at the quickstart guide to get up and running in just a few minutes for free.
Installing the client
- JavaScript
- Go
In your JavaScript project, add the
web3.storage package to your dependencies:
npm install web3.storage
In your Go project, add the client package to your dependencies using
go get:
go get github.com/web3-storage/go-w3s-client
Creating a client instance
- JavaScript
- Go
To create a
Web3Storage client object, we need to pass an access token into the constructor:
import { Web3Storage } from 'web3.storage' function getAccessToken () { // If you're just testing, you can paste in a token // and uncomment the following line: // return 'paste-your-token-here' // In a real app, it's better to read an access token from an // environement variable or other configuration that's kept outside of // your code base. For this to work, you need to set the // WEB3STORAGE_TOKEN environment variable before you run your code. return process.env.WEB3STORAGE_TOKEN } function makeStorageClient () { return new Web3Storage({ token: getAccessToken() }) }
Tip
Don't have an access token? Get your Web3.Storage API token in just a few minutes using the instructions in the quickstart guide.
First, make sure to import the client
w3s package:
import "github.com/web3-storage/go-w3s-client"
You can create a client instance with the [
NewClient function][reference-go-newclient], passing in an API token using the [
WithToken option][reference-go-withtoken]:
token := "<AUTH_TOKEN_GOES_HERE>" client, err := w3s.NewClient(w3s.WithToken(token))
Querying for status information
- JavaScript
- Go
The client object's
status method accepts a CID string and returns a JSON object with information about the upload. Here's how to include it in your project:
async function checkStatus (cid) { const client = makeStorageClient() const status = await client.status(cid) console.log(status) if (status) { // your code to do something fun with the status info here } } // replace with your own CID to see info about your uploads! checkStatus('bafybeifljln6rmvrdqu7xopiwk2bykwa25onxnvjsmlp3xdiii3opgg2gq')
IMPORTANT
Remember to check the return value! If you ask for the status of a CID that Web3.Storage doesn't know about, the
status method will return
undefined instead of a status object. Make sure to check that a return value exists before trying to use it, as we're doing above with the
if (status) conditional statement.
If the given CID is valid and has been uploaded to Web3.Storage, the
status method will return an object that looks similar to this:
{ "cid": "bafybeiepdjmu7bkau2sv5hag4m76jyt747d4do6kenhedpvd24kcc2zq7u", "created": "2021-08-24T21:35:31.988241Z", "dagSize": 15393, "pins": [ { "status": "Pinned", "updated": "2021-08-24T21:39:40.586057Z", "peerId": "12D3KooWMbibcXHwkSjgV7VZ8TMfDKi6pZvmi97P83ZwHm9LEsvV", "peerName": "web3-storage-dc13", "region": "US-DC" }, { "status": "Pinned", "updated": "2021-08-24T21:39:40.586057Z", "peerId": "12D3KooWF6uxxqZf4sXpQEbNE4BfbVJWAKWrFSKamxmWm4E9vyzd", "peerName": "web3-storage-am6", "region": "NL" }, { "status": "Pinned", "updated": "2021-08-24T21:39:40.586057Z", "peerId": "12D3KooWLWFUri36dmTkki6o9PwfQNwGb2gsHuKD5FdcwzCXYnwc", "peerName": "web3-storage-am6-2", "region": "NL" } ], "deals": [ { "dealId": 2332952, "storageProvider": "f022142", 13:00:30Z", "created": "2021-08-25T00:17:10.392875Z", "updated": "2021-08-25T07:57:26.999531Z" }, { "dealId": 2333120, "storageProvider": "f022352", 14:50:30Z", "created": "2021-08-25T01:00:28.410557Z", "updated": "2021-08-25T07:57:26.307022Z" }, { "dealId": 2333678, "storageProvider": "f01278", "status": "Published", -26T23:37:30Z", "created": "2021-08-25T03:02:14.998793Z", "updated": "2021-08-25T07:57:26.639659Z" } ] }
What do all those fields mean? Here's a summary:
cidcontains the same CID that was passed into the
statusmethod, so you don't have to keep track of which response goes with which request.
createdcontains an ISO-8601 datetime string indicating when the content was first uploaded to Web3.Storage.
dagSizecontains the size in bytes of the Directed Acyclic Graph (DAG) that contains all the uploaded content. This is the size of the data that is transferred over the network to Web3.Storage during upload, and is slightly larger than the total size of the files on disk.
pinscontains an array of objects describing the IPFS nodes that have pinned the data, making it available for fast retrieval using the IPFS network.
dealscontains an array of objects describing the Filecoin storage providers that have made storage deals. These storage providers have committed to storing the data for an agreed period of time. Note that it may take up to 48 hours after uploading data to Web3.Storage before Filecoin deals are activated.
For more details about the fields in this JSON response, including the format of the
pins and
deals objects, see the JavaScript client library reference.
Tip
If you're looking for info on files you've uploaded, you can also use the Files page on Web3.Storage to see the values for some of the more commonly-used attributes returned by
query(), namely
created,
cid,
dagSize, and the
status and
deals objects of
pins.
The Go client's
Client interface defines a
Status method that accepts a
context.Context and a
Cid from the
go-cid library.
The example below accepts a CID string and converts it to a
Cid using
cid.Parse. If your codebase is already using the
Cid type, you may not need this step.
func getStatusForCidString(client w3s.Client, cidString string) error { c, err := cid.Parse(cidString) if err != nil { return err } s, err := client.Status(context.Background(), c) if err != nil { return err } fmt.Printf("Status: %+v", s) return nil }
Next steps
If you haven't yet explored in depth how to store data using Web3.Storage, check out the storage how-to guide for a deep dive on how to upload files using the client libraries.
To learn in greater detail how to fetch your data using the Web3.Storage client, or directly from IPFS using a gateway or the IPFS command line, see the how-to guide on retrieval. | https://web3.storage/docs/how-tos/query/ | CC-MAIN-2022-40 | refinedweb | 1,076 | 57.87 |
« Return to documentation listing
#include <mpi.h>
int MPI_Comm_idup(MPI_Comm comm, MPI_Comm *newcomm, MPI_Request *request)
INCLUDE ’mpif.h’
MPI_COMM_IDUP(COMM, NEWCOMM, REQUEST, IERROR)
INTEGER COMM, NEWCOMM, REQUEST, IERROR
The completion of a communicator
duplication request can be determined by calling any of MPI_Wait, MPI_Waitany,
MPI_Test, or MPI_Testany with the request returned by this function.
This call applies to both intra-
and intercommunicators.
Note that it is not defined by the MPI standard
what happens if the attribute copy callback invokes other MPI functions.
In Open MPI, it is not valid for attribute copy callbacks (or any of their
children) to add or delete attributes on the same object on which the attribute
copy callback is being | https://www.open-mpi.org/doc/current/man3/MPI_Comm_idup.3.php | CC-MAIN-2015-22 | refinedweb | 116 | 52.49 |
mount_udf — mount
a UDF filesystem
The
mount_udf command attaches a UDF
filesystem (typically found on a DVD) residing on the device
special to the global filesystem namespace at the
location indicated by node. The filesystem is always
mounted readonly. This command is invoked by
mount(8) when using the
syntax
mount[options] -t udf special node
The options are as follows:
-ooptions
-oflag followed by a comma separated string of options. See the mount(8) man page for possible options and their meanings.
mount(2), fstab(5), mount(8), umount(8), vnconfig(8)
UDF support first appeared in FreeBSD 5.0, and was then ported to OpenBSD 3.8.
Scott Long <scottl@freebsd.org> did the original work; Pedro Martelletto <pedro@openbsd.org> adapted it to OpenBSD. | https://man.openbsd.org/OpenBSD-6.4/mount_udf.8 | CC-MAIN-2022-21 | refinedweb | 127 | 58.69 |
Hey guys. I'm trying to make a class called "purse" where I make an array list and store String in it (quarters, dimes, etc), and then I print out the names of each coin I stored in the purse. I got the printing out part just fine. Then I have to make a method where I reverse the order of the names and prints them out as well. I think I got this one right until I print them out and notice that I get an error in the output. This is the "reverse" method. Could anyone tell me what I'm doing wrong here?
Code :
import java.util.ArrayList; public class Purse { private ArrayList<String> coins; private ArrayList<String> reverseArray; public Purse() { ArrayList<String> coin = new ArrayList<String>(); coins = coin; } public void addCoin(String coinName) { coins.add(coinName); } public String reverse() { int n = coins.size(); for(int i = n; i == 0; i--) { String s = coins.get(n); reverseArray.add(s); } String reverseWords = reverseArray.toString(); return reverseWords; } public String toString() { String words = coins.toString(); return words; } }
Code :
public class PurseTester { public static void main(String[] args) { Purse jean = new Purse(); jean.addCoin("Quarter"); jean.addCoin("Dime"); jean.addCoin("Nickel"); jean.addCoin("Dime"); System.out.println(jean.toString()); System.out.println(jean.reverse()); } }
Output:
Quote:
[Quarter, Dime, Nickel, Dime]
Exception in thread "main" java.lang.NullPointerException
at Purse.reverse(Purse.java:27)
at PurseTester.main(PurseTester.java:12) | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/18940-reverse-order-strings-arraylist-printingthethread.html | CC-MAIN-2013-20 | refinedweb | 238 | 67.76 |
On Tue, Feb 07, 2006 at 07:59:46PM -0800, Ashley Yakeley wrote: > John. I assume you mean: > foo = return id >>= (\i -> return (i 7)) Yup. and this is just fine since Int is an instance of Eq. this should typecheck and does. foo is a completly generic function on any monad, the particular instance for 'Set' places the extra restriction that sets argument must be Eq. this need not be expressed in foo's type because it is polymorphic over all monads, however as soon as you instantiate foo to the concrete type of 'Set a' for any a, the Eq constraint is checked and in the dictionary passing scheme, the appropriate dictionary is constructed and passed to foo. it is important to realize that dictionaries are unchanged with this translation. a Monad dictionary is a monad dictionary whether it depends on an Eq instance (because it is an instance of a restricted data type) or not. 'foo' expects a monad dictionary just like any other, that said dictionary is created partially from Ints Eq instance is immaterial. John -- John Meacham - ⑆repetae.net⑆john⑈ | http://www.haskell.org/pipermail/haskell-prime/2006-February/000491.html | CC-MAIN-2014-42 | refinedweb | 185 | 61.67 |
Fringe benefits of the smoking ban
After confidently asserting to a colleague yesterday that it would be a "dry crisp night for cycling" I walked out to the cycle lockers in a thin drizzle. "Well," I thought, "at least it's not snowing."
As I left the woods near Lake Guillemont it began to sleet steadily and I lost contact with my finger ends. I got these back some miles later by making alternate fists on the handle bars as I went along (old trick). Then the sleet became heavy rain and in the darkest part of my journey, about eleven miles out, I heard a rhythmical tsk tsk tsk from the rear wheel as it began jetting its precious cargo of compressed air into the surface water.
It was flat inside a minute. This is the closest I have come to calling for backup on one of these commutes and I had this strongly in mind as I carried the bike to the nearest easily recognizable junction. But just then a pub came into view. And, of course, like most pubs these days it had a large, well lit awning outside for the use of those who are conscientiously hardening their lungs against the possibility of environmental catastrophe in the shape of huge tobacco volcanoes.
So I snuck in right under that welcome protection - it even had heating! - and started fishing out my spare inners. From time to time an old buffer would emerge from the pub for a bit of lung-hardening and give a sort of running commentary on my progress. "Ah! I see you've partially inflated (puff) the inner tube (wheeze gasp) - I don't do that. Mind you I ride a Vincent Rapide 500cc... (wistful sigh)." In my haste to get home I bust the first inner with a tyre lever - never done that before... So I put the second one on with thumbs only. "Ah! I see you've set the tyre without the use of levers (pant). Make sure you wash your hands before you leave (long drag) as dirt inside the gloves may compromise their thermal properties..."
On some more clement evening I may stop off their for a pint. But as I pulled away last night it began at last to snow heavily and I lost contact with my finger ends again. But it has been a useful lesson. Even out of season, pub patios can join the list of impromptu repair shops for waylaid cyclists.
Posted at
10:32AM Oct 29, 2008
by John Alderson in Get on yer Bike |
Blowing off steam
The sins of my "reputable local builder":
Well, that feels better!
Posted at
02:05PM Sep 09, 2008
by John Alderson in Life, Jim... |
In The Badlands
Disclaimer
I went for a walk around the lake this afternoon, to rest my eyes after accidentally pointing them at a perl program. Throughout I was observed by the heron, who seems rather fat and complacent these days. The water was conspicuously devoid of fish.
Because that hadn't taken long I pushed on into the undergrowth behind the Lake. I began to feel strangely exposed and self-conscious. Apart from a couple of people on the canteen patio, sipping cappuccinos and poring over spreadsheets, I was quite alone. I think I began to imagine my colleagues congregating invisibly behind the huge office plate-glass windows, which reflected only sky in my direction. They would be murmuring to each other "What is he doing?" - "He has reached the birch copse!" - "Does he have enough oxygen to make it back safely?".
They would perhaps speculate that I was on some obscure mission - possibly religious. Maybe I was burying the secret of how to write a complete webserver in three lines of awk, for a future in which people would once again revere such things. When I finally disappeared from view they would disperse again to today's hot desks with furrowed brows and an inkling of disquiet.
What I did discover in the dark continent between the Lake and the Lost City of Building 4 was a very good blackberry bush. It always seems to be the smaller blackberries on the harder-to-reach bushes which taste the best.
Posted at
01:12AM Aug 13, 2008
by John Alderson in Lake Guillemont |
Robo-Cropper
How many accidents are caused, or made worse, by a mis-ordered unconscious list of priorities?
You are standing on a new carpet in your neighbour's sitting room, holding a cup of hot coffee. Through the sitting room door you are horrified to see that an ambitious early toddler has managed to open a stairgate and is wobbling giddily on the top step of a long staircase. The right thing to do is to drop the coffee and skip up the stairs as fast as possible (mere shouting often destabilizes toddlers). But a significant minority of people will waste a precious half second attempting to put the coffee down carefully. Not spilling our drinks (especially if we are guests) is a habit of almost instinctive strength; overriding it takes conscious effort, or practice.
I've had a bad week for drivers (of both sexes) on four wheels attempting to run me over on my two. In today's sorry case I had made good eye contact with one bent on entering from a side road and I knew that she had seen me. But still she kept coming, so that I was pushed into the other lane (which, luckily, was empty) as she shouldered her way onto the road. I waved (in a manner of speaking) and was acknowledged. Then she continued - not especially quickly - on her way.
I've been pondering her state of mind at the point when she should have stopped but didn't and I think the story of the toddler on the staircase sheds some light on it. I don't think she bore me any ill will. I'd guess she was following the simple rule-of -thumb "don't get behind a cyclist". Probably she's never hit a cyclist but she's been miserably stuck behind one plenty of times. The weight of experience unconsciously favoured her trying to squeeze in front of me, before she had time to consciously evaluate the safety aspects. Avoiding a known minor hazard (the coffee / the delay) seems to take priority over an obscure major one (the fall / the collision).
So, in the spirit of The Off-Bike I propose "Robo-Cropper". The Off-Bike attempted to safely familiarize cyclists with ghastly mechanical mishaps by conditioning their reflexes. Robo-Cropper uses the same approach with motorists. Robo-Cropper is a convincing humanoid form (say, one of those crash test dummies but with lycra, nostrils, headgear and good hair) mounted on a semi-autonomous bicycle powered by a discreet motor in the dummy's torso and a novel hidden transmission through the saddle and seat-post.
An operator behind a hedge steers and brakes the bike by remote control. The dummy can give signals, turn its head and wail pitifully, but is otherwise passive and of good temperament.
The operator repeatedly sends robo-cropper across the same junctions at busy periods. Robo-cropper cycles responsibly but does not take evasive action and is eventually mown down by a driver with a mis-ordered set of unconscious priorities (or maybe just by a vindictive swine - which is less interesting...) The hope (wishful) is that the shock of believing (if only for a moment) that they have actually caused injury will initiate a rewiring of complacent safety reflexes in the driver's mind.
Obviously the more likely outcome is that all the cars will crash into each other leading to a national scandal similar to the one we'd get if some celebrity were injured exercising the more advanced options of the Off-Bike. Oh well...
Cycle safely and Noli nothis permittere te terere.
Posted at
03:33PM Jun 06, 2008
by John Alderson in Get on yer Bike |
Wrong Mystery Solved
Another team meeting:
The day Donna shredded the mysterious extra piece Risto was seen loitering around the printer area trying to look like someone who has been shocked or confused by something the photocopier has said. However, when no-one was looking he rummaged in the shredder bin. This had recently been emptied, so he was able to make a complete inventory of the surplus jigsaw piece we all thought we had seen the last of.
Such behaviour is already obsessive, but it turns out he has gone one huge step further by photographing and analyzing the many fragments in an attempt to reconstruct the whole piece and continue towards his original goal of determining if it is really surplus or has been displaced by some other more genuinely surplus piece. To this end he has ported some pattern recognition software to harness the formidable power of the SFW1000+8i and chosen our team meeting for a grand unveiling of the results...
We all cluster round the big screen and Algernon, halfway up his mountain, shades his eyes and squints at the portable LCD. Risto has the floor.
"I devised a q-parallel stochastic procedure to approximate best-fit," he says, "and converged using repeated runs of a classical genetic algorithm. This method could have been further optimized into q-space if the other 7 superposition engines were in the coherence group." He looks meaningfully at Donna, almost as if he suspects the fact that the best brains on the planet have not yet achieved 8-way q-bus superposition is all part of a global conspiracy to prevent verification of a true and complete Jackson Pollock jigsaw.
"Anyway, I'll show you the the final result. This is the definitive hi-resolution reconstruction of the query surplus piece. Further runs from this point do not improve signal to noise ratio at the interpolated-pixel level..."
"Just show us the goddamn picture Riz!" snaps Algernon, and Risto winces slightly.
It is a very high-quality image. We stare at it in admiration for a while; then someone says, "Ooh look, I can see a song thrush!"
"It's not a song thrush, it's a square dinnerplate with a pair of nail clippers in one corner."
"They're not nail clippers!"
"Is that David Beckham?"
"Hang on, hang on," says Arnie, "It's the wrong way round. Risto turn it 90 degrees clockwise. - - You see? There's the sky, and down here there's like a crowd of people. And that bit of dinner plate is the corner of a building. And here's a car with some guy waving."
"Oh yes! I see it now!"
"Amazing!" says Algernon, "That's John F. Kennedy in the car. And if I'm not mistaken the building behind is the Texas School Book Depository. Zoom in on the corner of the sixth floor."
We may have talked ourselves into this, but it does suddenly seem a highly detailed image. Zooming in on the corner window the shadowy figure of a man holding a bulky object becomes suddenly clear. There is a stupefied silence and then, moments later, pandemonium.
Some people were angry with Risto afterwards - but personally I don't think he was to blame. Of course, this may be another conspiracy, or another editorial lapse from the BBC, or it may be our first concrete glimpse of the dizzying weirdness of quantum reality - whatever. But according to the SFW1000's pattern recognition software the man standing at that fateful window was Terry Wogan, wearing a Pudsy Bear necktie and wielding a Spider Man 3 Super Soaker.
Posted at
11:00AM Aug 14, 2007
by John Alderson in Lake Guillemont |
Off-bike plugins
More training modules for the Off-bike.
Thanks are due to the helpful commentator who supplied the following suggestions:
These are all good - although I have passed them on to the simulator arm of the Off-bike Project (possibly to be coupled with the haptic jacket of VR fable).
Some I have thought of since, which could reasonably be added to the bike itself, are:
It would seem quite easy to build these in.
I was once startled by a truck driver who thought it was a neat idea to play the sound of a horse whinnying at extreme volume as he went past. I have a recurring fantasy of his trying this out on a real horse and pleading most pitiably with his insurance company after the horse has demolished his cab. (I didn't fall off but I failed to respond appropriately: i.e. to catch up long enough to read his licence plate).
I was once thrown off when my front tyre went bang while I was whizzing down a hill. I don't know if one can learn to cope with this as I have never repeated the experiment. I do now know that it is possible to bounce more than once on your knees...
Posted at
09:20AM Jul 24, 2007
by John Alderson in Get on yer Bike |
Fun with Webcams
The student interns are up to something. It's easy to tell because they haven't yet learned to control the smirking reflex. Cracking them was just a formality, although it was easy partly because I'm a cyclist.
The interns have taken agin the speed humps (sleeping policemen) which limit the speed of traffic around the lake. It's not that they have a perverse desire to increase the danger of our environment (at least, I hope not!) but more that they feel that push-bikes are disproportionately affected by these inverse pot-holes.
You'd think that as students they'd be hard-up but that doesn't seem to preclude owning some fairly high-tech bikes. They don't want to go down in a cloud of carbon nanotubes when their sleek machine buckles or tips negotiating the jump. Site Planning And Maintenance point out that the sidewalks are also for cycles. However, since July 1st in this land the sidewalks have become too dangerous, peopled as they are by glaze-eyed zombies hurrying to the smoking areas in the car-parks. These poor indigents only appear to have seen you. In reality they have paused mid-stride just to check (again) that they have everything they need, and will soon forge ahead without warning and on an unpredictable bearing.
Anyway, it turns out that the students' revenge is so inventive that it's worth describing in detail:
A couple of days ago they formed a sociable crowd around a lamp-post near one of the speed humps. While the outer students chatted the inner members of this crowd removed the maintenance plate from the lamp-post and inserted a small wireless PC, webcam and powerful integrated amp and speaker. This was all patched in to the lamp's power cable and the cover replaced with minor modifications for the camera and speaker (a few carefully positioned holes).
They contacted the PC from the office and checked that the camera images were good. Next a neural network was trained to recognize certain cars as they approached the hump. This job was facilitated enormously by Donna's SFW1000 which eats that kind of problem for breakfast. The student's included one of their own cars as a test and then tuned the tracking between visual match and arrival of the wheels at the hump.
The result is that when certain cars (and only those) traverse the hump the noise of a loud squeaky toy emanates from the lamp-post. Some of the resulting camera footage is absolutely classic. I would prise it away from the students but I think they are planning to sell it online to recover the funds they lost by buying smart bikes and mini wireless PCs.
In one sequence the victim stops, reverses and tries again. Again the squeak. He gets out of his car and waits for someone to go around him. No squeak. He scratches his head and inspects the tough plastic speed hump - and then actually begins to jump up and down on it to see if he can elicit the squeak! He gets in again and reverses with such violence that he nearly takes out a would-be smoker who has stopped briefly in the road to check his pockets. He drives forward again gingerly - squeak! - he stops and can still just be seen in the camera hunched over the wheel and staring wild-eyed from side to side before making for the nearest parking space.
With another victim we see the same reversing strategy, but then the guy gets out and starts rummaging in his boot (trunk - whatever). At length he pulls out a dog's squeaky bone toy and deposits it in the nearest bin.
I don't think this anarchy will achieve any useful result - but full marks for imagination!
Posted at
10:59AM Jul 23, 2007
by John Alderson in Lake Guillemont |
printf() - the immortal debugger
Caramba! Gone are the nights of "clubbin'" and the days of backchat and nose-powdering. In between hiding webcams in Project Central and stealing Ursula's entire library of O'Reillys Donna has succeeded in booting the SFW1000+8i! She is the first non-Sumover Futures employee to attain this level of magery. The engineers at Sumover wanted to send her a wee plaque in recognition but a "suit" intervened. The more credible this product looks the more snappy dressers with visitor's badges haunt the corridors.
True, she hasn't managed to entangle all 8 Superposition Engines for more than a picosecond yet but seems unperturbed by this and only smiles coyly when people inquire about her progress. In any case, even one working engine has Risto salivating. He limbered up with a couple of Travelling Salesman problems involving 100 cities and then launched into a project of his own. No-one knows what this is. Risto doesn't do "coy", he leans more towards the blunt end of things, with statements like "If I explained it to you you wouldn't understand anyway."
We have encountered new and fantastical difficulties when debugging quantum programs. Traditional debugging with breakpoints just won't work. There is an obvious and a less-obvious reason for this:
The obvious reason is that as soon as it hits a breakpoint the running program displays this fact on your terminal so that you can decide what to do next. This is equivalent to getting an eyeful of Schroedinger's Cat. The program will have gone irretrievably classical so there is no meaningful way it can be resumed.
So, you might say, at least we can do a post-mortem on the breakpointed program? Not necessarily... This brings us to the less-obvious problem: A breakpoint may sit on one of several code-paths and be missed by the others. In a classical program a breakpoint which is not visited has no effect on the execution of the program - but in a quantum program the mere possibility of visiting the breakpoint influences program execution even if the breakpoint is not visited.
In QM terms the breakpoint is a potential "observation". It's effect on a system even when the observation is not made is sometimes termed "counterfactual". I believe the idea of something which only might have happened influencing something that did was one of the paradoxes first raised by Einstein, Podolsky and Rosen in a thought experiment involving bomb fuses which could be triggered by a single photon.
So, anyway, trad breakpoints are a no-no. We've gone back to using printf() - but to a tiny qRAM filesystem which runs entangled with the program image. It's funny to think that messages may be written (sort of) to that filesystem which are no longer there when the burly programmer finally gets to look at the file. Still - our output is now coherent, even if not complete ;-)
We automated the initialisaton of the qRAM-FS:
/*
* Hello world - "Q-safe"
*/
#include <qstdio.h>
main()
{
fprintf(qstdout, "Hello, World!");
}
[NB: For anyone who feels in danger of losing the thread of Lake Guillemont a handy list of episodes is provided on the side-bar (most recent first)]
Posted at
04:11PM Jul 19, 2007
by John Alderson in Lake Guillemont |
The Missing Piece
Someone around here is one piece short of a jigsaw puzzle.
It is a curious fact of human nature that how we feel about a crime is not primarily dictated by the size of the injury - the amount stolen or the severity of the violence. When it comes to sentencing, size matters; but as social beings we are often swayed more by the motivations of the perpetrator and what the crime says about their trustworthiness, or simple worthiness.
So when we read about someone up on a charge of GBH for confronting a burglar with perhaps more than reasonable force our sympathies tend to go with the householder rather than the burglar - even though most people would rate violence as worse than theft. If I see someone deliberately drop an empty crisp packet on the street I'm emotionally ready to rescue the litter and incorporate it into the litterer's body in some painful configuration. Yes a crisp packet is tiny, but the void in the head of the person who dropped it is the size of a parking lot.
By the same token I imagine spammers are probably frightened of being identified in crowded places (if they ever leave the house, that is).
Someone in Lake Guillemont probably thought it was an amusing practical joke to pinch a piece from the completed Jackson Pollock jigsaw in Project Central. I imagine them thinking "They were a piece up, now they can try being a piece down...". Well, mean-spiritedness is revealed in the smallest actions probably more clearly than in the largest. If you want to join the ranks of street litterer's, spammers and others who should know better, then hang on to that piece. Otherwise replace it and we'll say no more about it.
In fact - I'll even offer an inducement. Return the piece and I'll blog one entry on the subject of your choice (at my discretion) - a reward made possible by the anonymous-coward technology of the internet.
P.S. You'd best wait till no-one's about. Donna thinks she knows who you are and I wouldn't want to be on the receiving end of her wrath. She handles that shredder like a pro these days.
Posted at
11:42AM Jul 13, 2007
by John Alderson in Lake Guillemont |
The "Off-bike"
Yesterday I was half-way up Whitchurch Hill (Reading, RG8) in a bit of a dream and accidentally changed up instead of down. As my small store of momentum dribbled away I rather savagely changed down again and knocked the chain off. This presented my cerebellum with a set of circumstances it had hitherto not encountered and I promptly fell over.
I always come up laughing from toe-clip-related accidents because they are such good slapstick - but my right knee is not laughing with me. These things are all over-and-done-with before the conscious mind can intervene sensibly (at least, at my age...) but low-level management (the cerebellum) seems to have to learn about them on a case-by-case basis.
I think my legs assumed I had discovered some new and most excellently low gear and they pedaled heartily while I was, in fact, moving gently backwards.
Hence this modest proposal:
Related to the bolt-on skid pan favoured by advanced driving schools I propose a training bike with built-in radio controlled sabotage:
The trainee rides around a traffic-free circuit (with hills) while the operator remotely triggers random disasters giving the rider ample opportunity to train his or her reflexes in a safe environment (with kneepads). I'd be particularly impressed with someone who learns to stop gracefully when the handlebar option is triggered without warning.
I guess you could build a bike simulator for this but it wouldn't be half as much fun - and "no pain, no gain" is not an empty mantra for these particular feedback loops. I remember the first time I successfully, unconsciously, yanked my right foot out in time when I was tipping the wrong way. There was, immediately to my right, a large and chilly-looking puddle...
Posted at
10:27AM Jul 09, 2007
by John Alderson in Get on yer Bike |
The best of the Two Tribes problems - Part 2
Continued from here.
You point to one of the paths and say:
I remember sitting at a trestle table and making a little grid out of knives and forks. I labelled the columns and rows with other domestic items and then filled in the grid with the answers given by the native. Salt meant pish and pepper meant tush. The resulting pattern was as follows:
From this I could see that if the native answers pish then the road goes to the village - regardless of whether pish means yes or no. In the general case, if the native uses the same word in the answer that you used in the question then the path leads to the village.
I remember the dawning sense of triumph I got from from examining this boolean decoration. Mum was less impressed: "That doesn't quite count as setting the table..."
Posted at
12:45PM Apr 27, 2007
by John Alderson in Problem Solving |
Donna's Pet Project
Donna is building a quantum computer!
This has arrived in kit form from Sumover Futures Inc (I bet the stock analysts love that name) who are a startup specializing in qbit-logic workstations. Some marketing guy there (probably only half a marketing guy) decided it would be funky to use complex numbers for their branding - so this beast is an SFW 1000+8i. It looks like an ordinary workstation at the moment - because that's what it is - but then there's this big rack hanging off the back with some major cooling plant on 3-phase.
The rack, once you've fought your way inside it, can take up to 8 "superposition engines". Each one of these can maintain a goodly pile of quantum "dots" in a state of quantum coherency for a respectable number of seconds. The actual number of seconds achieved is a matter of luck, of course, the only guideline we have is an MTBF of about 4.5.
In use it's supposed to be a bit like programming an FPGA. The host OS on the workstation (our bit) allows you to build qbit processing logic into one or more engines and then release them, hoping they don't go classical before they spit out an answer. There's supposed to be a photonic crossbar linking the 8 units so they can exchange "data" without loss of coherence. This would effectively increase the number of coherent dots eightfold. The cost would be a substantially reduced MTBF but at that level of, er, simultaneity who cares if you only get it for a second? Unfortunately the cross-bar isn't supported yet. You need correction codes to allow you to ignore photons which have accidentally bounced off something, and Sumover haven't got them working yet. Donna claims to have some ideas about that - I hope none of them involves the shredder.
Posted at
09:14AM Apr 26, 2007
by John Alderson in Lake Guillemont |
The best of the Two Tribes problems - Part 1
We were on holiday in a hut in a remote spot in Devon when I was eleven or twelve years old. On sunny days we walked down to the beach (about two miles away) and played all day, returning at night with as much driftwood as we could carry. On rainy days we burnt the driftwood on the hut's hearth which was backed by a fat black pipe thrown into folds like the body of a prone python. The water heated in the pipe rose by convection to a half-buried tank some way up the hill behind the hut.
Most of a rainy day was spent indoors reading books from the hut's ample stock of paperbacks and it may have been there that we discovered the first collection of Mathematical Games made from Martin Gardner's long-running column in Scientific American and published by Pelican - or we might have brought it with us. At any rate, it was there that we read his round-up of "Two Tribes" problems, the pinnacle of which went something like this:
To reduce disturbance from visiting anthropologists the natives have built a fork in the one road leading inland from the shore. One path of the fork leads to the village where travelers can be assured of safety and hospitality; the other leads to a dangerous swamp where they will be instantly devoured by voracious giant land-snails.
However, the natives are not unsporting and there is always one of their number stationed at the fork to provide assistance. By ancient tradition you are permitted to ask him or her ONE question which will be answered yes or no. Unfortunately you have lost your Remote Islandese dictionary in the rough sea crossing and, though you have a working knowledge of the language, you cannot remember the words for "yes" and "no". That is to say, you know the words are "pish" and "tush" but you can't remember which is which.
Your problem is to construct one question that you can ask the native at the fork in the road, the answer to which will guarantee that you know which path leads to the comfort and safety of the village and avoids the ravages of the snails.
(PS: I may have made up the bit about the snails...)
Posted at
05:42PM Apr 24, 2007
by John Alderson in Problem Solving |
Makeovers
One of the interns has hold of a large, shiny nut and bolt - which probably should be fastened through some critical component in the lab. He idly spins the nut up and down the bolt while he he sits at his desk and it makes an agreeable jingling sound to accompany his surfing industrious typing.
"Agreeable", that is, for about a minute. After that time it becomes monotonous. Then it begins to remind me of an animal in a cage too small, pacing up and down. At about this time Arnie Shepherd's leg starts up. I believe I mentioned way back that the office is earthquake proof; one consequence of this is that the floor vibrates like the skin of a drum. A good leg-twitch can transmit itself up every seatpost in a twenty metre radius. Confined to the office for a few generations we would probably acquire the ability to communicate with infrasaound, like elephants.
So I now have jingling from one direction and steady tremors from another. Output from a coredump seems to crawl around my screen and become disassociated from all meaning. What are these figures? 0xdeadbeef - what on earth does that mean?
- Thud thud thud, jingle jingle ... Brrrr thud thud, jingle jingle...
The caged animal must have a bell on it's collar. It seems to be eyeing me from behind the dense foliage of a SCSI packet structure. I try to move my mouse pointer but I have no idea what I am going to do with it when it arrives at its destination. The jingle is now as loud as the sound made by a convention of 500 chainsaw-wielding zombies on a luxury liner.
Suddenly in the corner of my eye I spot Ursula Resplandor heading purposefully towards the intern. Halleluja, I am not alone! However, I have watched this scene before. She will falter in the advance and make some angry but significantly oddball remark which will fail to move the intern. He will laugh, his fellow minions will laugh too, Ursula will retreat in disarray and the jingling will resume on a cosmic scale.
But as she passes me I am conscious of a scent of some hitherto unnoticed perfume - and around her eyes are distinct traces of makeup, applied with skill and economy. She goes right up to the intern and fixes him with a cold stare. The forehead is barely puckered, the eyes barely narrowed, but the effect is devastating. The intern's neck and head change colour from the bottom up like some funky GUI histogram warning of imminent memory exhaustion. Ursula holds out her hand and, receiving the nut and bolt without a single word, proceeds serenely labwards.
"Arnie, quit the leg!" I cry and, turning, I catch Donna watching after Ursula with an approving smile. Donna has taken to wearing rather chic glasses, the better to absorb Ursula's weighty copy of "The Compleat Cryptographer". She has also asked to take my Knuth home with her and I worry lest I will be separated from it forever.
Posted at
08:00AM Apr 24, 2007
by John Alderson in Lake Guillemont |
Minutes
Algernon spent most of the meeting showing off his yacht and extolling the virtues of his satellite network hardware - which he got from these guys.
Donna was declared winner in the question of who-put-the-last-piece-in-the-puzzle. Algernon cracked up and said "I like your style baby". (You have to cringe carefully in brave new webcam world or it may be held against you.) Donna will now get a project of her own to manage. Ursula barely batted an eyelid - curiouser and curiouser...
The next puzzle is to be a Mark Rothko. Algernon is going to try to get one to cover the whole East wall. Arnie Shepherd says "Me bagsie the middle bit".
Donna has had a note from Human Resources instructing her to remove the large pendant bearing a likeness of Alex Turner which she proudly wears at work. Algernon says "Don't worry, I'll take it up with them". Donna says "Arctic Monkey is, like, my religion!" "That could be a good angle..." says Algernon.
Posted at
07:13AM Apr 21, 2007
by John Alderson in Lake Guillemont |
Today's Page Hits: 21 | http://blogs.sun.com/beamish/ | crawl-002 | refinedweb | 5,752 | 68.6 |
Eric Schrock's Weblog Reflections on OS integration 2010-12-08T14:35:41+00:00 Apache Roller FISL Day 1 eschrock 2005-06-01T20:24:30+00:00 2005-06-02T10:40:50+00:00 <p>So the first day of <a href="">FISL</a> has come to a close. I have to say it went better than expected, based on the quality of questions posed by the audience and visitors to the Sun booth. If today is any indication, my voice is going to completely gone by the end of the conference. I started off the day with a technical overview of Solaris 10/OpenSolaris. You can find the slides for this presentation <a href="">here</a>. Before taking too much credit myself, the content of these slides are largely based off of <a href="">Dan's<.</p> </p> <p:</p> <p><center><h3>"If you DTrace it, they will come"</h3></center></h3> Technorati tags: <a href="" rel="tag">Solaris</a> <a href="" rel="tag">OpenSolaris</a> Designing for Failure eschrock 2005-04-14T23:30:33+00:00 2005-04-15T06:40:42+00:00 <p>In the last few weeks, I've been completely re-designing the ZFS commands from the ground up<sup>1</sup>. When I stood back and looked at the current state of the utilities, several glaring deficiencies jumped out at me<sup>2</sup>. I thought I'd use this blog entry to focus on one that near and dear to me. Having spent a great deal of time with the debugging and observability tools, I've invariably focused on answering the question <i>"How do I diagnose and fix a problem when something goes wrong?"</i>. When it comes to command line utilities, the core this problem is in well-designed error messages. To wit, running the following (former) ZFS command demonstrates the number one mistake when reporting error messages:</p> <pre> # zfs create -c pool/foo pool/bar zfs: Can't create pool/bar: Invalid argument # </pre> <p:</p> <p><b>An error message must clearly identify the source of the problem in a way that that the user can understand.</b></p> <p><b>An error message must suggest what the user can do to fix the problem.</b></p> <p.</p> <p>A grand vision of proper failure analysis can be seen in the Fault Management Architecture in Solaris 10, part of <a href="">Predictive Self Healing</a>.).</p> <p>Such a wide-ranging problem doesn't necessarily compare to a simple set of command line utilities. A smaller scale example can be seen with the Solaris Management Facility. When SMF first integrated, it was incredibly difficult to diagnose problems when they occurred<sup>3</sup>. The result, after a few weeks of struggle, was one of the best tools to come out of SMF, <tt>svcs -x</tt>. <tt>svcs -x</tt> and FMA. I hope that this is reflected in the final product.</p> <p>So what does this mean for you? First of all, if there's any Solaris error message that is unclear or uninformative <b>that is a bug</b>. There are some rare cases when we have no other choice (because we're relying on an arbitrary subsystem that can only communicate via errno values), but 90% of the time its because the system hasn't been sufficiently designed with failure in mind.</p> <p>I'll also leave you with a few cardinal<sup>4</sup> rules of proper error design beyond the two principles above:</p> <ol> <li>Never distill multiple faults into a single error code. Any error that gets passed between functions or subsystems must be traceable back to a single specific failure.</li> <li>Stay away from <tt>strerror(3c)</tt> at all costs. Unless you are truly interfacing with an arbitrary UNIX system, the errno values are rarely sufficient.</li> <li>Design your error reporting at the same time you design the interface. Put all possible error messages in a single document and make sure they are both consistent and effective.</li> <li>When possible, perform automated diagnosis to reduce the amount of unimportant data or give the user more specific data to work with.</li> <li>Distance yourself from the implementation and make sure that any error message makes sense to the average user.</li> </ol> <hr/> <p><sup>1</sup>No, I cannot tell you when ZFS will integrate, or when it will be available. Sorry.</p> <p><sup>2</sup>This is not intended as a jab at the ZFS team. They have been working full steam on the (significantly more complicated) implementation. The commands have grown organically over time, and are beginning to show their age.</p> <p><sup>3</sup>Again, this is not meant to disparage the SMF team. There were many more factors here, and all the problems have since been fixed.</p> <p><sup>4</sup> "cardinal" might be a stretch here. A better phrase is probably "random list of rules I came up with on the spot".</p> How not to code eschrock 2005-03-31T16:59:40+00:00 2005-04-01T18:32:45+00:00 <p>This little gem came up in conversation last night, and it was suggested that it would make a rather amusing blog entry. A Solaris project had a command line utility with the following, unspeakably horrid, piece of code:</p> <pre> /\* \* Use the dynamic linker to look up the function we should \* call. \*/ (void) snprintf(func_name, sizeof (func_name), "do_%s", cmd); func_ptr = (int (\*)(int, char \*\*)) dlsym(RTLD_DEFAULT, func_name); if (func_ptr == NULL) { fprintf(stderr, "Unrecognized command %s", cmd); usage(); } return ((\*func_ptr)(argc, argv)); </pre> <p>So when you type "a.out foo", the command would <tt>sprintf</t:</p> <pre> for (i = 0; i < sizeof (func_table) / sizeof (func_table[0]); i++) { if (strcmp(func_table[i].name, cmd) == 0) return (func_table[i].func(argc, argv)); } fprintf(stderr, "Unrecognized command %s", cmd); usage(); </pre> <p <tt>do_foo()</tt> using cscope.</p> <p>This serves as a good reminder that the most clever way of doing something is usually not the right answer. Unless you have a really good reason (such as performance), being overly clever will only make your code more difficult to maintain and more prone to error.</p> <p><b>Update - </b> Since some people seem a little confused, I thoght I'd elaborate two points. First off, there is no loadable library. This is a library <i>linked directly to the application</i>. There is no need to asynchronously update the commands. Second, the proposed function table does <b>not</b> have to live separately from the code. It would be quite simple to put the function table <i>in the same file</i> with the function definitions, which would improve maintainability and understability by an order of magnitude.</p> Slashdotted... eschrock 2004-09-27T16:01:10+00:00 2004-09-27T23:01:10+00:00 <p>So my last few posts have sparked quite a bit of discussion out there, appearing on <a href="">slashdot</a> as well as <a href="">OSNews</a>. It's been quite an interesting experience, though it's had a significant effect on my work productivity today :-) While I'm not responding to every post, I promise that I'm reading them (and thanks to those of you sending private mail, I promise to respond soon).</p> <p>I have to say that I've been reasonably impressed with the discussion so far. Slashdot, as usual, leaves something to be desired (even reading at +5), but the comments in my blog and in my email have been for the most part very reasonable. There is a certain amount of typical fanboy drivel (more so on the pro-Linux side, but only because Solaris doesn't have many fanboys). But there's also a reasonable contingent on Slashdot fighting down the baseless arguments of the zealots. In the past, the debate has been rather one-sided. Solaris is usually dismissed as an OS for <a href="">big computers for people with lots of money</a>. Sun has traditionally let our marketing department do all the talking, which works really well for CEOs and CTOs (our paying customers), but not as well for spreading detailed technical knowledge to the developer community. We're changing our business model - encouraging blogs, releasing Solaris Express, hosting discussions with actual kernel engineers, and eventually open sourcing Solaris - to encourage direct connections with the community at large.</p> <p>We've been listening to the (often one-sided) discussion for a long time now, and it shows in Solaris. Solaris 10 has killer performance, even on single- and dual-processor x86 machines. Hardware support has been greatly improved (S10 installed on my Toshiba laptop without a hitch). We're focusing on the desktop again, with X.Org integration, Gnome 2.6, Mozilla 1.7, and better open source packages all around. Sure, we're still playing catchup in a lot of ways, but we're learning. I only hope the Linux community can learn from Solaris's strengths, and dismiss many of the Solaris stereotypes that have been implanted (not always without merit) over the course of history. Healthy competition is good, and can only benefit the customer.</p> <p>As much as I would like to continue this debate forever, I think it's time I get back to doing what I really love - making Solaris into the best OS it can be. I'll probably be focusing on more technical posts for a while, but I'll revive the discussion again at a future point. Until then, feel free to continue posting comments or sending me mail. I do read them, even if I don't respond publicly.</p> GPL thoughts and clarifications eschrock 2004-09-24T09:47:51+00:00 2004-09-28T18:44:57+00:00 <p>So it seems my <a href="">previous entry</a> has finally started to stir up some controversy. I'll address some of the technical issues <a href="">raised here</a> shortly. But first I thought I'd clarify my view of the GPL, with the help of an analogy:</p> <p>Let's say that I manufacture wooden two by fours, and that I want to make them freely available under an "open source" license. There are several options out there:</p> <ol> <li><p><b>You have the right to use and modify my 2x4s to your hearts content.</b></p> <p>This is the basis for open source software. It protects the rights of the consumer, but imparts few rights to the developer.</p></li> <li><p><b>You have the right to use my 2x4s however you please, but if you modify one, then you have to make that modification freely available to the public in the same fashion as the original.</b><p> <p>This gives the developer a few more guarantees about what can and cannot be done with his or her contributions. It protects the developer's rights without infringing on the rights of the consumer.</p></li> <li><p><b>You have the right to use my 2x4 as-is, but if you decide to build a house with it, then your house must be as freely available as my 2x4.</b></p> <p>This is the provision of the GPL that I don't agree with, and neither do customers that we've talked to. It protects my rights as a developer, but severely limits the rights of the consumer in what can and cannot be done with my public donation.</p></li> </ol> <p.</p> <p.</p> .</p> <p.</p> .</p> <p>[ UPDATE ]</p> <p>As has been enumerated in the comments on this post, the original intent of the analogy is to show the the definition of derived works. As mentioned in the comments:</p> <p><i></p> <p.</p> Linux Kernel Debugging with KDB eschrock 2004-09-07T21:55:16+00:00 2004-09-08T05:37:21+00:00 <p>So it's been a while since my <a href="">KMDB post</a>, but I promised I would do some investigation into kernel debugging on the Linux side. Keep in mind that I have no Linux kernel experience. While I will try to be thorough in my research, there may be things I miss simply from lack of experience or a good test system. Feel free to comment on any errors or omissions.</p> <p>We'll try to solve the same problem that I approached with KMDB in the last post: a deadlock involving reader-writer locks. Linux has a choice of two debuggers, kdb and kgdb (though User Mode Linux presents interesting possibilities). In this post I'll be taking a look at <a href="">KDB</a>.</p> <h3>Fire up KDB</h3> <p>Chances are you're not running a Linux kernel with KDB installed. Some distros (like Debian) make it easier to download and apply the patch, but none seems to include it by default (admittedly, I didn't do a very thorough search). This means you'll have to go download the patch, apply it, tweak some kernel config variables (<tt>CONFIG_KDB</tt> and <tt>CONFIG_FRAME_POINTER</tt>), recompile/reinstall your kernel, and reboot. Hopefully you've done all this beforehand, because as soon you reboot you've lost your bug (possibly forever - race conditions are fickle creatures). Assuming you were running a kdb-enabled kernel when you hit this bug, you then run:</p> <pre> # echo "1" > /proc/sys/kernel/kdb </pre> <p>And then press the 'pause' key on your keyboard. Alternatively, you can hook up a serial console, but I'll opt for the easy way out.</p> <h3>Find our troubled thread</h3> <p>First, we need to find the pid our offending process. The only way to do this is to use the <tt>'ps'</tt> command to display all processes on the system, and then pick out (visually) which pid belongs to our 'ps' process. Once we have this information, we can then use <tt>'btp <pid>'</tt> to get a stack trace.</p> <h3>Get the address of the rwlock</h3> <p>This step is very similar to the one we took when using kmdb. The stack trace produced by <tt>'btp'</tt> includes frame pointers like kmdb's <tt>$C</tt>. Looking back over my kmdb post, it wasn't immediately clear where I got that magic starting number - it came from the frame pointer in the (verbose) stack trace. In any case, we use <tt>'id <addr>'</tt> to disassemble the code around our call site. We then use <tt>'mdr <addr+offset>'</tt> to examine the memory where the original value is saved. This gets much more interesting (painful) on amd64, where arguments are passed in registers and may not get pushed on the stack until several frames later.</p> <h3>Without a paddle?</h3> <p>At this point, the next step should be "Find who owns the reader lock." But I can't find any commands in the kdb manpages that would help us determine this. Without kmdb's <tt>::kgrep</tt>, we're stuck searching for a needle in a haystack. Somewhere on this system, one or more threads have referenced this rwlock in the past. Our only course of action is to try <tt>'bta'</tt>, which will give us a stack trace of every single process on the system. With a deep understanding of the code, a great deal of persistence, and a little bit of luck, we may be able to pick out the offending stack just by sight. This quickly becomes impractical on large systems, not to mention difficult to verify and prone to error.</p> <p>With KDB we can do some basic debugging tasks, but it still relies on giant "leaps of faith" to correlate two pieces of seemingly disjoint data (two thread involved in a deadlock, for example). As a point of comparison, KDB provides 40 different commands, while KMDB provides 771 (356 dcmds and 415 walkers on my current desktop). Next week I'll look at kgdb and see if it fills in any of these gaps.</p> So now Linux is innovative? eschrock 2004-08-18T23:48:09+00:00 2004-08-19T15:50:56+00:00 <p>I just ran across <a href="">this interview</a> with Linus. If you've read my blog, you know I've <a href="">talked before</a> about OS innovation, particularly with regards to Linux and Solaris. So I found this particular Linus quote very interesting:</p> <p><i.</i></p> <p>This seems to fly in the face of his <a href="">previous statements</a>,<sup>1</sup>.</p> <p>I also don't buy the "supporting lots of platforms means no chance for innovation" stance. Most of the Solaris 10 innovations (Zones, Greenline, Least Privileges) are completely hardware independent. Those projects which <i>are</i> hardware dependent develop a platform-neutral infrastructure, and provide modules only for those platforms which they suppot (FMA being a good example of this). Testing is hard. It's clear that <a href="">Linux testing</a><sup>2</sup>.</p> <p>As we look towards OpenSolaris, I'm intrigued by this comment by Linus:</p> <p><i.</i></p> <p>Stephen has <a href="">previously questioned</a> the importance of a single leader for an open source project. In the course of development for OpenSolaris, we've looked at many open source models, ranging from the "benevolent dictatorship" to the community model (and perhaps briefly, the <a href="">pornocracy</a>)..</p> <p>So it's time for Space Ghosts's "something.... to think about....":</p> <p><i>Is it beneficial to have one man, or one corporation, have the final say in the development of an open source project?</i></p> <hr/> <p><sup>1</sup>ZFS is an example of truly innovative performance improvements. Once you chuck the volume manager, all sorts of avenues open up that nobody's ever though about before.</p> <p><sup>2</sup>To.</p> More on OS innovation eschrock 2004-08-04T09:44:57+00:00 2004-08-04T16:44:07+00:00 <p>The other day on vacation, I ran across a Slashdot article on UNIX branding and GNU/Linux. Tne <a href="">original article</a> was mildy interesting, to the point where I actually bothered to read <a href="">the comments</a>. Now, long ago I learned that 99% of Slashdot comments are worthless. Very rarely to you find thoughtful and objective comments; even browsing at +5 can be hazardous to your health. Even so, I managed to find <a href="">this comment</a>, which contained in part some perspective relating to my <a href="">previous post</a> on Linux innovation:</p> <i><p.</p> <p>There is a basic set of core functions that O/S do and this has not changed in principle for over a decade. Log based file systems, threads that work etc are now standard, but none of this was new ten years ago.</p> <p>The interesting stuff all takes place either above or below the O/S layer. .NET, J2EE etc are where interesting stuff is happening.</p></i> <p.</p> <p.</p> <p.</p> <p>So think twice before declaring the OS irrelevant. Even if you don't use features directly provided by the OS, your quality of life has been improved by having them available to those that do use them.</p> Is Linux innovative? eschrock 2004-07-20T22:11:26+00:00 2004-07-22T00:26:18+00:00 <p>In a departure from recent musings on the inner workings of Solaris, I thought I'd examine one of the issues that <a href="">Bryan</a> has touched on in his blog. Bryan has been looking at some of the larger issues regarding OS <a href="">innovation</a>, commoditization, and <a href="">academic research</a>. I thought I'd take a direct approach by examining our nearest competitor, Linux.</p> <p>Bryan probably <a href="">said it best</a>: <i>We believe that the operating system is a nexus of innovation.</i></p> <p>I don't have a lot of experience with the Linux community, but my impression is that the OS is perceived as a commodity. As a result, Linux is just another OS; albeit one with open source and a large community to back it up. I see a lot of comments like "Linux basically does everything Solaris does" and "Solaris has a lot more features, but Linux is catching up." Very rarely do I see mention of features that blow Solaris (or other operating systems) out of the water. Linus himself has <a href="">said</a>:</p> <p><i>A lot of the exciting work ends up being all user space crap. I mean, exciting in the sense that I wouldn't car [sic], but if you look at the big picture, that's actually where most of the effort and most of the innovation goes.</i></p> <p>So Linus seems to agree with my intuition, but I'm in unfamiliar territory here. So, I pose the question:</p> <p><b>Is the Linux operating system a source of innovation?</b></p> <p>This is a specific question: I'm interested only in software innovation relating to the OS. Issues such as open source, ISV suport, and hardware compatibility are irrelevant, as well as software which is not part of the kernel or doesn't depend on its facilities. I consider software such as the Solaris ptools as falling under the purview of the operating system, because they work hand-in-hand with the /proc filesystem, a kernel facility. Software such as GNOME, KDE, X, GNU tools, etc, are all independent of the OS and not germane to this discussion. I'm also less interested in purely academic work; one of the pitfalls of academic projects is that they rarely see the light of day in a real-world commercial setting. Of course, most innovative work must begin as research before it can be viable in the industry, but certainly proven technologies make better examples.</p> <p>I can name dozens of Solaris innovations, but only a handful of Linux ones. This could simply be because I know so much about Solaris and so little about Linux; I freely acknowledge that I'm no Linux expert. So are there great Linux OS innovations out there that I'm just not aware of?</p> Real life obfuscated code eschrock 2004-07-01T22:39:34+00:00 2004-07-02T05:45:36+00:00 <p>In a departure from my usual Solaris propaganda, I thought I'd try a little bit of history. This entry is aimed at all of you C programmers out there that enjoy the novelty of <a href="">Obfuscated C</a>. If you think you're a real C hacker, and haven't heard of the obfuscated C contenst, then you need to spend a few hours browsing their archives of <a href="">past winners</a><sup>1</sup>.</p> <p>If you've been reading manpages on your UNIX system, you've probably been using some form of <tt>troff</tt><sup>2</sup>. This is an early typesetting language processor, dating back to pre-UNIX days. You can find some history <a href="">here</a>. The <tt>nroff</tt> and <tt>troff</tt> commands are essentially the same; they are built largely from the same source and differ only in their options and output formats.</p> <p>The original <tt>troff</tt> was written by Joe F. Ossanna in assembly language for the PDP-11 in the early 70s. Along came this whizzy portable language known as <a href="">C</a>, so Ossana rewrote his formatting program. However, it was less of a rewrite and more of a direct translation of the assembly code. The result is a truly incomprehensible tangle of C code, almost completely uncommented. To top it off, Ossana was tragically killed in a car accident in 1977. Rumour has it that attempts were made to enhance <tt>troff</tt>, before Brian Kernighan caved in and rewrote it from scratch as <tt>ditroff</tt>.</p> <p>If you're curious just <i>how</i> incomprehensible 7000 lines of uncommented C code can be, you can find a later version of it from <a href="">The Unix Tree</a>, an invaluable resource for the nostalgic among us. To begin with, the files are named <tt>n1.c</tt>, <tt>n2.c</tt>, etc. To quote from 'n6.c':</p> <pre> setch(){ register i,\*j,k; extern int chtab[]; if((i = getrq()) == 0)return(0); for(j=chtab;\*j != i;j++)if(\*(j++) == 0)return(0); k = \*(++j) | chbits; return(k); } find(i,j) int i,j[]; { register k; if(((k = i-'0') >= 1) && (k <= 4) && (k != smnt))return(--k); for(k=0; j[k] != i; k++)if(j[k] == 0)return(-1); return(k); } </pre> <p>If this doesn't convince you to write well-structured, well-commented code, I don't know what will. The scary thing is that there are at least 18 bugs in our database open against <tt>nroff</tt> or <tt>troff</tt>; one of the side-effects of promising full backwards compatibility. <a href="">Anyone</a> who has the courage to putback nroff changes earns a badge of honor here - it is a <a href="">dark place</a> that has claimed the free time of a few brave programmers<sup>3</sup>. Whenever an open bug report includes such choice phrases as this, you know you're in trouble:</p> <p><i>I've seen this problem on non-Sun Unix as well, like Ultrix 3.1 so the problem likely came from Berkeley. The System V version of \*roff (ditroff ?) doesn't have this problem.</i></p> <hr/> <p><sup>1</sup>One of my personal favorites is this little gem, a 2000 winner 'natori'. It should be a full moon tomorrow night...</p> <pre> #include <stdio.h> #include <math.h> double l;main(_,o,O){return putchar((_--+22&&_+44&&main(_,-43,_),_&&o)?(main(-43, ++o,O),((l=(o+21)/sqrt(3-O\*22-O\*O),l\*l<4&&(fabs(((time(0)-607728)%2551443)/ 405859.-4.7+acos(l/2))<1.57))[" #"])):10);} </pre> <p><sup>2</sup>On Solaris, most manpages are written in SGML, and can be found in <tt>/usr/share/man/sman\*</tt>.</p> <p><sup>3</sup>I'd like to think that the x86 disassembler is a close second, but maybe that's just because I'm a survivor.<p> Software Abstraction and the Jaws of Life eschrock 2004-06-17T17:09:12+00:00 2004-06-18T06:11:03+00:00 <p>Before I start looking at some of problems we're addressing in Solaris, I want to step back and examine one of the more fundamental problems I've been seeing in the industry. In order to develop more powerful software quickly, we insert layers of abstraction to distance ourselves from the actual implmentation (let someone else worry about it). There is nothing inherently wrong with this; no one is going to argue that you should write your business critical web service in assembly language instead of Java using <a href="">J2EE</a>. The problem comes from the disturbing trend that programmers are increasingly less knowledgeable about the layers upon which they build.</p> <p>Most people can sit down and learn how to program Java or C, given enough time. The difference between an average programmer and a gifted programmer is the ability to <b>truly understand</b> the levels above and below where one works. For the majority of us<sup>1</sup>, this means understanding two things: our development platform and our customers. While understanding customer needs is a difficult task, a more tragic problem is the failure of programmers to understand their immediate development environment.</p> <p <i>need</i> to know the OS works doesn't mean you <i>shouldn't</i>. Knowing your environment encourages good software practice, as well as making you more effective at solving problems when they do occur.</p> <p <a href="">rip the hood off</a><sup>2</sup> so you can see what's really happening inside.</p> <p <a href="">good book</a> once in a while.</p> <hr/> <p><sup>1</sup>For.</p> <p><sup>2</sup>Scott is in the habit of talking about how we sell cars, not auto parts. Does that mean we also provide the <a href="">Jaws of Life</a> to save you after you crash your new <a href="">Enzo</a>? | http://blogs.oracle.com/eschrock/feed/entries/atom?cat=%2FSoftware | CC-MAIN-2015-27 | refinedweb | 4,832 | 61.77 |
__init_subclass__ Just asking (py 3.6)
@omz, I understand ui Elements are done in Objective-C and can't be sub classed. But does the introduction of the init_subclass hook in py3.6 give any new opportunities? I am guessing the answer is no, but wanted to ask anyway.
When you define an
__init_subclass__method on a class, that method is called when you subclass that class. This only really helps you when you are writing the base class, which isn't the case here.
The reason why the
ui.Viewsubclasses can't be subclassed is different. It's not that classes implemented in C cannot be subclassed - after all,
objectand
ui.Vieware also implemented in C, and you can subclass those. The issue is that (as I understand it) C classes do not support subclassing by default, and if you want to support it, you need to add extra custom handling for each class. There are quite a lot of default
ui.Viewsubclasses, so omz might have decided that it's not worth the effort to write and test subclassing support for each one.
@dgelessus , thanks for the good explanation. I am wondering if I got the right magic method here. I was watching a video about 3.6 changes and they mentioned a magic method that you get called on before the init is called. Basically so you can avoid having to do the tricks to craft a class before it's built.
I have to go back and watch the video. It sounded important and interesting. I was initially thinking that it might have been a help to the stuff @jonb did with bindings to get a loaded pyui file into custom class.
Anyway, I will rewatch the video and see
@dgelessus is right. The reason
ui.Viewsubclasses (and some other things) cannot be subclassed further is that supporting subclassing requires additional precautions. It's not that it's impossible (see
ui.View), but it's more work than simply not allowing subclassing (e.g.
ui.Rect).
@omz , ok. Fair enough. But has come a long way. Can add attrs at runtime, can pass all **kwargs for creation. The bindings also helped with pyui classes. So just saying many enhancements have been made to supplement not being able to subclass thinks like ui.Button.
The below example has always frustrated me. That is if you add a method to a ui Element at runtime, you cant get a reference to the instance of the object calling the method. Maybe there is a way I don't know about. But as far as I know you cant.
I am looking from the point of view, if these items cant be subclassed, what do you really need from subclassing the item. The one I mention here would be a good one to have as I see it.
import ui def pos(sender=None, x=0, y=0): print('hello, but i dont which object called me') print(f'btw x={x} and y={y}') ''' i would like it possible that sender was valid here. i dont want to have to pass in the reference to the object as a param ''' if __name__ == '__main__': btn = ui.Button(frame = (20, 20, 80, 32), bg_color='white', border_width =.5) btn.title = 'Hit Me' btn.present(style='sheet') btn.pos = pos btn.pos(None, 10, 20)
__new__gets called before init, maybe that is what you were thinking?
BTW, what you are trying can be accomplished using
MethodType--binding an instance method to an instance.
Adapted from stackoverflow:
import types def patch_me(target): def pos(self,x,y): print ("x=",x,"y=",y) print ("called from", self) target.pos = types.MethodType(pos,target) #add more if needed import ui a = ui.Button() print (a) patch_me(a) #patch instance a.pos(10,20)
Using this approach, hopefully it should be obvious that you can sort of "subclass" ui.Button, though only sort of (the button still thinks it is a ui.Button, and you cannot override existing methods).
You could probably do this in a more generic way, say you define a custom class, which takes a Button in
__new__, which then traverses over instance methods in your NewClass and binds them to your button instance, then calls your NewClass.
__init__on the button, and finally returns the now patched button.
@JonB, thanks again. I remember code around like this before. Not sure it was exactly the same of not.
But I could not get this example working. I sort of can see what is happening. I get the trace back as listed below.
I played around with this statement target.method = types.MethodType(method,target) , but could not figure out how to get it correct.
Did you run it also?
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/MyProjects/scratch/patching_ui_methods.py", line 13, in <module>
patch_me(a) #patch instance
File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/MyProjects/scratch/patching_ui_methods.py", line 7, in patch_me
target.method = types.MethodType(method,target)
NameError: name 'method' is not defined
sorry, i edited it in real time to make it specifc to your pos method, but then forgot the generic one. I fixed the code above.
methodshould have been
pos
@JonB , thanks a lot. Sorry, I couldn't work it out. I was close, but still a million miles away. I never remember it being this easy to do this. I remembered I wanted to call positioning code on the ui.object rather than passing the object into functions. Also other things. But this is a nice addition to have. I didn't re watch that video yet, but i will. When i was watching it, the first thing that went though my mind is that it may simplify the pyui wrapper class you made. Although there is nothing wrong with it, still works fine.
Ok, but thanks again.
@JonB, I found this Talk from PyCon 2017. Know thy self, methods and method-bindings. I haven't had time to watch it all yet, but pretty sure this will help me understand all this a bit better.
I also mention for others who might read this thread. | https://forum.omz-software.com/topic/4246/__init_subclass__-just-asking-py-3-6 | CC-MAIN-2018-13 | refinedweb | 1,045 | 76.72 |
How to manage zip file
Hi. I have to manage a zip file (not gzip, just zip). Can somenone suggest me a way to do it (on both Linux and Windows)? qCompress and qUncompress does not work.
Regards.
The only answer is zlib, you just need to decide the flavour
- QuaZIP (handles only .zip, wrapper around zlib)
- KArchive (supports multiple compression formats, for zip it's a wrapper on zlib)
- zlib if you don't mind C then you can use directly the reference library for zip files
I personally use KArchive because it's already conveniently wrapped in a Qt style and it can rely on the support of KDE
Hi. I'm trying to use quazip.
I have built quazip package without problem. When I try to run
JlCompress::extractDir("a.zip", ".");
the probgram goes to crash.
.pro
windows { INCLUDEPATH += C:/Users/Denis/git/ControlloAccessi/quazip-0.7.2 INCLUDEPATH += C:/Users/Denis/git/ControlloAccessi/zlib128-dll/include LIBS += C:/Users/Denis/git/ControlloAccessi/quazip-0.7.2/quazip/release/quazip.lib }
main.cpp
#include "quazip/quazip.h" #include "QFile" #include "QDebug" #include <quazip/JlCompress.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); JlCompress::extractDir("a.zip", "b"); }
@mrdebug Did you try to debug to see what happens? Is it SIGSEGV or something else? Any error messages?
@mrdebug said in How to manage zip file:
When I try to run
You are linking to the release version of quazip so make sure you run the release version of your app.
change
LIBS += C:/Users/Denis/git/ControlloAccessi/quazip-0.7.2/quazip/release/quazip.libinto
CONFIG(debug, debug|release) { LIBS += -L"C:/Users/Denis/git/ControlloAccessi/quazip-0.7.2/quazip/debug" LIBS += -lquazipd }else { LIBS += -L"C:/Users/Denis/git/ControlloAccessi/quazip-0.7.2/quazip/release" LIBS += -lquazip }
Also make sure you make both Quazip.dll and zlib.dll (if you did not compile it as static) available at runtime
Sorry. I have missed the required dlls.
Is there a way to unzip a zip stream, from a QByteArray without to store it to a file before?
yes with
create a
QDataStreamoperating on the
QByteAraryand then pass
QDataStream::device()to that constructor.
On the other hand, I'm not sure what you are trying to do but you might not need QuaZip at all, have a look at and below
Someting like this?
QDataStream BufferIn(&Source, QIODevice::ReadOnly); QuaZipFile quaZip(BufferIn.device()); qDebug() << quaZip.open(QIODevice::ReadOnly);
returns false...
QuaZipFilerepresents a file inside a zip file, not a zip file in itself. the constructor you are calling is this one: use
QuaZipinstead.
P.S.
QDataStream BufferIn(&Source, QIODevice::ReadOnly);is the same as
QDataStream BufferIn(Source);
After many tries I can't unzip something without to use a file.
These lines of code
QDataStream BufferIn(&QBABufferOut, QIODevice::ReadOnly); QuaZip quaZip(BufferIn.device());
does not seem to work.
- SGaist Lifetime Qt Champion last edited by
Hi,
What do you have in QBABufferOut ?
Are you sure it's opened correctly ?
Why do you need
BufferInfor ?
And most important, what do you mean by
does not seem to work? That's to vague to help you.
Please have a look at this sequence:
QuaZipFile quaZip(QBABufferOut); // (rapresents a zip archivie in ram). if (quaZip.open(QIODevice::ReadOnly)) { // QIODevice::ReadOnly or someting else qDebug() << "ok"; } else qDebug() << "error"; // always error!!!!!!!!!!!!
You have to open the QuaZip for decompression first:
QBuffer storageBuff(&QBABufferOut); QuaZip zip(&storageBuff); if (!zip.open(QuaZip::mdUnzip)) qDebug() << "error"; QuaZipFile file(&zip); for (bool f = zip.goToFirstFile(); f; f = zip.goToNextFile()) { QuaZipFileInfo fileInfo; file.getFileInfo(&fileInfo); qDebug() << fileInfo.name; file.open(QIODevice::ReadOnly); qDebug() << "Content: " << file.readAll().toBase64(); file.close(); } zip.close();
P.S.
// (rapresents a zip archivie in ram).
No it doesn't. As mentioned before QuaZipFile represent a file inside a zip archive, not the archive itself
It works perfectly.
Many thanks.
@VRonin said in How to manage zip file:
QuaZIP
Is there a license associated with the use of this? As I have a need for compressing large amounts of binary data that I need to transmit to remote clients.
@SPlatten said in How to manage zip file:
Is there a license associated with the use of this?
Thank you,
@SPlatten if both ends are in your software I'd suggest agains using 3rd party library. qCompress and qUncompress work just fine in that regard. My usual approach is to supply a header (using QDataStream) with checksum and whatever else is needed, then stream to it output from compression routine. Works sufficiently well, eliminates the need for another dependency.
- Ramkumar Mohan last edited by
Hi, I'm working with zip files. | https://forum.qt.io/topic/74306/how-to-manage-zip-file | CC-MAIN-2022-33 | refinedweb | 783 | 60.72 |
11 Essential Code Blocks for Complete EDA (Exploratory Data Analysis)
This article is a practical guide to exploring any data science project and gain valuable insights.
By Susan Maina, Passionate about data, machine learning enthusiast, writer at Medium
Exploratory Data Analysis, or EDA, is one of the first steps of the data science process. It involves learning as much as possible about the data, without spending too much time. Here, you get an instinctive as well as a high-level practical understanding of the data. By the end of this process, you should have a general idea of the structure of the data set, some cleaning ideas, the target variable and, possible modeling techniques.
There are some general strategies to quickly perform EDA in most problems. In this article, I will use the Melbourne Housing snapshot dataset from kaggle to demonstrate the 11 blocks of code you can use to perform a satisfactory exploratory data analysis. The dataset includes
Address,
Type of Real estate,
Suburb,
Method of Selling,
Rooms,
Price, Real Estate Agent
(SellerG),
Date of Sale and,
Distance from C.B.D. You can follow along by downloading the dataset here.
The first step is importing the libraries required. We will need Pandas, Numpy, matplotlib and seaborn. To make sure all our columns are displayed, use
pd.set_option(’display.max_columns’, 100) . By default, pandas displays 20 columns and hides the rest.
import pandas as pd pd.set_option('display.max_columns',100)import numpy as npimport matplotlib.pyplot as plt %matplotlib inlineimport seaborn as sns sns.set_style('darkgrid')
Panda’s
pd.read_csv(path) reads in the csv file as a DataFrame.
data = pd.read_csv('melb_data.csv')
Basic data set Exploration
1. Shape (dimensions) of the DataFrame
The
.shape attribute of a Pandas DataFrame gives an overall structure of the data. It returns a tuple of length 2 that translates to how many rows of observations and columns the dataset has.
data.shape### Results (13580, 21)
We can see that the dataset has 13,580 observations and 21 features, and one of those features is the target variable.
2. Data types of the various columns
The DataFrame’s
.dtypes attribute displays the data types of the columns as a Panda’s Series (Series means a column of values and their indices).
data.dtypes### Results Suburb object Address object Rooms int64 Type object Price float64 Method object SellerG object Date object Distance float64 Postcode float64 Bedroom2 float64 Bathroom float64 Car float64 Landsize float64 BuildingArea float64 YearBuilt float64 CouncilArea object Lattitude float64 Longtitude float64 Regionname object Propertycount float64 dtype: object
We observe that our dataset has a combination of categorical (object) and numeric (float and int) features. At this point, I went back to the Kaggle page for an understanding of the columns and their meanings. Check out the table of columns and their definitions here created with Datawrapper.
What to look out for;
- Numeric features that should be categorical and vice versa.
From a quick analysis, I did not find any mismatch for the datatypes. This makes sense as this dataset version is a cleaned snapshot of the original Melbourne data.
3. Display a few rows
The Pandas DataFrame has very handy functions for displaying a few observations.
data.head()displays the first 5 observations,
data.tail() the last 5, and
data.sample() an observation chosen randomly from the dataset. You can display 5 random observations using
data.sample(5)
data.head() data.tail() data.sample(5)
What to look out for:
- Can you understand the column names? Do they make sense? (Check with the variable definitions again if needed)
- Do the values in these columns make sense?
- Are there significant missing values (NaN) sighted?
- What types of classes do the categorical features have?
My insights; the
Postcode and
Propertycount features both changed according to the
Suburb feature. Also, there were significant missing values for the
BuildingArea and
YearBuilt.
Distribution
This refers to how the values in a feature are distributed, or how often they occur. For numeric features, we’ll see how many times groups of numbers appear in a particular column, and for categorical features, the classes for each column and their frequency. We will use both graphs and actual summary statistics. The graphs enable us to get an overall idea of the distributions while the statistics give us factual numbers. These two strategies are both recommended as they complement each other.
Numeric Features
4. Plot each numeric feature
We will use Pandas histogram. A histogram groups numbers into ranges (or bins) and the height of a bar shows how many numbers fall in that range.
df.hist() plots a histogram of the data’s numeric features in a grid. We will also provide the
figsize and
xrot arguments to increase the grid size and rotate the x-axis by 45 degrees.
data.hist(figsize=(14,14), xrot=45) plt.show()
Histogram by author
What to look out for:
- Possible outliers that cannot be explained or might be measurement errors
- Numeric features that should be categorical. For example,
Genderrepresented by 1 and 0.
- Boundaries that do not make sense such as percentage values> 100.
From the histogram, I noted that
BuildingArea and
LandSize had potential outliers to the right. Our target feature
Price was also highly skewed to the right. I also noted that
YearBuilt was very skewed to the left and the boundary started at the year 1200 which was odd. Let’s move on to the summary statistics for a clearer picture.
5. Summary statistics of the numerical features
Now that we have an intuitive feel of the numeric features, we will look at actual statistics using
df.describe()which displays their summary statistics.
data.describe()
We can see for each numeric feature, the count of values in it, the mean value, std or standard deviation, minimum value, the 25th percentile, the 50th percentile or median, the 75th percentile, and the maximum value. From the count we can also identify the features with missing values; their count is not equal to the total number of rows of the dataset. These are
Car,
LandSize and
YearBuilt.
I noted that the minimum for both the
LandSize and
BuildingArea is 0. We also see that the
Price ranges from 85,000 to 9,000,000 which is a big range. We will explore these columns in detailed analysis later in the project.
Looking at the
YearBuilt feature, however, we note that the minimum year is 1196. This could be a possible data entry error that will be removed during cleaning.
Categorical features
6. Summary statistics of the categorical features
For categorical features, it is important to show the summary statistics before we plot graphs because some features have a lot of unique classes (like we will see for the
Address) and the classes would be unreadable if visualized on a countplot.
To check the summary statistics of only the categorical features, we will use
df.describe(include=’object’)
data.describe(include='object')
Categorical summary statistics by author
This table is a bit different from the one for numeric features. Here, we get the count of the values of each feature, the number of unique classes, the top most frequent class, and how frequently that class occurs in the data set.
We note that some classes have a lot of unique values such as
Address, followed by
Suburb and
SellerG. From these findings, I will only plot the columns with 10 or less unique classes. We also note that
CouncilArea has missing values.
7. Plot each categorical feature
Using the statistics above, we note that
Type,
Method and
Regionname have less than 10 classes and can be effectively visualized. We will plot these features using the Seaborn countplot, which is like a histogram for categorical variables. Each bar in a countplot represents a unique class.
I created a For loop. For each categorical feature, a countplot will be displayed to show how the classes are distributed for that feature. The line
df.select_dtypes(include=’object’) selects the categorical columns with their values and displays them. We will also include an If-statement so as to pick only the three columns with 10 or fewer classes using the line
Series.nunique() < 10. Read the
.nunique() documentation here.
for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: sns.countplot(y=column, data=data) plt.show()
Count plots by author
What to look out for:
- Sparse classes which have the potential to affect a model’s performance.
- Mistakes in labeling of the classes, for example 2 exact classes with minor spelling differences.
We note that
Regionname has some sparse classes which might need to be merged or re-assigned during modeling.
Grouping and segmentation
Segmentation allows us to cut the data and observe the relationship between categorical and numeric features.
8. Segment the target variable by categorical features.
Here, we will compare the target feature,
Price, between the various classes of our main categorical features
(Type,
Method and
Regionname) and see how the
Price changes with the classes.
We use the Seaborn boxplot which plots the distribution of
Price across the classes of categorical features. This tutorial, from where I borrowed the Image below, explains the boxplot’s features clearly. The dots at both ends represent outliers.
Image from
Again, I used a for loop to plot a boxplot of each categorical feature with
Price.
for column in data.select_dtypes(include=’object’): if data[column].nunique() < 10: sns.boxplot(y=column, x=’Price’, data=data) plt.show()
Box plots by author
What to look out for:
- which classes most affect the target variables.
Note how the
Price is still sparsely distributed among the 3 sparse classes of
Regionname seen earlier, strengthening our case against these classes.
Also note how the
SA class (the least frequent
Method class) commands high prices, almost similar prices of the most frequently occurring class
S.
9. Group numeric features by each categorical feature.
Here we will see how all the other numeric features, not just
Price, change with each categorical feature by summarizing the numeric features across the classes. We use the Dataframe’s groupby function to group the data by a category and calculate a metric (such as mean, median, min, std, etc) across the various numeric features.
For only the 3 categorical features with less than 10 classes, we group the data, then calculate the
mean across the numeric features. We use
display() which results to a cleaner table than
print().
for column in data.select_dtypes(include='object'): if data[column].nunique() < 10: display(data.groupby(column).mean())
We get to compare the
Type,
Method and
Regionname classes across the numeric features to see how they are distributed.
Relationships between numeric features and other numeric features
10. Correlations matrix for the different numerical features
A correlation is a value between -1 and 1 that amounts to how closely values of two separate features move simultaneously. A positive correlation means that as one feature increases the other one also increases, while a negative correlation means one feature increases as the other decreases. Correlations close to 0 indicate a weak relationship while closer to -1 or 1 signifies a strong relationship.
Image from edugyan.in
We will use
df.corr() to calculate the correlations between the numeric features and it returns a DataFrame.
corrs = data.corr() corrs
This might not mean much now, so let us plot a heatmap to visualize the correlations.
11. Heatmap of the correlations
We will use a Seaborn heatmap to plot the grid as a rectangular color-coded matrix. We use
sns.heatmap(corrs, cmap=’RdBu_r’,annot=True).
The
cmap=‘RdBu_r’ argument tells the heatmap what colour palette to use. A high positive correlation appears as dark red and a high negative correlation as dark blue. Closer to white signifies a weak relationship. Read this nice tutorial for other color palettes.
annot=True includes the values of the correlations in the boxes for easier reading and interpretation.
plt.figure(figsize=(10,8)) sns.heatmap(corrs, cmap='RdBu_r', annot=True) plt.show()
Heatmap by author
What to look out for:
- Strongly correlated features; either dark red (positive) or dark blue(negative).
- Target variable; If it has strong positive or negative relationships with other features.
We note that
Rooms,
Bedrooms2,
Bathrooms, and
Price have strong positive relationships. On the other hand,
Price, our target feature, has a slightly weak negative correlation with
YearBuilt and an even weaker negative relationship with
Distance from CBD.
In this article, we explored the Melbourne dataset and got a high-level understanding of the structure and its features. At this stage, we do not need to be 100% comprehensive because in future stages we will explore the data more elaborately. You can get the full code on Github here. I will be uploading the dataset’s cleaning concepts soon.
Bio: Susan Maina is passionate about data, machine learning enthusiast, writer at Medium.
Original. Reposted with permission.
Related:
- Powerful Exploratory Data Analysis in just two lines of code
- Pandas Profiling: One-Line Magical Code for EDA
- Statistical and Visual Exploratory Data Analysis with One Line of Code | https://www.kdnuggets.com/2021/03/11-essential-code-blocks-exploratory-data-analysis.html | CC-MAIN-2021-25 | refinedweb | 2,186 | 57.06 |
bugfix: local names are now freed correctly even with quotations.
1: \ A powerful locals implementation 2: 3: \ Copyright (C) 1995,1996,1997,1998,2000,2003,2004,2005:: :noname ( -- ) 575: locals-mem-list @ free-list 576: 0 locals-mem-list ! ; 577: is free-old-local-names 578: 579: : locals-;-hook ( sys addr xt sys -- sys ) 580: def? 581: 0 TO locals-wordlist 582: 0 adjust-locals-size ( not every def ends with an exit ) 583: lastcfa ! last ! 584: DEFERS ;-hook ; 585:: 599: : (then-like) ( orig -- ) 600: dead-orig = 601: if 602: >resolve drop 603: else 604: dead-code @ 605: if 606: >resolve set-locals-size-list dead-code off 607: else \ both live 608: over list-size adjust-locals-size 609: >resolve 610: adjust-locals-list: 655: ' locals-:-hook IS :-hook 656: ' locals-;-hook IS ;-hook 657: 658: 659: ' (then-like) IS then-like 660: ' (begin-like) IS begin-like 661: ' (again-like) IS again-like 662: ' (until-like) IS until-like 663: ' (exit-like) IS exit-like: 704: : (local) ( addr u -- ) \ local paren-local-paren 705: \ a little space-inefficient, but well deserved ;-) 706: \ In exchange, there are no restrictions whatsoever on using (local) 707: \ as long as you use it in a definition 708: dup 709: if 710: nextname POSTPONE { [ also locals-types ] W: } [ previous ] 711: else 712: 2drop 713: endif ; 714: 715: : >definer ( xt -- definer ) \ gforth!}. 720: dup >does-code 721: ?dup-if 722: nip 1 or 723: else 724: >code-address 725: then ; 726: 727: : definer! ( definer xt -- ) \ gforth 728: \G The word represented by @var{xt} changes its behaviour to the 729: \G behaviour associated with @var{definer}. 730: over 1 and if 731: swap [ 1 invert ] literal and does-code! 732: else 733: code-address! 734: then ; 735: 736: :noname 737: ' dup >definer [ ' locals-wordlist ] literal >definer = 738: if 739: >body ! 740: else 741: -&32 throw 742: endif ; 743: :noname 744: comp' drop dup >definer 745: case 746: [ ' locals-wordlist ] literal >definer \ value 747: OF >body POSTPONE Aliteral POSTPONE ! ENDOF 748: \ !! dependent on c: etc. being does>-defining words 749: \ this works, because >definer uses >does-code in this case, 750: \ which produces a relocatable address 751: [ comp' some-clocal drop ] literal >definer 752: OF POSTPONE laddr# >body @ lp-offset, POSTPONE c! ENDOF 753: [ comp' some-wlocal drop ] literal >definer 754: OF POSTPONE laddr# >body @ lp-offset, POSTPONE ! ENDOF 755: [ comp' some-dlocal drop ] literal >definer 756: OF POSTPONE laddr# >body @ lp-offset, POSTPONE 2! ENDOF 757: [ comp' some-flocal drop ] literal >definer 758: OF POSTPONE laddr# >body @ lp-offset, POSTPONE f! ENDOF 759: -&32 throw 760: endcase ; 761: interpret/compile: TO ( c|w|d|r "name" -- ) \ core-ext,local 762: 763: : locals| ( ... "name ..." -- ) \ local-ext locals-bar 764: \ don't use 'locals|'! use '{'! A portable and free '{' 765: \ implementation is compat/anslocals.fs 766: BEGIN 767: name 2dup s" |" str= 0= 768: WHILE 769: (local) 770: REPEAT 771: drop 0 (local) ; immediate restrict | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/glocals.fs?sortby=rev;f=h;only_with_tag=MAIN;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.67 | CC-MAIN-2021-17 | refinedweb | 489 | 51.58 |
I have this program that works by asking the user to determine what size box they would like displayed. It asks 7 times.
What I need to do is modify it so it just prints the output without asking the user. (that's what happens when you don't read the assignment thoroughly!)
The output should say:
A box of 3 is shown below:
* * *
* * * (without the * in the middle)
* * *
It;s supposed to display boxes sized 5, 4, 3, 2, 1, then error messages for 0 and -1.
I got the code working but now I don't know how to change it to just display everything without asking the user to specify the size.
sorry if this is hard to read...everything moved when I pasted it.sorry if this is hard to read...everything moved when I pasted it.Code:#include <iostream> #include <cmath> using namespace std; int centspace(); int counter(); //Functions used ... void instructions (); //User instructions int box (); //------------------------------------------------------- int main () { instructions (); box (); box (); box (); box (); box (); box (); box (); cout << endl; return 0; } //-------------------------------------------------- int box () { int size; cout << "enter a number: "; cin >> size; if ((size <= 0) || (size >= 40)) { cout << "It is not possible to print a box of size " << size << endl; } else { for (int counter = 1; counter <= size; counter++) cout << "* "; cout << endl; if (size > 2) { for (int counter = 1; counter <= (size-2); counter++) { cout << "*"; for (int space = 1; space <= (size-2); space++) cout << " "; cout << " *" << endl; } } if (size > 1) { for (int counter = 1; counter <= size; counter++) { cout << "* "; } cout << endl; } } return 0; }
Any point in the right direction would help me tremendously. Thanks! | https://cboard.cprogramming.com/cplusplus-programming/45929-help-modifying-program.html?s=68899c12e2656b972f4c1362bfa4e647 | CC-MAIN-2020-16 | refinedweb | 263 | 75.54 |
Learning Resources for Software Engineering Students »
Author: Thenaesh Elango
Table of Contents
Haskell is a purely functional programming language with strong, static, inferred typing.
While Haskell has its roots in academia, its emphasis on purity and side-effect-free computation makes it a valuable asset in software engineering contexts. Programs written in Haskell tend to be easy to test, refactor and debug, with the compiler usually catching all bugs before the program can even be compiled and run. Consequently, Haskell codebases are extraordinarily stable.
Here's an example of a Haskell program that reads a string of numbers, prints
the sum of the numbers and repeats the process until the string
"quit" is
entered. This shall serve as our Hello World.
-- the entry point of the program main :: IO () main = do str <- getLine if str == "quit" then return () else do let sumOfNumbers = sumAllNumbersInString str putStrLn $ show sumOfNumbers main sumAllNumbersInString :: String -> Int sumAllNumbersInString str = sumAll $ extractInts $ tokenize str -- sums up a list of integers using a higher-order function (the left fold) sumAll :: [Int] -> Int sumAll = foldl (+) 0 -- convert each string of digits in a list to an actual integer extractInts :: [String] -> [Int] extractInts = fmap read -- split string by spaces using a built-in function tokenize :: String -> [String] tokenize = words
Haskell is widely used in a whole range of industries, including banks, financial companies, technology companies and engineering companies use Haskell in a variety of systems. A comprehensive list may be found here.
This tutorial, in general, assumes a system-wide installation of the Haskell Platform. This is primarily for simplicity. It is perfectly acceptable to write small programs or code not intended for production in this manner.
When using Haskell in an actual project, however, it is strongly-recommended to use Stack. Not doing so may cause dependency management to become a nightmare.
For new users, Haskell may be quickly and easily installed by downloading the Haskell Platform for their respective operating systems. The Haskell Platform contains many common and important Haskell libraries, in addition to the Glasgow Haskell Compiler (GHC).
At the time of writing, the Haskell Platform has binaries available for all common operating systems, and many uncommon ones as well.
For Haskell projects of significant size, it may be necessary to control the exact versions of the compiler and libraries used. For such use cases, the system-wide installation method above may prove unwieldy and inadequate. In cases like these, it may be preferable to have an entire Haskell environment just for that project, together with a curated set of libraries.
In such a scenario, Stack may come in handy. Stack is a package manager of sorts for Haskell, similar to NPM. Installation instructions may be found in the Stack Documentation, and is fairly standard.
A new Stack project may be created and set up with the following:
# create the project skeleton stack new ${PROJECT_NAME} # go into the project source directory cd ${PROJECT_NAME} # install GHC for the project stack setup # compile the project stack build # run the project executable stack exec ${PROJECT_NAME}-exe
The command
stack new is used to create a new project, which contains a
skeleton already set up. This skeleton includes a
${PROJECT_NAME}.cabal file,
which contains nearly the entire configuration for the project (compiler/library
versions, modules to be exposed, build targets, etc), and is best thought of as
a sort of
package.json or
Gemfile for Stack.
The command
stack setup downloads and installs GHC. Stack installs GHC
versions into an isolated location in a user's home directory, and does not add
them to the system path. The version used for any particular project depends on
the setting in the project's
${PROJECT_NAME}.cabal file.
The commands
stack build and
stack exec are used to build and run the
project. The executable name for a project named Project is
Project-exe. This
name is configurable in
Project.cabal.
The rest of the Stack documentation may be found in the official guide.
The command
ghci may be used to invoke the GHC interpreter. This launches an
REPL where
Haskell code can be entered and evaluated interactively. This is a very useful
tool when first learning Haskell, and also when debugging code that fails to
compile.
The command
ghc may be used to compile Haskell code down to machine code. The
invocation of
ghc is very similar to that of
gcc.
When using Stack, simply prefix the commands with
stack.
Haskell is statically typed, meaning that every variable binds to a value of a specified type. Haskell is also strongly-typed, meaning that every value has a well-defined type.
We specify types explicitly by postfixing the variable names with the type.
a :: Int a = 5 -- unbounded integer type, similar to Java BigInt b :: Integer b = product [1..1000] -- this is the factorial of 1000 pi :: Double pi = 3.141592654
Haskell has very powerful type inference engine, so it is possible to omit the type definitions in most cases.
a = 5
Functions, which are just values, have types too. It is considered good practice in Haskell to specify types for toplevel functions, as a form of documentation, even though the compiler is likely able to infer types.
-- input: x of type Double -- output: x * x of type Double square :: Double -> Double square x = x * x -- computes the hypotenuse of a right triangle given the other two sides hypotenuse :: Double -> Double -> Double hypotenuse adj opp = sqrt (square adj + square opp)
If the above syntax is confusing and the comments insufficient, the reader may wish to consult the detailed introduction to Haskell syntax here.
The type definition for
square is rather obvious. But the type definition of
hypotenuse is a little strange. One would expect
(Double, Double) -> Double)
instead of
Double -> Double -> Double. The reason is that functions in Haskell
are curried, so a two-parameter
function can be called with a single argument, with a one-parameter function
(that takes in the remaining argument and produces the value) being returned.
(Double, Double) -> Double is actually a function that takes in a single
2-tuple parameter, which is different from a function that takes in two parameters.
The
-> binds to the right, so
Double -> Double -> Double may be written as
Double -> (Double -> Double) (a function that takes a double and
returns a function that takes a double and returns a double).
Calling
hypotenuse 3 4 is also the same as calling
(hypotenuse 3) 4,
as function application binds to the left.
We may go even further with currying, by fixing some parameters in the function:
-- hypotenuse of a right triangle whose adjacent side is restricted to 3 hypotenuseWithAdjacent3 :: Double -> Double hypotenuseWithAdjacent3 = hypotenuse 3
This clearly illustrates how currying can be used to reuse and partially specialise code as needed. This idiom comes in handy very often in Haskell, as will be seen later.
It may be of interest to note that all functions in Haskell take in at most one parameter. The illusion of multi-parameter functions is created by currying and left-binding function calls.
It is possible to create custom data types, either from nothing or from existing types.
data TrafficSignal = Red | Amber | Green -- define some values of type TrafficSignal, all type-inferred redLight = Red amberLight = Amber greenLight = Green
The
TrafficSignal type is an example of creating data types from nothing.
We call
Red,
Amber and
Green the value constructors and
TrafficSignal
itself the type constructor. In this case, a
TrafficSignal has 3 possible
values,
Red,
Amber or
Green.
Both type and value constructors must start with a capital letter.
We make use of types in functions by pattern matching on the value constructors. It is necessary to pattern match on all the value constructors; omitting any will cause the compiler to complain of non-exhaustive pattern matches.
makeTrafficDecision :: TrafficSignal -> String -- leaving any of these out will cause the compiler to complain makeTrafficDecision Red = "Stop" makeTrafficDecision Amber = "Carefully Proceed" makeTrafficDecision Green = "Go"
It is also possible to create data types that encapsulate/contain other data types. The value constructors in this case take parameters instead of being bare. Pattern matching is done by "expanding" the value constructor.
data HttpRequest = Get String | Post String handleRequest :: HttpRequest -> String -- the ++ denotes string concatenation in this context handleRequest (Get string) = "Get request performed on " ++ string -- we use _ to denote that we don't care about the actual value handleRequest (Post _) = "Post request not supported"
There is also an additional way to declare data types. Suppose we had a C++ class like so:
// we are omitting trivial details like constructors class Box { double length; double breadth; double height; double density; public: double getVolume() { return this->length * this->breadth * this->height; } double getMass() { return this->density * this->getVolume(); } };
We could certainly represent a
Box as an algebraic data type as follows:
-- NOTE: a value constructor can have the same name as the type constructor data Box = Box Double Double Double Double
But we are missing key information here. Which
Double stands for which
attribute? In situations like these, we can use Haskell's record syntax:
-- define box as a record type data Box = Box { length :: Double, breadth :: Double, height :: Double, density :: Double } getVolume :: Box -> Double getVolume (Box { length = l, breadth = b, height = h }) = l * b * h getMass :: Box -> Double getMass box = getVolume box * density box silverBox = Box { length = 5, breadth = 10, height = 15, density = 10.5 } goldBox = Box 5 10 15 19.3 -- we can still use normal construction by parameter order
There are a few things to note here, other than the syntax itself. When pattern
matching on a record type, we may omit any parameters we do not need (we do not
even need to specify
_). We may also extract values from the record type by
treating the record parameter names as functions from the record type to the
parameter type. For instance,
density in the above example is actually a
Box -> Double function. Doing
density silverBox will give the value
10.5.
Consider the division operator on
Double. We may be tempted to define it with
the type
Double -> Double -> Double, but the result may be undefined when
dividing by zero. Here's a first stab at a solution to remedy this:
-- represents a value that may or may not exist data MaybeDouble = Undefined | Defined Double divide :: Double -> Double -> MaybeDouble divide _ 0 = Undefined divide x y = Defined (x / y)
This ensures that division by zero returns a clearly-defined result instead of something weird.
Now suppose we want to send a HTTP request and retrieve the response data. This response data may not exist as the server may refuse to return the data. We can try to solve the problem in the following manner:
data MaybeResponse = NoResponse | GotResponse HttpResponse makeRequest :: HttpRequest -> MaybeResponse -- implementation details irrelevant
We have
MaybeDouble and
MaybeResponse, both of which have a common pattern:
they represent possible failure of computation. Naturally, we may wish to abstract
this out. But all the means of abstraction available to us thus far cannot be
used, as we wish to abstract on types rather than values.
For this purpose, Haskell supports type parameters, much like how C++ has templates and Java has generics.
We define the following abstraction of failing computations:
data Maybe t = Nothing | Just t divide :: Double -> Double -> Maybe Double divide _ 0 = Nothing divide x y = Just (x / y) makeRequest :: HttpRequest -> Maybe Response -- implementation details irrelevant
Note that we introduce an additional parameter
t on the left side of the definition.
This is known as a type parameter, and must always be lowercase. This parameter
can then be used in the value constructors as a placeholder for any type that
should be there.
The use of type parameters in this way is similar to the use of generics in Java.
We may think of
Maybe t as
Optional<T>, if that helps to understand the role
of
t.
Note that there can be more than one type parameter. An example is
Either,
which represents the result of a computation that returns values of different
types on success or failure:
data Either a b = Left a | Right b divide :: Double -> Double -> Either String Double divide _ 0 = Left "Attempt to divide by zero!" divide x y = Right (x / y)
Type constructors can be curried just like regular functions or value constructors.
Therefore,
Either String Double is a concrete type, while
Either String is
a type constructor that takes in the remaining type.
Maybe and
Either are both defined in the Haskell prelude library.
We can define a data type in terms of itself. Consider, for instance, a tree. A tree can be thought of as either an empty tree, or a node with a left subtree and right subtree attached. We encode it like so:
data Tree t = EmptyTree | Node t (Tree t) (Tree t)
Another classic inductive data type is the singly-linked list. The list is either an empty list or the first element together with the rest of the list. While not canonical, this is a very common representation of lists in the functional programming world:
data List t = EmptyList | Element t (List t)
This representation of lists is actually exactly how traditional lists are defined in Haskell, just with different names and notation as will be seen later.
We are now poised to enter the world of actual functional programming in Haskell.
A function may be defined in one of several ways. We illustrate the various syntaxes for defining a function below, with more details here if needed:
sumOfSquares :: Double -> Double -> Double -- standard definition sumOfSquares x y = (x * x) + (y * y) -- lambda function sumOfSquares = \x y -> (x * x) + (y * y) fizzBuzz :: Int -> Either String Int -- the horrible, disgusting, but still perfectly correct way fizzBuzz x = case x `mod` 15 == 0 of True -> Left "fizzbuzz" False -> case x `mod` 3 == 0 of True -> Left "fizz" False -> case x `mod` 5 == 0 of True -> Left "buzz" False -> Right x -- far more elegant way using guard patterns fizzBuzz x | x `mod` 15 = Left "fizzbuzz" | x `mod` 3 = Left "fizz" | x `mod` 5 = Left "buzz" | otherwise = Right x
Recursion is one of the fundamental themes of functional programming. It is the ability of a function to call itself.
-- Time: O(n) -- Space: O(n) factorial :: Integer -> Integer factorial 0 = 1 factorial n = n * factorial (n - 1) -- Time: O(2^n) -- Space: O(n), may vary due to lazy evaluation fibonacci :: Integer -> Integer fibonacci 0 = 0 fibonacci 1 = 1 fibonacci n = fibonacci (n - 2) + fibonacci (n - 1)
While Haskell has no primitive loop structures, looping can be simulated by recursion. While attempting this in languages in C may cause a stack overflow, Haskell avoids this via tail-call optimisation, which can be applied to recursive calls that meet certain requirements.
-- Time: O(n) -- Space: O(1) factorial :: Integer -> Integer factorial = factorial' 1 where factorial' p 0 = p factorial' p n = factorial' (p * n) (n - 1) -- Time: O(n) -- Space: O(1) fibonacci :: Integer -> Integer fibonacci 0 = 0 fibonacci 1 = 1 fibonacci n = fibonacci' 0 1 n where fibonacci a _ 0 = a fibonacci' a b n = fibonacci' b (a + b) (n - 1)
We can safely omit the types in the inner function definitions due to type
inference. Also note how we freely use currying in the
factorial definition.
As described earlier, a list is an inductive data type, defined as either the empty list or an element concatenated with the rest of the list. The actual list data type is
data [] t = [] | (:) t ([] t)
where
: is an infix value constructor.
IMPORTANT: Infix Functions
Any function (a value constructor is really just a function) that takes in two parameters whose name consists of nothing but symbols is infix by default.
An infix function like
+may be used in prefix form by enclosing in parentheses. For instance,
1 + 1is the same as
(+) 1 1.
In the type definition, the prefix form must be used i.e.
(+) :: Int -> Int -> Int.
In the function definition, either is acceptable.
We will use this concept freely from now on.
Here are several ways to define a list
xs :: [Int] containing 2,4,6,8 in that order:
-- the crazy way, using prefix notation directly from the list definition xs = (:) 2 ((:) 4 ((:) 6 ((:) 8 []))) -- using infix syntax for (:), still annoying to write xs = 2:(4:(6:(8:[]))) -- taking advantage of binding rules for (:), noiseless and easier to understand at a glance xs = 2:4:6:8:[] -- using varying amounts of list syntactic sugar provided by the compiler xs = 2:4:6:[8] xs = 2:4:[6,8] xs = 2:[4,6,8] xs = [2,4,6,8]
The last representation is most commonly used, while the second last is often used when pattern matching on lists. The rest are almost never seen in practice. However, it is hoped that this pedantic exercise helps the reader understand the true nature of lists: an ordinary inductive data type with some compiler syntactic sugar tacked on.
List processing is a very important part of elementary functional programming. This is due to the fact that lists can store large amounts of data, and it is very easy to define powerful abstractions to slice and dice that data in ways typically unknown in imperative programming.
One common idiom is to loop over a list and aggregate their values.
It is possible to run over a list and sum their values recursively like so:
sumList :: [Int] -> Int sumList [] = 0 sumList (x:xs) = x + sumList xs
Note the infix pattern match
(x:xs) as opposed to
((:) x xs). What if we wish
to take the product of the elements instead of a sum? Then we would write:
prodList :: [Int] -> Int prodList [] = 1 prodList (x:xs) = x * prodList xs
It is clear that some abstraction is in order here. The functions are almost identical except for the aggregating function used and the initial value (0 for sum, 1 for product). We can write a generalised aggregating function:
-- 1st parameter is the aggregating function (e.g. (+) or (*)) -- 2nd parameter is the initial value -- 3rd parameter is the list to aggregate aggregate :: (Int -> Int -> Int) -> Int -> [Int] -> Int aggregate _ initial [] = initial aggregate op initial (x:xs) = op x (aggregate op initial xs)
This is better, but perhaps we could generalise this even further beyond
Int.
We then arrive at the following, by simply changing the type signature:
-- 1st parameter is the aggregating function (e.g. (+) or (*)) -- 2nd parameter is the initial value -- 3rd parameter is the list to aggregate aggregate :: (a -> b -> b) -> b -> [a] -> b aggregate _ initial [] = initial aggregate op initial (x:xs) = op x (aggregate op initial xs)
This function is known as
foldl in the Haskell prelude library, and there is
also a variant called
foldr that does the aggregation from the right instead.
One may wish to take in a list, transform every element in the list, and output the resulting list. This is known as a map, and may be defined as:
map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = (f x):(map f xs)
The type definition itself contains a wealth of information. The
map function
takes in a "transformer", the list to be transformed, and return the transformed
list. An example of its usage would be:
-- xs is [1,4,9,16] xs = map (\x -> x * x) [1,2,3,4]
One may also wish to remove certain elements, that fail some predicate, from a given list. This is known as a filter:
filter :: (t -> Bool) -> [t] -> [t] filter _ [] = [] filter predicate (x:xs) | predicate x == True = x:xs | otherwise = xs
This example uses guard patterns. An example of using filter would be:
-- xs is [2,4] xs = filter (\x -> x `mod` 2 == 0) [1,2,3,4]
It is left as an exercise for the reader to implement
map and
filter
in terms of
foldl (or
aggregate as defined above, which is the same).
Recursion is a natural fit with inductive data types other than lists. One example would be finding an element in a binary tree:
find :: Tree Int -> Int -> Bool find EmptyTree _ = False find (Node x left right) target | x == target = True | x < target = find left target | x > target = find right target
The above runs in O(log n) as long as the tree is balanced.
Typeclasses are essentially contracts/constraints imposed on types. They are similar to how Java interfaces are constraints imposed on Java classes. When used properly, they are an extremely powerful tool in helping to structure code.
-- "class" here has nothing to do with OOP class Eq t where (==) :: t -> t -> Bool (!==) :: t -> t -> Bool -- this ensures that we don't have to define (!==) separately a != b = not (a == b)
We have just defined a typeclass called
Eq. As its name probably suggests,
this typeclass is used when we wish to define the meaning of equality on types.
We then instantiate the typeclass with the
TrafficSignal type, like so:
instance Eq TrafficSignal where -- note that these are infix function DEFINITIONS -- we can define infix operators directly in infix notation Red == Red Amber == Amber Green == Green
We have thus defined
(==) completely for
TrafficSignal. Note that
(!=)
now comes for free, since we have defined it in terms of
(==) in the typeclass
itself.
Here's another example:
instance Eq (List t) where EmptyList == EmptyList (Element x xs) == (Element y ys) = (x == y) && (xs == ys)
Here, we define the equality of a list in terms of its underlying elements.
This seems reasonable. However, running this program will give an error. This
is because we are attempting to compare the underlying elements (of type
t)
using
(==), which is not guaranteed to be defined on
t.
The solution, in this case, is to enforce a typeclass constraint prerequisite
on
t by writing:
instance (Eq t) => Eq (List t) where -- as before
Here is an example of
Eq being defined on
Trees:
instance (Eq t) => Eq (Tree t) where EmptyTree == EmptyTree (Node x left right) == (Node x' left' right') = (x == x') && (left == left') && (right == right') tree1 = Node 1 (Node 2 EmptyTree) (Node 3 EmptyTree) tree2 = Node 1 (Node 2 EmptyTree) EmptyTree tree3 = Node 1 (Node 2 EmptyTree) EmptyTree -- some experiments tree1 == tree2 -- False tree2 == tree3 -- True tree3 != tree1 -- True
We present another common typeclass called
Ord, which defines order for a type:
-- anything that instantiates Ord must also instantiate Eq -- this makes the typeclass definitions simpler as (==) is already provided and can be used class (Eq t) => Ord t where -- the only one we actually need to implement when instantiating (<) :: t -> t -> Bool -- we predefine these and can then get them all for free (>) :: t -> t -> Bool a > b = not ((a < b) || (a == b)) (<=) :: t -> t -> Bool a <= b == (a < b) || (a == b) (>=) :: t -> t -> Bool a >= b = not (a < b)
Consider the following function to check if the elements in the following list are all in ascending order:
isAscending :: [t] -> Bool isAscending [] = True -- handle 0-element lists isAscending (x:[]) = True -- handle 1-element lists isAscending (x:y:xs) = (x < y) && isAscending (y:xs) -- recursive case
This function seems reasonable, except for one minor detail: we (and the compiler)
are not sure if
t can be compared using
(<)!. To remedy this, we need to
explicitly state that
t instantiates
Ord, thereby allowing the use of
(<).
We do this by adding the constraint in the function type definition:
isAscending :: (Ord t) => [t] -> Bool
We can now try out the
isAscending function:
isAscending [1,2,4,3] -- False isAscending [1,2,3,4,5] -- True isAscending [] -- True
Up to this point, we have been instantiating typeclasses with concrete types,
such as
TrafficSignal and
Tree t. It is also possible to instantiate
typeclasses with parameterized type constructors like
Tree and
List.
Consider the following typeclass
Container that is instantiated by types that
have some notion of constituent elements and size. For instance, a
List has a
length and contains elements of some type. A
Tree has nodes and a size (number
of nodes). The length is independent of type of element contained within.
class Container s where -- t is an arbitrary unconstrained type size :: s t -> Int
We can instantiate
Container with
Tree and
List. These are parameterized
type constructors, not concrete types. We can even instantiate with
Maybe.
instance Container Tree where size EmptyTree = 0 size (Node _ left right) = 1 + size left + size right instance Container List where size EmptyList = 0 size (Element _ restOfList) = 1 + size restOfList instance Container Maybe where size Nothing = 0 size (Just _) = 1
As an exercise, the reader may wish to redefine the size of a
Tree to mean
"height of tree" rather than "number of nodes". It is necessary to instantiate
Container with
Tree differently to achieve this. The function
max :: (Ord a) => a -> a -> a may come in handy (
Int is an instance of
Ord).
Consider the
map function previously defined. The type
of
map is
(a -> b) -> [a] -> [b], which means that it operates only on lists.
We may imagine extending maps to
Trees and
Maybes in the following manner:
map :: (a -> b) -> Tree a -> Tree b map :: (a -> b) -> Maybe a -> Maybe b
The two type definitions above look very similar and suggest a generalization: types that can be mapped over. We call such types functors, and can represent their behaviour with a typeclass.
class Functor f where -- f is a type constructor that takes in one type parameter fmap :: (a -> b) -> f a -> f b instance Functor Tree where fmap _ EmptyTree = EmptyTree fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right) instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just x) = Just (f x)
We can then map over values of any functor:
sq x = x * x fmap sq (Just 5) -- returns Just 25 fmap sq Nothing -- returns Nothing fmap sq (Node 1 (Node 2 EmptyTree) (Node 3 (Node 4 EmptyTree) EmptyTree)) -- returns (Node 1 (Node 4 EmptyTree) (Node 9 (Node 16 EmptyTree) EmptyTree))
More information about functors, including the functor laws, may be found here.
An applicative functor is a functor that allows for a more advanced type of
mapping. We shall jump straight into the (abridged) typeclass definition and the
example of
Maybe as an applicative functor:
class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b -- generalized map function instance Applicative Maybe where pure x = Just x Nothing <*> _ = Nothing _ <*> Nothing = Nothing Just f <*> Just x = Just (f x)
Applicative functors have the concept of lifting, embodied in
pure, where
a value is taken and placed in the context of a functor. For instance, in the
context of
Maybe,
pure 5 returns the value
Just 5.
Applicative functors allow a more general form of mapping, where it is possible to use an N-parameter function to map over N functors. To understand the value of this, consider the following code:
euclideanDistance :: Double -> Double -> Double -> Double euclideanDistance x y z = sqrt ((x * x) + (y * y) + (z * z)) (pure euclideanDistance) <*> Just 1 <*> Just 2 <*> Just 3 -- returns Just 3.7416573867739413
The above code can be written with just
fmap in the ordinary
Functor class,
but will involve incredible contortions.
More information about applicative functors can be found
here. There is a
lot of additional functionality available in the
Applicative typeclass. We
have barely scratched the surface.
No Haskell tutorial will be complete without an introduction to the fabled monad. Monads have been described with various analogies, as well as with notorious phrases from category theory like "a monad is a monoid in the category of endofunctors".
None of these are useful for the software engineer, so we dispense with them and opt for just showing the code:
class (Applicative m) => Monad m where -- this function, called "bind", is at the heart of the monad (>>=) :: m a -> (a -> m b) -> m b -- we could actually just use pure, but return is here for historical reasons return :: a -> m a return = pure
A monad is essentially an applicative functor that allows for operations to be
chained together with a value carried in the background. To consider this, let
us consider the familiar case of
Maybe, which is a monad.
instance Monad Maybe where Nothing >>= _ = Nothing (Just x) >>= f = Just (f x) -- maybeSomeValue is Just 50 maybeSomeValue = Just 5 >>= (\x -> Just (x * x) >>= (\x -> Just (x + x)))
Essentially, the bind function allows for values carried inside the monad (which
is ultimately just a functor) to be extracted and passed into another computation.
This explanation may seem obtuse, but consider the same code, with some extracted
whitespace added and the
return function used:
maybeSomeValue = Just 5 >>= (\x -> Just (x * x) >>= (\x -> return (x + x)))
If the reader squints hard enough, this looks like an imperative program! It looks like the following is being done:
maybeSomeValue = do x <- Just 5 x <- Just (x * x) return (x + x)
The result of the imperative-looking code is exactly the same as that of the
original computation, if traced through. Using monads to provide an imperative
interface in a functional program is such a common pattern that the
do notation
was conceived as syntactic sugar to make writing such a pattern easier. That means
that the imperative-looking code is actually valid Haskell!
In addition to
Maybe, there are several other monads. A major example is the
IO monad, which allows external state to be encapsulated in the monad an interfaced
with in a manner familiar to imperative programmers.
Monads are a big topic, and additional resources are available:
IOand
STmonads provided | https://se-education.org/learningresources/contents/haskell/Haskell.html | CC-MAIN-2019-26 | refinedweb | 4,927 | 55.17 |
Full-text Search with Solr Last modified: March 26, 2017 by baeldung Persistence 1. Overview In this article, we’ll explore a fundamental concept in the Apache Solr search engine – full-text search. The Apache Solr is an open source framework, designed to deal with millions of documents. We’ll go through the core capabilities of it with examples using Java library – SolrJ. 2. Maven Configuration Given the fact that Solr is open source – we can simply download the binary and start the server separately from our application. To communicate with the server, we’ll define the Maven dependency for the SolrJ client: <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>6.4.2</version> </dependency> You can find the latest dependency here. 3. Indexing Data To index and search data, we need to create a core; we’ll create one named item to index our data. Before we do that, we need data to be indexed on the server, so that it becomes searchable. There are many different ways we can index data. We can use data import handlers to import data directly from relational databases, upload data with Solr Cell using Apache Tika or upload XML/XSLT, JSON and CSV data using index handlers. 3.1. Indexing Solr Document We can index data into a core by creating SolrInputDocument. First, we need to populate the document with our data and then only call the SolrJ’s API to index the document: SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", id); doc.addField("description", description); doc.addField("category", category); doc.addField("price", price); solrClient.add(doc); solrClient.commit(); Note that id should naturally be unique for different items. Having an id of an already indexed document will update that document. 3.2. Indexing Beans SolrJ provides APIs for indexing Java beans. To index a bean, we need to annotate it with the @Field annotations: public class Item { @Field private String id; @Field private String description; @Field private String category; @Field private float price; } Once we have the bean, indexing is straight forward: solrClient.addBean(item); solrClient.commit(); 4. Solr Queries Searching is the most powerful capability of Solr. Once we have the documents indexed in our repository, we can search for keywords, phrases, date ranges, etc. The results are sorted by relevance (score). 4.1. Basic Queries The server exposes an API for search operations. We can either call /select or /query request handlers. Let’s do a simple search: SolrQuery query = new SolrQuery(); query.setQuery("brand1"); query.setStart(0); query.setRows(10); QueryResponse response = solrClient.query(query); List<Item> items = response.getBeans(Item.class); SolrJ will internally use the main query parameter q in its request to the server. The number of returned records will be 10, indexed from zero when start and rows are not specified. The search query above will look for any documents that contain the complete word “brand1” in any of its indexed fields. Note that simple searches are not case sensitive. Let’s look at another example. We want to search any word containing “rand”, that starts with any number of characters and ends with only one character. We can use wildcard characters * and ? in our query: query.setQuery("*rand?"); Solr queries also support boolean operators like in SQL: query.setQuery("brand1 AND (Washing OR Refrigerator)"); All boolean operators must be in all caps; those backed by the query parser are AND, OR, NOT, + and – . What’s more, if we want to search on specific fields instead of all indexed fields, we can specify these in the query: query.setQuery("description:Brand* AND category:*Washing*"); 4.2. Phrase Queries Up to this point, our code looked for keywords in the indexed fields. We can also do phrase searches on the indexed fields: query.setQuery("Washing Machine"); When we have a phrase like “Washing Machine“, Solr’s standard query parser parses it to “Washing OR Machine“. To search for a whole phrase, we can only add the expression inside double quotes: query.setQuery("\"Washing Machine\""); We can use proximity search to find words within specific distances. If we want to find the words that are at least two words apart, we can use the following query: query.setQuery("\"Washing equipment\"~2"); 4.3. Range Queries Range queries allow obtaining documents whose fields are between specific ranges. Let’s say we want to find items whose price ranges between 100 to 300: query.setQuery("price:[100 TO 300]"); The query above will find all the elements whose price are between 100 to 300, inclusive. We can use “}” and “{” to exclude end points: query.setQuery("price:{100 TO 300]"); 4.4. Filter Queries Filter queries can be used to restrict the superset of results that can be returned. Filter query does not influence the score: SolrQuery query = new SolrQuery(); query.setQuery("price:[100 TO 300]"); query.addFilterQuery("description:Brand1","category:Home Appliances"); Generally, the filter query will contain commonly used queries. Since they’re often reusable, they are cached to make the search more efficient. 5. Faceted Search Faceting helps to arrange search results into group counts. We can facet fields, query or ranges. 5.1. Field Faceting For example, we want to get the aggregated counts of categories in the search result. We can add category field in our query: query.addFacetField("category"); QueryResponse response = solrClient.query(query); List<Count> facetResults = response.getFacetField("category").getValues(); The facetResults will contain counts of each category in the results. 5.2. Query Faceting Query faceting is very useful when we want to bring back counts of subqueries: query.addFacetQuery("Washing OR Refrigerator"); query.addFacetQuery("Brand2"); QueryResponse response = solrClient.query(query); Map<String,Integer> facetQueryMap = response.getFacetQuery(); As a result, the facetQueryMap will have counts of facet queries. 5.3. Range Faceting Range faceting is used to get the range counts in the search results. The following query will return the counts of price ranges between 100 and 251, gapped by 25: query.addNumericRangeFacet("price", 100, 275, 25); QueryResponse response = solrClient.query(query); List<RangeFacet> rangeFacets = response.getFacetRanges().get(0).getCounts(); Apart from numeric ranges, Solr also supports date ranges, interval faceting, and pivot faceting. 6. Hit Highlighting We may want the keywords in our search query to be highlighted in the results. This will be very helpful to get a better picture of the results. Let’s index some documents and define keywords to be highlighted: itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 100f); itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 300f); itemSearchService.index("hm0003", "Brand2 Ceiling Fan", "Home Appliances", 200f); itemSearchService.index("hm0004", "Brand2 Dishwasher", "Washing equipments", 250f); SolrQuery query = new SolrQuery(); query.setQuery("Appliances"); query.setHighlight(true); query.addHighlightField("category"); QueryResponse response = solrClient.query(query); Map<String, Map<String, List<String>>> hitHighlightedMap = response.getHighlighting(); Map<String, List<String>> highlightedFieldMap = hitHighlightedMap.get("hm0001"); List<String> highlightedList = highlightedFieldMap.get("category"); String highLightedText = highlightedList.get(0); We’ll get the highLightedText as “Home <em>Appliances</em>”. Please notice that the search keyword Appliances is tagged with <em>. Default highlighting tag used by Solr is <em>, but we can change this by setting the pre and post tags: query.setHighlightSimplePre("<strong>"); query.setHighlightSimplePost("</strong>"); 7. Search Suggestions One of the important features that Solr supports are suggestions. If the keywords in the query contain spelling mistakes or if we want to suggest to autocomplete a search keyword, we can use the suggestion feature. 7.1. Spell Checking The standard search handler does not include spell checking component; it has to be configured manually. There are three ways to do it. You can find the configuration details in the official wiki page. In our example, we’ll use IndexBasedSpellChecker, which uses indexed data for keyword spell checking. Let’s search for a keyword with spelling mistake: query.setQuery("hme"); query.set("spellcheck", "on"); QueryResponse response = solrClient.query(query); SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse(); Suggestion suggestion = spellCheckResponse.getSuggestions().get(0); List<String> alternatives = suggestion.getAlternatives(); String alternative = alternatives.get(0); Expected alternative for our keyword “hme” should be “home” as our index contains the term “home”. Note that spellcheck has to be activated before executing the search. 7.2. Auto Suggesting Terms We may want to get the suggestions of incomplete keywords to assist with the search. Solr’s suggest component has to be configured manually. You can find the configuration details in its official wiki page. We have configured a request handler named /suggest to handle suggestions. Let’s get suggestions for keyword “Hom”: SolrQuery query = new SolrQuery(); query.setRequestHandler("/suggest"); query.set("suggest", "true"); query.set("suggest.build", "true"); query.set("suggest.dictionary", "mySuggester"); query.set("suggest.q", "Hom"); QueryResponse response = solrClient.query(query); SuggesterResponse suggesterResponse = response.getSuggesterResponse(); Map<String,List<String>> suggestedTerms = suggesterResponse.getSuggestedTerms(); List<String> suggestions = suggestedTerms.get("mySuggester"); The list suggestions should contain all words and phrases. Note that we have configured a suggester named mySuggester in our configuration. 8. Conclusion This article is a quick intro to the search engine’s capabilities and features of Solr. We touched on many features, but these are of course just scratching the surface of what we can do with an advanced and mature search server such as Solr. The examples used here are available as always, over on GitHub. An intro SPRING data, JPA andTransaction Semantics Details with JPAGet Persistence right with Spring Download | http://www.baeldung.com/full-text-search-with-solr | CC-MAIN-2017-26 | refinedweb | 1,557 | 51.75 |
Digital_0<<
Want to make your own dynamic, digital, Raspberry Pi-powered talking point? Read on.
Prepare Your Pi
You’ll need for this project, so if necessary download and write to your SD card How to Install an Operating System on a Raspberry Pi How to Install an Operating System on a Raspberry Pi Here's how to install an OS on your Raspberry Pi and how to clone your perfect setup for quick disaster recovery. Read More . Once you’ve done that, take the time to setup wireless networking How to Set Up Wi-Fi and Bluetooth on the Raspberry Pi 3 How to Set Up Wi-Fi and Bluetooth on the Raspberry Pi 3 Unlike older models, the Raspberry Pi 3 and 4 have Wi-Fi and Bluetooth capabilities. Here's how to set them up properly. Read More and enable
!
Explore more about: Raspberry Pi, Reddit.
Hope someone is still watching this thread. I was able to get it to work but now after a couple of refreshes it dies with this error:
File "ep_st.py", line 300 in main
f.write(template.substitute(img=img_url, text=witty_text))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 34: ordinal not in range(128)
From what I've searched (not a python guru by any means) is to change the encode to UTF-8. Not sure how to do that here.
Any help is appreciated.
This project depends on an older version of PRAW. Can you update your instructions to install PRAW via: sudo pip install praw==3.6?
Is there anyway to make the fullscreen.sh script run without setting it up to autostart. Whenever I try it returns this:
unclutter: could not open display
matchbox: can't open display! check your DISPLAY variable.
Midori - Cannot open display
I want to be able to run it thru crontab so I can have a different script run part of the day.
Did MDM's issue get resolved? I'm working my way through this tutorial and I'm getting the same error. Any assistance is greatly appreciated. I'm a bit of a noob.
raspberry pi 3.
This is frustrating as at present I can't remount the project as I'm working on something else.
Have you run it as python ep_st.py, or with sudo?
Is Python up to date on your system?
The system used in preparing the tutorial was running an older image of Raspbian but on a Raspberry Pi 3, if this is of any help to anyone. As soon as I can get the current project finished, I'll start working through this again.
I ran it as the tutorial states. python ep_st.py
Apologies as I'm a total noob, first pi, first project. I do understand some command lines, I'm just not very familiar with linux or python. Thank you for looking into this.
Raspberrypi 3 Model B. I'm not sure if python is up to date with the system or not. Any advice on how to check?
The pi says it's running python v 2.7.
After digging around, if I type in python --version, I get 2.7.9
If I type in python3 --version, I get 3.4.2
neither will allow the script to run, even if I do python3 ep_st.py
Issue resolved using the advice- "make sure you have the module installed with "sudo pip install configparser" or whatever the name is that it says you're missing."
Yes was all up to date, tried sudo as well
Sorry ignore last comment long day, the following command
python ep_st.py
Okay, what do you have on line 23? is this a line you've edited?
Did not edit that file at all, as i did not see any instruction to.
Line 23
import configparser
Fair enough. Really don't know why it wouldn't work unless there was a problem.
Have you tried re-downloading?
Have attempted on several different pi's
I'm having the same issue. Did you find a resolution?
I'm having the same issue, did you find a resolution?
Very sorry forgot to include that
When running this command
sudo nano /home/pi/Frame/ep_st.config
At what stage does this occur, mdm?
Getting an error
Traceback (most recent call last):
File "ep_st.py", line 23, in
import configparser
ImportError: No module named configparser | https://www.makeuseof.com/tag/showerthoughts-earthporn-make-inspiring-raspberry-pi-photo-frame/ | CC-MAIN-2019-39 | refinedweb | 740 | 76.01 |
In order to be able to do something useful with the output of a Dumbo program, you often need to index it first. Suppose, for instance, that you ran a program that computes JIRA issue recommendations on lots and lots of issues, saving the output to jira/recs on the DFS. If the HADOOP-1722 patch has been applied to your Hadoop build, you can then dump this output to a fairly compact typed bytes file recs.tb as follows:
$ /path/to/hadoop/bin/hadoop jar \ /path/to/hadoop/build/contrib/streaming/*.jar dumptb jira/recs > recs.tb
Such a typed bytes file isn’t very convenient for doing lookups though, since you basically have to go through the whole thing to find the recommendations corresponding to a particular issue. Keeping it completely in memory as a hash table might be an option if you have tons of RAM, but indexing it and putting only the index in memory can do the trick as well.
Here’s a very simple, but nevertheless quite effective, way of generating an index for a typed bytes file:
import sys import typedbytes infile = open(sys.argv[1], "rb") outfile = open(sys.argv[2], "wb") input = typedbytes.PairedInput(infile) output = typedbytes.PairedOutput(outfile) pos = 0 for key, value in input: output.write((key, pos)) pos = infile.tell() infile.close() outfile.close()
This Python program relies on the typedbytes module to read a given typed bytes file and generate a second one containing (key, position) pairs. More concretely, running it with the arguments recs.tb recs.tb.idx leads to an index file recs.tb.idx for recs.tb. If you put
file = open("recs.tb") input = typedbytes.PairedInput(file) index = dict(typedbytes.PairedInput(open("recs.tb.idx")))
in the initialization part of a Python program, you can then lookup the recommendations for a particular issuenr as follows:
file.seek(index[issuenr]) readnr, recs = input.read() if readnr != issuenr: raise ValueError("corrupt index")
When dealing with huge output files, you might have to use a second-level index on (a sorted version of) the index obtained in this way, but in many cases this simple approach gets the job done just fine. | https://dumbotics.com/tag/indexing/ | CC-MAIN-2019-22 | refinedweb | 366 | 58.28 |
This action might not be possible to undo. Are you sure you want to continue?
by Wikibooks contributors
the open-content textbooks collection
Developed on Wikibooks,
© Copyright 2004–2007,". Principal authors: Rod A. Smith (C) · Jonas Nordlund (C) · Jlenthe (C) · Nercury (C) · Ripper234 (C) Cover: C♯ musical note, by Mothmolevna (See naming) (GFDL) The current version of this Wikibook may be found at:
Contents
INTRODUCTION..........................................................................................04
Foreword............................................................................................................04 Getting Started..................................................................................................06
LANGUAGE BASICS.....................................................................................08
Syntax................................................................................................................08 Variables............................................................................................................11 Operators...........................................................................................................17 Data Structures.................................................................................................23 Control...............................................................................................................25 Exceptions.........................................................................................................31
CLASSES........................................................................................... ......33 .
Namespaces.......................................................................................................33 Classes...............................................................................................................35 Encapsulation....................................................................................................40
THE .NET FRAMEWORK.............................................................................42
.NET Framework Overview...............................................................................42 Console Programming.......................................................................................44 Windows Forms.................................................................................................46
ADVANCED OBJECT-ORIENATION CONCEPTS......................................................47
Inheritance........................................................................................................47 Interfaces...........................................................................................................49 Delegates and Events........................................................................................51 Abstract Classes................................................................................................54 Partial Classes...................................................................................................55 Generics.............................................................................................................56 Object Lifetime..................................................................................................59
ABOUT
THE BOOK.............................................................................. .........61
History & Document Notes...............................................................................61 Authors..............................................................................................................62 GNU Free Documentation License....................................................................63
and projects with strict reliability requirements. Anders Hejlsberg as Chief Engineer. library. Similar to Java. Developers can thus write part of an application in C# and another part in another . the language is open to implementation by other parties. Because of the similarities between C# and the C family of languages.NET languages rely on an implementation of the virtual machine specified in the Common Language Infrastructure. multiple types of polymorphism. Its strong typing helps to prevent many programming errors that are common in weakly typed languages. a developer with a background in object-oriented languages like C++ may find C# structure and syntax intuitive. it has features such as garbage collection that allow beginners to become proficient in C# more quickly than in C or C++. handles object references.NET initiative and subsequently opened its specification via the ECMA.g. which provides a large set of classes. projects implemented by individuals or large or small teams.NET Framework API. including ones for encryption. and separation of interfaces from implementations.NET languages). and graphics. combined with its powerful development tools. VB .NET). as well as Java. keeping the tools. That virtual machine manages memory. comes with an extensive class library. multi-platform support. and performs Just-In-Time (JIT) compiling of Common Intermediate Language code. Internet applications. The virtual machine makes C# programs safer 4 | C# Programming . C# and other . like Microsoft's Common Language Runtime (CLR). created C# as part of their . Other implementations include Mono and DotGNU.NET language (e.Chapter 1 1 F OREWORD live version · discussion · edit chapter · comment · report an error C # (pronounced "See Sharp") is a multi-purpose computer programming language suitable for all development needs. and supports exception handling. A large part of the power of C# (as with other . Testing frameworks such as NUnit make C# amenable to test-driven development and thus a good language for use with Extreme Programming (XP). Standard Microsoft. comes with the common . it is object-oriented. make C# a good choice for many types of software development projects: rapid application development projects. Introduction Although C# is derived from the C programming language. Thus. and objectoriented development model while only having to learn the new language syntax. Those features. TCP/IP socket programming. and generics.
0 version of C# includes such new features as generics. live version · discussion · edit chapter · comment · report an error Wikibooks | 5 .Foreword than those that must manage their own memory and is one of the reasons . Microsoft submitted C# to the ECMA standards group mid-2000. codenamed "Cool". Se microsoft-watch and hitmil. More like Java than C and C++.0 was released in late-2005 as part of Microsoft's development suite. partial classes. which could otherwise allow software bugs to corrupt system memory and force the operating system to halt the program forcibly with nondescript error messages. History Microsoft's original plan was to create a rival to Java. The 2. named J++ but this was abandoned to create C#. C# discourages explicit use of pointers. and iterators. C# 2.NET language code is referred to as managed code. Visual Studio 2005.
Net project page. or the C:\WINDOWS\Microsoft. For Linux.NET can be compiled in Visual Studio 2002 and 2003 (only supports the .Chapter 2 2 G ETTING S TARTED live version · discussion · edit chapter · comment · report an error T o compile your first C# application.Net Framework SDK installation places the Visual C# . a good compiler is cscc which can be downloaded for free from the DotGNU Portable. If the default Windows directory (the directory where Windows or WinNT is installed) is C:\WINDOWS. there are plenty of editors that are available.NET code.NET programs with a simple text editor.cs: using System. you will need a copy of a . Currently C#. Microsoft For Windows. The Visual Studio C# Express Edition can be downloaded and used for free from Microsoft's website.NET Framework SDK installed on your PC.0 and earlier versions with some tweaking). but it should be noted that this requires you to compile the code yourself.1. the .NET frameworks available: Microsoft's and Mono's.0. For writing C#.0.NET\Framework\v2. Microsoft offers five Visual Studio editions.NET Compiler (csc) in the C:\WINDOWS\Microsoft.NET\Framework\v1.NET Framework 2.exe or mcs. Linux. or other Operating Systems. an installer can be downloaded from the Mono website.Net Framework SDK can be downloaded from Microsoft's .1) and Visual Studio 2005 (supports the .0 and 1.NET Framework Developer Center.3705 directory for version 1. The code below will demonstrate a C# program written in a simple text editor. namespace MyConsoleApplication { class MyFirstClass 6 | C# Programming . four of which cost money. The compiled programs can then be run with ilrun.NET\Framework\v1.50727 directory for version 2. There are two .NET Framework version 1. the C:\WINDOWS\Microsoft. Mono For Windows. the . It's entirely possible to write C#.4322 directory for version 1. If you are working on Windows it is a good idea to add the path to the folders that contain cs. Start by saving the following code to a text file called hello.0.0.exe to the Path environment variable so that you do not need to type the full path each time you want to compile.1. Microsoft offers a wide range of code editing programs under the Visual Studio line that offer syntax highlighting as well as compiling and debugging capabilities.
Console.exe <name>. Alternatively. run C:\WINDOWS\Microsoft. Note that the example above includes the System namespace via the using keyword. System.0.Net 2.exe". Note that much of the power of the language comes from the classes provided with the . On Linux.cs. even though that is for debugging. That inclusion allows direct references to any member of the System namespace without specifying its fully qualified name.exe. compile with "cscc -o <name>.ReadLine()."). The second call to that method shortens the reference to the Console class by taking advantage of the fact that the System namespace is included (with using System).Net framework.WriteLine("Hello. in Visual C# express.cs • For Mono run mcs hello.exe: • • On Windows. } } } To compile hello.cs.WriteLine("Hello.cs". Console. run the following from the command line: • For standard Microsoft installations of . • For users of cscc.exe.exe will produce the following output: Hello.50727\csc. World! The program will then wait for you to strike 'enter' before returning to the command prompt.0. which are not part of the C# language syntax Wikibooks | 7 . Console.exe or "ilrun <name>."). C# is a fully object-oriented language. you could just hit F5 or the green play button to run the code.Getting Started { static void Main(string[] args) { System.exe hello.Console. The following command will run hello.Console. use mono hello. The first call to the WriteLine method of the Console class uses a fully qualified reference. Running hello.WriteLine("World!"). Doing so will produce hello. use hello.WriteLine("World!").NET\Framework\v2. The following sections explain the syntax of the C# language as a beginner's course for programming in the language.
live version · discussion · edit chapter · comment · report an error 8 | C# Programming .Chapter 2 per se.
define an expression. and the code within a corresponding catch block. Wikibooks | 9 . control the flow of execution of other statements.SampleMethodReturningInteger(i). Statements can be grouped into comma-separated statement lists or braceenclosed statement blocks. Examples: int sampleVariable. whose detailed behaviors are defined by their statements. Statements The basic unit of execution in a C# program is the statement. SampleClass sampleObject = new SampleClass(). The object-oriented nature of C# requires the high-level structure of a C# program to be defined in terms of classes. Code blocks can be nested and often appear as the bodies of methods. perform a simple action by calling a method. // // // // // declaring a variable assigning a value constructing a new object calling an instance method calling a static method // executing a "for" loop with an embedded "if" statement for(int i = 0. i < upperLimit. code blocks serve to limit the scope of variables defined within them. i++) { if (SampleClass. Statements are usually terminated by a semicolon.SampleInstanceMethod(). } } Statement blocks A series of statements surrounded by curly braces form a block of code. or field. the protected statements of a try block. create an object. sampleVariable = 5.Syntax 3 S YNTAX live version · discussion · edit chapter · comment · report an error C # syntax looks quite similar to the syntax of Java because both inherit much of their syntax from C and C++. try { // Here is a code block protected by the "try" statement. private void MyMethod() { // This block of code is the body of "MyMethod()" CallSomeOtherMethod().SampleStaticMethod(). A statement can declare a variable. property. or assign a value to a variable. SampleClass. Among other purposes.SampleStaticMethodReturningBoolean(i)) { sum += sampleObject. sampleObject.
} // "variableWithLimitedScope" is not accessible here. Multiple-line comments Comments can span multiple lines by using the multiple-line comment style. //************************** 10 | C# Programming .Chapter 3 int variableWithLimitedScope. Avoid using butterfly style comments. It allows multiple lines. either. Single-line comments. } catch(Exception) { // Here is yet another code block. end at the first endof-line following the "//" comment marker. Three styles of comments are allowed in C#: Single-line comments The "//" character sequence marks the following text as a single-line comment. */ XML Documentation-line comments This comment is used to generate XML documentation. The text between those multi-line comment markers is the comment. /// <summary> documentation here </summary> This is the most recommended type. //This style of a comment is restricted to one line. // "variableWithLimitedScope" is not accessible here. /* This is another style of a comment. CallYetAnotherMethod(). Comments Comments allow inline documentation of source code. // "variableWithLimitedScope" is accessible in this code block. Each line of the comment begins with "///". The C# compiler ignores comments. as one would expect. For example: //************************** // Butterfly style documentation comments like this are not recommended. } // Here ends the code block for the body of "MyMethod()". Such comments start with "/*" and end with "*/".
writeline("Hello"). live version · discussion · edit chapter · comment · report an error Wikibooks | 11 . The variables myInteger and MyInteger below are distinct because C# is case-sensitive: int myInteger = 3. The following code will generate a compiler error (unless a custom class or variable named console has a method named writeline()): // Compiler error! console. int MyInteger = 5.WriteLine("Hello"). The following corrected code compiles as expected because it uses the correct case: Console. including its variable and method names.Syntax Case sensitivity C# is case-sensitive.
for example. name ). parameters. Fields can also be associated with their class by making them constants (const).e. Fields. i. Parameter Parameters are variables associated with a method. a variable binds an object (in the general sense of the term. a specific value) to an identifier (the variable's name) so that the object can be accessed later. Fields Fields. which requires a declaration assignment of a constant value and prevents subsequent changes to the field. Local variables Like fields. Local Variables. They thus have both a scope and an extent of the method or statement block that declares them. 12 | C# Programming . More technically. or private (from most visible to least visible). Only values whose types are compatible with the variable's declared type can be bound to (stored in) the variable. and local variables.WriteLine ( "Good morning. while non-constant local variables are stored (or referenced from) the stack. Console. protected internal.Chapter 4 4 V ARIABLES live version · discussion · edit chapter · comment · report an error V ariables are used to store values. {0}" . protected. Each field has a visibility of public. while a static variable. sometimes called class-level variables. is a field associated with the type itself.ReadLine(). Variables can. store the value of user input: string name = Console. Each variable is declared with an explicit type. internal. An instance variable is a field associated with an instance of the class or structure. are variables associated with classes or structures. local variables can optionally be constant (const). and Parameters C# supports several program elements corresponding to the general programming concept of variable: fields. Constant local variables are stored in the assembly data region. declared with the static keyword.
NET languages. string) are passed in "by value" while reference types (objects) are passed in "by reference.NET framework remain the same. Although the names of the aliases vary between .Int32 i = 42. except that it is bound before the method call and it need not be assigned by the method.NET framework. Such a variable is considered by the compiler to be unbound upon method entry. If a method signature includes one. A params parameter represents a variable number of parameters. A reference parameter is similar to an out parameter. } public void EquivalentCodeWithoutAlias() { System. Types Each type in C# is either a value type or a reference type. so that changes to the parameter by the method do not affect the value of the callee's variable. the params argument must be the last argument in the signature. objects created in assemblies written in other languages of the .NET Framework can be bound to C# variables of any type to which the value can be converted. The following illustrates the cross-language compatibility of types by comparing C# code with the equivalent Visual Basic . double. each integral C# type is actually an alias for a corresponding type in the . Integral types Because the type system in C# is unified with other languages that are CLIcompliant. thus it is illegal to reference an out parameter before assigning it a value. so that changes to the variables will affect the value of the callee's variable. or passed in by reference. per the conversion rules below. } Wikibooks | 13 .Variables An in parameter may either have its value passed in from the callee to the method's environment. thus changes to the variable's value within the method's environment directly affect the value from the callee's environment." An out parameter does not have its value copied. C# has several predefined ("built-in") types and allows for declaration of custom value types and reference types. Value types (int. the underlying types in the . It also must be assigned by the method in each valid (non-exceptional) code path through the method in order for the method to compile.NET code: // C# public void UsingCSharpTypeAlias() { int i = 42. Thus.
and string. // The value of i is now the integer 97.NET Framework. a long is only guaranteed to be at least as large as an int. an alias for the System. from which all other reference types derive.Int.Int32 type implements a ToString() method to convert the value of an integer to its string representation.e. and is implemented with different sizes by different compilers.NET Framework type names. the System.NET Framework types follow: 14 | C# Programming . As reference types.Chapter 4 ' Visual Basic . int unboxedInteger = (int)boxedInteger.Object class. C#'s int type exposes that method: int i = 97.g. For example.Int32 = 42 End Sub Using the language-specific type aliases is often considered more readable than using the fully-qualified . e.NET Framework types. The predefined C# type aliases expose the methods of the underlying . any class) are exempt from the consistent size requirement. Likewise.ToString(). each an alias to a corresponding value type in the System namespace of the . may vary by platform. where. since the . an alias for the System. The fact that each C# type corresponds to a type in the unified type system gives each value type a consistent size across platforms and compilers. the size of reference types like System. The unified type system is enhanced by the ability to convert value types to reference types (boxing) and likewise to convert certain reference types to their corresponding value types (unboxing): object boxedInteger = 97. There are two predefined reference types: object. Fortunately.IntPtr. string s = i.Int32 type implements the Parse() method. That is. // The value of s is now the string "97".Parse(s). int i = int. The built-in C# type aliases and their equivalent . C# likewise has several integral value types. That consistency is an important distinction from other languages such as C. which can therefore be accessed via C#'s int type: string s = "97". as opposed to value types like System.NET Public Sub UsingVisualBasicTypeAlias() Dim i As Integer = 42 End Sub Public Sub EquivalentCodeWithoutAlias() Dim i As System.String class. there is rarely a need to know the actual size of a reference type. variables of types derived from object (i.NET Framework's System.
Single System.String 32/64 16 * length Wikibooks | 15 .0 x 10-28 to 7.Variables Integers C# Alias sbyte byte short ushort char int uint long ulong .535 -2.294.NET Type System.615 Range System.036.808 to 9.775.446.036.Int32 8 8 16 16 32 Size (bits) -128 to 127 0 to 255 -32.372.7 x 10308 1.709.Char System.854.NET Type System.9 x 1028 decimal System.NET Type Size (bits) Range true or false.295 -9.5 x 10-45 to 3.4 x 1038 5.Int64 64 System.648 to 2.147.SByte System.775.Decimal 128 Other predefined types C# Alias bool object string .223.Boolean 32 System.223.551.Int16 System.647 0 to 4.Byte System.073.535 A unicode character of code 0 to 65.967. A unicode string with no special upper bound.UInt64 64 Floating-point C# Alias float double .UInt16 16 System.807 0 to 18.UInt32 32 System.Object System. System. which aren't related to any integer in C#.854.372.768 to 32. Platform dependant (a pointer to an object).147.483.0 x 10-324 to 1.767 0 to 65.744.483.Double Size (bits) 32 64 Precision 7 digits 15-16 digits 28-29 decimal places Range 1.
arr[i] = arr[j]. int i.Chapter 4 Custom types The predefined types can be aggregated and extended into custom types. and explicit cast definitions. 16 | C# Programming . Custom value types are declared with the struct or enum keyword. If the type conversion is guaranteed not to lose information. Likewise. the following code snippet successfully swaps two elements in an integer array: static void swap (int[] arr. int j) { int temp = arr[i]. custom reference types are declared with the class keyword. As with other variable types. Arrays Although the number of dimensions is included in array declarations. the conversion can be implicit (i. however. Predefined conversions Many predefined value types have predefined conversions to other predefined value types. For example. specify the size of each dimension: s = new string[5] . arrays are passed by reference. initialization can be combined: string[] s = new string[5] . and not passed by value. the size of each dimension is not: string[] s . } Conversion Values of a given type may or may not be explicitly or implicitly convertible to other types depending on predefined conversion rules. the declaration and the It is also important to note that like in Java. inheritance structure.e. an explicit cast is not required). arr[j] = temp. Assignments to an array variable (prior to the variable's usage).
Scope and extent The scope and extent of variables is based on their declaration. The extent of variables is determined by the runtime environment using implicit reference counting and a complex garbage collection algorithm. In either case. The scope of parameters and local variables corresponds to the declaring method or statement block. Similarly. the conversion must be explicit in order for the conversion statement to compile. the runtime environment throws a conversion exception if the value to convert is not an instance of the target type or any of its derived types. live version · discussion · edit chapter · comment · report an error Wikibooks | 17 . to convert an interface instance to a class that implements it. while the scope of fields is associated with the instance or class and is potentially further restricted by the field's access modifiers. To convert a base class to a class that inherits from it. the conversion must be explicit in order for the conversion statement to compile.Variables Inheritance polymorphism A value can be implicitly converted to any class from which it inherits or interface that it implements.
Arithmetic The following arithmetic operators operate on numeric operands (arguments a and b in the "sample usage" below). The binary operator % operates only on integer arguments. Similar to C++. When placed before its argument.) The unary operator ++ operates only on arguments that have an l-value. The binary operator / returns the quotient of its arguments. When placed after its argument. It returns the remainder of integer division of those arguments. it increments that argument by 1 and returns the value of that argument before it was incremented.e.returns the difference between its arguments. it obtains that quotient using integer division (i. The unary operator -. defining or redefining the behavior of the operators in contexts where the first argument of that operator is an instance of that class. Following are the built-in behaviors of C# operators. it drops any resulting remainder). but doing so is often discouraged for clarity. it decrements that argument by 1 and returns the value of a / b a % b a++ a plus plus ++a a-- plus plus a a minus minus 18 | C# Programming . When placed after its argument.b a * b Read a plus b a minus b a times b a divided by b a mod b Explanation The binary operator + returns the sum of its arguments. it increments that argument by 1 and returns the resulting value.operates only on arguments that have an l-value. The binary operator * returns the multiplicative product of its arguments. Sample usage a + b a . (See modular arithmetic. The binary operator . If both of its operators are integers. The unary operator ++ operates only on arguments that have an l-value.Chapter 5 5 O PERATORS live version · discussion · edit chapter · comment · report an error C # operators and their precedence closely resemble the operators in other languages of the C family. classes can overload most operators.
the logical disjunction is performed bitwise. When placed before its argument. The binary operator && operates on boolean operands only. it evaluates and returns the results of the second operand. Logical The following logical operators operate on boolean or integral operands. If the result is false. That is. the exclusive or is performed bitwise. The binary operator ^ returns the exclusive or ("XOR") of their results.operates only on arguments that have an l-value. Note that if evaluating the second operand would hypothetically have no side effects. the results are identical to the logical conjunction performed by the & operator. Sample usage a & b Read a bitwise and b Explanation The binary operator & evaluates both of its operands and returns the logical conjunction ("AND") of their results. it returns false. it returns true. it decrements that argument by 1 and returns the resulting value. it evaluates and returns the results of the second operand. Otherwise. it returns true if a evaluates to false and it returns false if a evaluates to true. The binary operator || operates on boolean operands only. If the operands are integral. It evaluates the first operand. If the result is true. The binary operator | evaluates both of its operands and returns the logical disjunction ("OR") of their results. It Wikibooks | 19 a && b a and b a | b a bitwise or b a || b a or b a ^ b a x-or b !a ~a not a bitwise . The unary operator ! operates on a boolean operand only. Note that if evaluating the second operand would hypothetically have no side effects. If the operands are integral. Otherwise. --a minus minus a The unary operator -. It evaluates its operand and returns the negation ("NOT") of the result. If the operands are integral. as noted. It evaluates its first operand.Operators that argument before it was decremented. the logical conjunction is performed bitwise. the results are identical to the logical disjunction performed by the | operator. The unary operator ~ operates on integral operands only.
~a returns a value where each bit is the negation of the corresponding bit in the result of evaluating a. Sample usage Read Explanation For arguments of value type. false otherwise. That is. >. false otherwise.Chapter 5 evaluates its operand and returns the bitwise negation of the result. The binary operator >> evaluates its operands and returns the resulting first argument right-shifted by the number of a bits specified by the second argument. It returns true if a is greater than b. not a Bitwise shifting Sample usage Read Explanation a << b The binary operator << evaluates its operands and returns the resulting first argument left-shifted by the number of bits a left specified by the second argument. It returns true if a is less than b. For other reference types (types derived from System. <=. it returns true if the strings' character sequences match. The operator <= operates on integral types. however. false otherwise. the operator == returns true if its operands have the same value. The operator > operates on integral types. it returns true if a is not equal to b. equal to b and false if they are equal. a is less than b a is greater than b a is less The operator < operates on integral types. a >> b Relational The binary relational operators ==. or to zero if the first argument is unsigned. a == b returns true only if a and b reference the same object. and >= are used for relational operations and for type comparisons. Thus. <. a == b a is equal to b a != b a < b a > b a <= b The operator != returns the logical negation of the a is not operator ==. For the string type. !=. It discards high-order bits shift b that shift beyond the size of its first argument and sets new low-order bits to zero.Object). It discards low-order right bits that are shifted beyond the size of its first argument and shift b sets new high-order bits to the sign bit of the first argument. It returns 20 | C# Programming .
so the first argument typically just refers to a different object but the object that it originally referenced does not change (except that it may no longer be referenced and may thus be a candidate for garbage collection). Sample usage a += b Read a plus equals (or increment by) b Explanation Equivalent to a = a + b. false otherwise. and then a set to b Equivalent to a = (b = c). false otherwise. When there are consecutive assignments. b set to c.) The first argument of the assignment operator (=) is typically a variable.Operators than or true if a is less than or equal to b. equal to b a >= b a is greater The operator >= operates on integral types. the assignment operation changes the reference. the right-most assignment is evaluated first. it assigns the value of its second argument to its first argument. When the first argument is a reference type. proceeding from right to left. Sample usage a = b Read Explanation The operator = evaluates its second argument and then a equals assigns the results to (the l-value indicated by) its first (or set to) b argument. a = b = c Short-hand Assignment The short-hand assignment operators shortens the common assignment operation of a = a operator b into a operator= b. It returns than or true if a is greater than or equal to b. the assignment operation changes the argument's underlying value. equal to b Assignment The assignment operators are binary. Not surprisingly. (More technically. resulting in less typing and neater syntax. The most basic is the operator =. Wikibooks | 21 . When that argument has a value type. the operator = requires for its first (left) argument an expression to which a value can be assigned (an l-value) and for its second (right) argument an expression which can be evaluated (an r-value). both variables a and b have the value of c. That requirement of an assignable expression to its left and a bound expression to its right is the origin of the terms l-value and r-value. In this example.
Equivalent to a = a >> b. []. or. Equivalent to a = a * b. Remarks: The sizeof operator can be applied only to value types.Chapter 5 a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b a minus equals (or decrement by) b a multiply equals (or multiplied by) b a divide equals (or divided by) b a mod equals b a and equals b a or equals b a xor equals b a left-shift equals b a right-shift equals b Equivalent to a = a . if x is of type T. not reference types. Equivalent to a = a << b. Else returns null. Equivalent to a = a ^ b. Type information Expression x is T x as T Explanation returns true if the variable x of base class type stores an object of derived class type T. if x is of type T.Type object describing the type.b. sizeof(x) typeof(T) Pointer manipulation Expression Explanation To be done *. or. Else returns false. Equivalent to a = a & b. ->. & Overflow exception control Expression checked(a) Explanation uses overflow checking on value a unchecked(a) avoids overflow checking on value a 22 | C# Programming . and not a variable. Equivalent to a = a % b. Use the GetType method to retrieve run-time type information of variables. The sizeof operator can only be used in the unsafe mode. T must be the name of the type. returns (T)x (x casted to T) if the variable x of base class type stores an object of derived class type T. Equivalent to a = a / b. Equivalent to x is T ? (T)x : null returns the size of the value type x. returns a System. Equivalent to a = a | b.
returns the value of b. otherwise c if a is null. concatenates a and b if a is true.Operators Others Expression a. otherwise returns a live version · discussion · edit chapter · comment · report an error Wikibooks | 23 . returns b.b a[b] (a)b new a a+b a?b:c a ?? b Explanation accesses member b of type or namespace a the value of index b in a casts the value b to type a creates an object of type a if a and b are string types.
Wednesday. The elements in the above enumeration are then available as constants: Weekday day = Weekday.". it is often more readable to use an enumeration. Friday. Structs Structures (keyword struct) are light-weight objects. or geographical territory in a more meaningful way than an integer could.WriteLine("You become a teenager at an age of {0}.Tuesday) { Console. Tuesday. They are mostly used when only a data container is required for a collection of value type variables. e. and the successive values are assigned to each subsequent element.g.WriteLine("Time sure flies by when you program in C#!"). if (day == Weekday. Enumerations An enumeration is a data type that enumerates a set of items by assigning to each of them an identifier (a name). specific values from the underlying integral type can be assigned to any of the enumerated elements: enum Age { Infant = 0. Diamonds. It may be desirable to create an enumeration with a base type other than int. Spades. The underlying values of enumerated elements may go unused when the purpose of an enumeration is simply to group a set of items together. Sunday }. Teenager = 13. The underlying type is int by default. Adult = 18 }. Saturday.Chapter 6 6 D ATA S TRUCTURES live version · discussion · edit chapter · comment · report an error There are various ways of grouping sets of data together in C#. Clubs }. } If no explicit values are assigned to the enumerated items as the example above. state. to represent a nation. Thursday.. However. specify any integral type besides char as with base class extension syntax after the name of the enumeration. 24 | C# Programming . To do so.Monday. (int)age).Teenager. Console. the first element has the value 0. Rather than define a group of logically related constants. Age age = Age. but can be any one of the integral types except for char. as follows: enum CardSuit : byte { Hearts. while exposing an underlying base type for ordering the elements of the enumeration. Enumerations are declared as follows: enum Weekday { Monday.
} It is also possible to provide constructors to structs to make it easier to initialize them: using System. 7. Another very important difference is that structs cannot support inheritance. While structs may appear to be limited with their use.birthDate = new DateTime(1974. 18). int weightInKg. new DateTime(1974.name = name. dana. 50).Data Structures Structs are similar to classes in that they can have constructors.weightInKg = weightInKg. public int heightInCm. DateTime birthDate. } } live version · discussion · edit chapter · comment · report an error Wikibooks | 25 . } } public class StructWikiBookSample { public static void Main() { Person dana = new Person("Dana Developer". public Person(string name. dana. if (dana.DateTime birthDate. 7. be declared like this: struct Person { public string name. DateTime birthDate. int heightInCm. } The Person struct can then be used like this: Person dana = new Person().WriteLine("Thank goodness! Dana Developer isn't from the future!"). int heightInCm. methods. A struct can.weightInKg = 50.Now) { Console.name = "Dana Developer". this. but there are important differences.heightInCm = heightInCm. public System. and even implement interfaces. public int weightInKg. this. for example. dana. Structs are value types while classes are reference types. 178. they require less memory and can be less expensive if used in the proper way. 18). dana. int weightInKg) { this.birthDate < DateTime. this.birthDate = birthDate.heightInCm = 178. struct Person { string name. which means they behave differently when passed into methods as parameters.
and Java. try-finally. foreach. An exception handling statement can be used to handle exceptions using keywords such as throw. continue. else if. else if( myNumber < 0 ) { Console. and in. if ( myNumber == 4 ) Console. it is written in the following form: if-statement ::= "if" "(" condition ")" if-body ["else" else-body] condition ::= boolean-expression if-body ::= statement-or-statement-block else-body ::= statement-or-statement-block The if statement evaluates its condition expression to determine whether to execute the if-body. A jump statement can be used to transfer program control using keywords such as break. return. and yield. Thus.Chapter 7 7 C ONTROL live version · discussion · edit chapter · comment · report an error C onditional. public class IfStatementSample { public void IfMyNumberIs() { int myNumber = 5. Conditional statements A conditional statement decides whether to execute code based on conditions. while. the if statement has the same syntax as in C. else if. else if.WriteLine("This will not be shown because myNumber is not negative. C++. jump."). providing code to execute when the condition is false. an else clause can immediately follow the if body. and exception handling statements control a program's flow of execution. else statements: using System. The if statement and the switch statement are the two types of conditional statements in C#. try-catch. Optionally. iteration.WriteLine("This will not be shown because myNumber is not 4. 26 | C# Programming . for."). Making the elsebody another if statement creates the common cascade of if. and try-catch-finally. An iteration statement can create a loop using keywords such as do. The if statement As with most of C#.
C# does not support "fall through" from one case statement to the next (thereby eliminating a common source of unexpected behaviour in C programs). The default label is optional. default: Console.WriteLine("myNumber does not match the coded conditions. break. break. Wikibooks | 27 . case 2: Console.WriteLine("Rans S6S Coyote"). break. so this sentence will be shown!"). If no default case is defined. } } } The switch statement The switch statement is similar to the statement from C.WriteLine("Dual processor computer"). In other words. If goto is used.Control } else if( myNumber % 2 == 0 ) Console. However "stacking" of cases is allowed. each case statement must finish with a jump statement (which can be break or goto or return).WriteLine("You don't have a CPU! :-)")."). break. A simple example: switch (nCPU) { case 0: Console. case 1: Console.WriteLine("A multi processor computer"). goto case 0 or goto default). then the default behaviour is to do nothing. // Stacked cases case 3: case 4: case 5: case 6: case 7: case 8: Console. it may refer to a case label or the default case (e. Unlike C. case "C-GJIS": Console.g. as in the example below. else { Console. break.WriteLine("A seriously parallel computer"). break.WriteLine("This will not be shown because myNumber is not even. For example: switch (aircraft_ident) { case "C-FESO": Console. C++ and Java. } A nice improvement over the C switch statement is that the switch variable can be a string.WriteLine("Single processor computer").WriteLine("Rans S12XL Airaile").
The do.while loop always runs its body once. The for loop The for loop likewise has the same syntax as in other languages derived from C. the body executes again.while loop The do. If the condition is true.. do { Console. break.. It is written in the following form: for-loop ::= "for" "(" initialization ". If the condition evaluates to true again after the body has ran.. default: Console. and the foreach loop are the iteration statements in C#..while loop likewise has the same syntax as in other languages derived from C. } while(number <= 10)..Chapter 7 break. public class DoWhileLoopSample { public void PrintValuesFromZeroToTen() { int number = 0. the body executes. } } The above code writes the integers from 0 to 10 to the console. } Iteration statements An iteration statement creates a loop of code to execute a variable number of times. using System." iteration ")" body initialization ::= variable-declaration | list-of-statements condition ::= boolean-expression iteration ::= list-of-statements 28 | C# Programming . The for loop. After its first run.WriteLine(number++.while-loop ::= "do" body "while" "(" condition ")" condition ::= boolean-expression body ::= statement-or-statement-block The do. the do.... the do loop.while loop ends.WriteLine("Unknown aircraft"). it evaluates its condition to determine whether to run its body again. It is written in the following form: do...ToString()). the while loop. When the condition evaluates to false." condition ".
} } In the above code. The foreach loop exits when there are no more elements of the enumerable-expression to assign to the variable of the variable-declaration. It is often used to test an index variable against some limit.Control body ::= statement-or-statement-block The initialization variable declaration or statements are executed the first time through the for loop. and "Charlie" to the console.WriteLine(item). "Bravo".Console. "Charlie"}. the foreach statement iterates over the elements of the string array to write "Alpha". public class ForLoopSample { public void ForFirst100NaturalNumbers() { for(int i=0. typically to declare and initialize an index variable. public class ForEachSample { public void DoSomethingForEachItem() { string[] itemsToWrite = {"Alpha". It is written in the following form: foreach-loop ::= "foreach" "(" variable-declaration "in" enumerableexpression ")" body body ::= statement-or-statement-block The enumerable-expression is an expression of a type that implements IEnumerable. the body is executed. so it works even with collections that lack indices altogether. If the condition evaluates to true. typically to increment or decrement an index variable. The condition expression is evaluated before each pass through the body to determine whether to execute the body.WriteLine(i.Console. "Bravo".ToString()). The iteration statements are executed after each pass through the body. The variable-declaration declares a variable that will be set to the successive elements of the enumerableexpression for each pass through the body. i<100. but the foreach statement lacks an iteration index. } } } The above code writes the integers from 0 to 99 to the console. The foreach loop The foreach statement is similar to the for statement in that both allow code to iterate over the items of collections. foreach (string item in itemsToWrite) System. Wikibooks | 29 . i++) { System. so it can be an array or a collection.
} } Jump statements A jump statement can be used to transfer program control using keywords such as break. DateTime start = DateTime. you use yield return to return individual values and yield break to end the sequence.WriteLine(d). using System. Instead of using return to return the sequence. } Console.Console.Now . i.Now < limit) yield return DateTime. If the condition then evaluates to true again.Chapter 7 The while loop The while loop has the same syntax as in other languages derived from C.Collections. the body executes again. while (DateTime.Generic. 0. public class WhileLoopSample { public void RunForAwhile() { TimeSpan durationToRun = new TimeSpan(0.e.start < durationToRun) { Console. continue. When the condition evaluates to false.Now. a function that returns a sequence of values from an object implementing IEnumerable. the body executes. using System.WriteLine("not finished yet").WriteLine("finished"). 30 | C# Programming .Now + new TimeSpan(0. It is written in the following form: while-loop ::= "while" "(" condition ")" body condition ::= boolean-expression body ::= statement-or-statement-block The while loop evaluates its condition to determine whether to run its body. public class YieldSample { static IEnumerable<DateTime> GenerateTimes() { DateTime limit = DateTime. the while loop ends. and yield. yield break. Using yield A yield statement is used to create an iterator. } static void Main() { foreach (DateTime d in GenerateTimes()) { System.30).Now. 30).0. return. while (DateTime. using System. If the condition is true.
Control } System. Exception handling statements An exception handling statement can be used to handle exceptions using keywords such as throw. } } Note that you define the function as returning a System.Generic. note that the body of the calling foreach loop is executed in between the yield return statements. try-catch.Collections. then yield return individual values of the parameter type.Console. Also.IEnumerable parameterized to some type. try-finally. and try-catch-finally.Read(). See the Exceptions page for more information on Exception handling live version · discussion · edit chapter · comment · report an error Wikibooks | 31 .
WriteLine("press enter to continue. All exception objects are instantiations of the System.Exception or a child class of it. the use of a null object reference detected by the runtime system or an invalid input string entered by a user and detected by application code. such as the stack trace at the point of the exception and a descriptive error message. An exception can represent a variety of abnormal conditions. } catch (ApplicationException e) { Console. There are many exception classes defined in the .ReadLine(). topping).. topping)). The following example demonstrates the basics of exception throwing and handling exceptions: class ExceptionTest { public static void Main(string[] args) { try { OrderPizza("pepperoni"). OrderPizza("anchovies"). for example. this example produces the following output: one pepperoni pizza ordered Unsupported pizza topping: anchovies press enter to continue.. } } private static void OrderPizza(string topping) { if (topping != "pepperoni" && topping != "sausage") { throw new ApplicationException( String. Console. 32 | C# Programming . Code that detects an error condition is said to throw an exception and code that handles the error is said to catch the exception.WriteLine("one {0} pizza ordered". such as ApplicationException. } finally { Console. including. Programmers may also define their own class inheriting from System. } Console.Message). } } When run..Exception or some other appropriate exception class from the .NET Framework used for various purposes. An exception in C# is an object that encapsulates various information about the error that occurred.").NET Framework.Chapter 8 8 E XCEPTIONS live version · discussion · edit chapter · comment · report an error T he exception handling system in the C# allows the programmer to handle errors or anomalous situations in a structured manner that allows the programmer to separate the normal flow of the code from error handling logic.WriteLine(e.Format("Unsupported pizza topping: {0}"..
The throw is followed by the object reference representing the exception object to throw. it is one method in the call stack higher.Exceptions The Main() method begins by opening a try block. These blocks contain the exception handling logic. The try block calls the OrderPizza() method. but normally it is used to release acquired resources or perform other cleanup activities. the exception object is constructed on the spot. In this case. similar to the way a method argument is declared. an exception is thrown using the throw keyword. When an exception matching the type of the catch block is thrown. in this case. The method checks the input string and. A try block is a block of code that may throw an exception that is to be caught and handled. When the exception is thrown. which may throw an ApplicationException. In this case. if it has an invalid value. live version · discussion · edit chapter · comment · report an error Wikibooks | 33 . Each catch block contains an exception object declaration. The finally block is optional and contains code that is to be executed regardless of whether an exception is thrown in the associated try block. the finally just prompts the user to press enter. Following the try block are one or more catch blocks. the Main() method contains a finally block after the catch block. In this case. Lastly. control is transferred to the inner most catch block matching the exception type thrown. that exception object is passed in to the catch and available for it to use and even possibly re-throw. an ApplicationException named e.
world!"). you explicitly tell the compiler that you'll be using a certain namespace in your program. with the System namespace usually being by far the most commonly seen one. a class named Console. as you told it which namespaces it should look in if it couldn't find the data in your application.WriteLine("Hello. So one can then type like this: using System.NET Framework. such as variable names. along with making it so your application doesn't occupy names for other applications. such as: System.g.NET already use one in its System namespace. Since the compiler would then know that.WriteLine("Hello. will cause the compiler to treat the 34 | C# Programming . and another with the same name in another source file. They're used especially to provide the C# compiler a context for all the named information in your program.Chapter 9 9 N AMESPACES live version · discussion · edit chapter · comment · report an error N amespaces are used to provide a "named space" in which your application resides. The purpose of namespaces is to solve this problem. if your application is intended to be used in conjunction with another. } There is an entire hierarchy of namespaces provided to you by the . world!").NET Framework for your applications to use. namespace MyApplication { class MyClass { void ShowGreeting() { Console. operator. // note how System is now not required } } } Namespaces are global. This will call the WriteLine method that is a member of the Console class within the System namespace.Console. So namespaces exist to resolve ambiguities a compiler wouldn't otherwise be able to do. so a namespace in one C# source file. Without namespaces. Namespaces are easily defined in this way: namespace MyApplication { // The content to reside in the MyApplication namespace is placed here. Data in a namespace is referred to by using the . and release thousands of names defined in the . as . it no longer requires you to type the namespace name(s) for such declared namespaces. By using the using keyword. you wouldn't be able to make e.
that one would then not have to be explicitly declared with the using keyword. often named after your application or project name. Sometimes.Namespaces different named information in these two source files as residing in the same namespace. and still not have to be completely typed out. Nested namespaces Normally. Either like this: namespace CodeWorks { namespace MyApplication { // Do stuff } } .. and the nested namespaces the respective project names. If both the library and your program shared a parent namespace. and are identical in what they do.MyApplication { // Do stuff } Both methods are accepted. companies with an entire product series decide to use nested namespaces though. The developer of the library and program would finally also separate all the named information in their product source codes. you can show this in two ways. third party developers that may use your code would additionally then see that the same company had developed the library and the program. This can be especially convenient if you're a developer who has made a library with some usual functionality that can be shared across programs. for fewer headaches especially if common names are used. If your code was open for others to use.. your entire application resides under its own special namespace. live version · discussion · edit chapter · comment · report an error Wikibooks | 35 . To make your application reside in a nested namespace. where the "root" namespace can share the name of the company. or like this: namespace CodeWorks.
} get { return _name. and structures. public string Name { set { _name = value. } } public void GetPayCheck() { } public void Work() { } } public class Sample { public static void Main() { Employee Marissa = new Employee(). The methods and properties of a class contain the code that defines how the class behaves. including subtyping polymorphism via inheritance and parametric polymorphism via generics. } get { return _age.Work(). It also defines a Sample class that instantiates and uses the Employee class: public class Employee { private string _name. } } public int Age { set { _age = value. } } 36 | C# Programming . static classes. Classes are defined using the keyword "class" followed by an identifier to name the class. Instances of the class can then be created with the "new" keyword followed by the name of the class.GetPayCheck(). Marissa.Chapter 10 10 C LASSES live version · discussion · edit chapter · comment · report an error A s in other object-oriented programming languages. C# classes support information hiding by encapsulating functionality in properties and methods and by enabling several types of polymorphism. the functionality of a C# program is implemented in one or more classes. including instance classes (standard classes that can be instantiated). The code below defines a class called Employee with properties Name and Age and with empty methods GetPayCheck() and Work(). Several types of C# classes can be defined. Marissa. private int _age.
WriteLine("End").Classes Methods C# methods are class members containing code.Console. a constructor can have parameters. the new command accepts parameters.Console. The below code defines and then instantiates multiple objects of the Employee class. as well as a generic type declaration. } } Output: Start Constructed without parameters Parameter for construction End Finalizers The opposite of constructors. Employee Alfred = new Employee(). Employee Billy = new Employee("Parameter for construction").Console.WriteLine("Constructed without parameters"). To create an object using a constructor with parameters. but they are not restricted to doing so.Console. once using the constructor without parameters and once using the version with a parameter: public class Employee { public Employee() { System. Like fields.WriteLine(text). finalizers define final the behavior of an object Wikibooks | 37 . } } public class Sample { public static void Main() { System. They may have a return value and a list of parameters. methods can be static (associated with and accessed through the class) or instance (associated with and accessed through an object instance of the class).WriteLine("Start"). Constructors often set properties of their classes. A constructor's code executes to initialize an instance of the class when a program requests a new object of the class's type. } public Employee(string text) { System. Constructors A class's constructors control its initialization. System. Like other methods.
a.k. is called sometime after an object is no longer referenced. public class Employee { public Employee(string text) { System. they are less frequently used in C# due to the .Console. } ~Employee() { System. They simplify the syntax of calling traditional get and set methods (a. Like methods. } } Output: Constructed! Finalized! Properties C# properties are class members that expose functionality of methods using the syntax of fields.Chapter 10 and execute when the object is no longer in use. which takes no parameters.Console. but the complexities of garbage collection make the specific timing of finalizers uncertain. After a property is defined it can be used like a variable.NET Framework Garbage Collector. If you were to write some 38 | C# Programming . // Sets integerField with a default value of 3 public int IntegerField { get { return integerField. // set assigns the value assigned to the property of the field you specify } } } The C# keyword value contains the value assigned to the property. An object's finalizer. Marissa = null.WriteLine(text). // get returns the field you specify when this property is assigned } set { integerField = value. they can be static or instance. accessor methods).WriteLine("Finalized!"). Properties are defined in the following way: public class MyClass { private int integerField = 3. Although they are often used in C++ to free memory reserved by an object. } public static void Main() { Employee Marissa = new Employee("Constructed!").
Classes additional code in the get and set portions of the property it would work like a method and allow you to manipulate the data before it is read or written to the variable. // Indirectly assigns 7 to the field myClass. . Events C# events are class members that expose notifications to clients of the class.IntegerField = 7. myClass. if the class was EmployeeCollection. use the this keyword as in the following example: public string this[string key] { get {return coll[_key]. you could write code similar to the following: EmployeeCollection e = new EmployeeCollection().} set {coll[_key] = value. e["Smith"] = "xxx". // Writes 3 to the command line. public class MyProgram { MyClass myClass = new MyClass.integerField } Using properties in this way provides a clean. . list[0] to access the first element of list even when list is not an array).IntegerField). using System.g. string s = e["Jones"]. Wikibooks | 39 . Console. . easy to use mechanism for protecting data. For example. To create an indexer. Operator C# operator definitions are class members that define or redefine the behavior of basic C# operators (called implicitly or explicitly) on instances of the class.WriteLine(myClass.} } This code will create a string indexer that returns a string value. Indexers C# indexers are class members that define the behavior of the array access operation (e.
but have subtle differences. } } public class Sample { public static void Main() { Writer. using a standard class is a better choice. Structs are used as lightweight versions of classes that can help reduce memory management efforts in when working with small data structures. } } } Static classes Static classes are commonly used to implement a Singleton Pattern.Console class) and can thus be used without instantiating the static class: public static class Writer { public static void Write() { System.Chapter 10 Structures Structures. Access to the private field is granted through the public property "Name": struct Employee { private string name. and fields of a static class are also static (like the WriteLine() method of the System. } get { return name. } } live version · discussion · edit chapter · comment · report an error 40 | C# Programming .WriteLine("Text"). Thus when you pass a struct to a function by value you get a copy of the object so changes to it are not reflected in the original because there are now two distinct objects but if you pass an instance of a class by value then there is only one instance. public int age. All of the methods.Write(). public string Name { set { name = value. The Employee structure below declares a public and a private field. The principal difference between structs and classes is that instances of structs are values whereas instances of classes are references.Console. however. properties. In most situations. They are similar to classes. are defined with the struct keyword followed by an identifier to name the structure. or structs.
and operations which are not allowed to outside users. Protected Protected members can be accessed by the class itself and by any class Wikibooks | 41 . and preventing him from manipulating objects in ways not intended by the designer. In this example. These methods and properties represent the operations allowed on the class to outside users. For example: public class Frog { public void JumpLow() { Jump(1). The Jump private method is implemented by changing the value of a private data member _height. data members (and other elements) with private protection level represent the internal state of the class (for variables). even a class derived from the class with private members cannot access the members. A method in another class. only 10 or 1. A class element having public protection level is accessible to all code anywhere in the program. which is also not visible to an outside user. } public void JumpHigh() { Jump(10). Methods. so he cannot make the frog jump 100 meters. they are implemented using the private Jump function that can jump to any height. the public method the Frog class exposes are JumpLow and JumpHigh. Some private data members are made visible by properties. } private void Jump(int height) { _height += height. Protection Levels Private Private members are only accessible within the class itself.} } private int _height = 0. This operation is not visible to an outside user.Encapsulation 11 E NCAPSULATION live version · discussion · edit chapter · comment · report an error E ncapsulation is depriving of the user of a class information he does not need. Internally.
Internal Internal members are accessible only in the same assembly and invisible outside it. Public Public members can be accessed by any method in any class.Chapter 11 derived from that class. live version · discussion · edit chapter · comment · report an error 42 | C# Programming .
NET Framework contains common class libraries . but has nothing to do with .Process. and running Web Services and Web Applications.Start("notepad.NET and Windows Forms .NET F RAMEWORK O VERVIEW live version · discussion · edit chapter · comment · report an error Introduction NET was originally called NGWS(Next Generation Windows Services).Net does not run IN any browser.wikibooks. In the System namespace.NET Framework is a common environment for building.. deploying.Version.NET Framework Overview 12 .The .MachineName). Let's look at a couple.NET is built on the following Internet standards: HTTP.NET delivers software as Web Services .OSVersion.exe"). or a webpage.Net . Console. the format for exchanging data between Internet Applications SOAP.ToString() + " + System. You can also get information about your system in the Environment namespace: Console.Process.OSVersion. It is a RUNTIME language (Common Language Runtime) like the Java runtime.Environment.NET will run in any browser on any platform . the standard format for requesting Web Services UDDI.Diagnostics.like ADO.Platform.Write: Wikibooks | 43 . .NET.Start(". you can write: System. there are a lot of useful libraries.org").ToString()). System.NET is a server centric computing model .WriteLine(System.Environment.NET is a new Internet and Web based infrastructure .ReadLine() This can be directly passed as a parameter to Console. ASP. the communication protocol between Internet Applications XML.. Silverlight does run in a browser.WriteLine("Machine name: " + System. • • • • .to provide advanced standard services that can be integrated into a variety of computer systems.Diagnostics. " User input You can read a line from the user with Console.NET is based on the newest Web standards . If you want to start up a external program. the standard to search and discover Web Services The .Environment.
Write ( "I'm afraid I can't do that.ReadLine() ) . "{1}" would be the next parameter etc.Write(). which will be most effective for the input "Dave" :-) In this case. {0}" .ReadLine(). which is Console. live version · discussion · edit chapter · comment · report an error 44 | C# Programming . Console. "{0}" gets replaced with the first parameter passed to Console.Chapter 12 Console.
my first program! Goodbye World! That text is output using the System. The middle lines use the Write() method.Console Programming 13 C ONSOLE P ROGRAMMING live version · discussion · edit chapter · comment · report an error Output The example program below shows a couple ways to output text: using System. but allows us to encode certain special characters (like a new line character).WriteLine("Hello World!"). public class HelloWorld { public static void Main() { Console.WriteLine("Goodbye World!"). which does not automatically create a new line.WriteLine("Nice to meet you.. we can use the sequence backslash-n ( \n ).. If for whatever reason we wanted to really show the \n character instead. To specify a new line. Console.Read()..Write("My name is: "). Input Input can be gathered in a similar method to outputing data using the Read() and ReadLine methods of that same System. Console.Console class. The using statement at the top allows the compiler to find the Console class without specifying the System namespace each time it is used. " + name).Console class: using System.Write("This is"). string name = Console. Console. The backslash is known as the escape character in C# because it is not treated as a normal character.ReadLine(). System.WriteLine("Greetings! What is your name?"). } } Wikibooks | 45 .. Console. public class ExampleClass { public static void Main() { Console.Console. my first program!\n"). Console. } } // relies on "using System." // no "using" statement required The above code displays the following text: Hello World! This is. we add a second backslash ( \\n ).Write(".
} } Try running the program with only entering your first name or no name at all. The final Console. That assumption makes the program unsafe. using System. it can be executed from the command line using two arguments. } } If the program above code is compiled to a program called username.Length property returns the total number of arguments.Length >= 2) Console.WriteLine("Last Name: " + args[1]).Length >= 1) Console. it will return zero.Read(). it will crash when it attempts to access the missing argument. Command line arguments Command line arguments are values that are passed to a console program before execution. If it is run without the expected number of command line arguments.Read() waits for the user to enter a key before exiting the program. If no arguments are given. "Bill" and "Gates": C:\>username. Console.exe Bill Gates Notice how the Main() method above has a string array parameter. public class Test { public static void Main(string[] args) { if(args.g. live version · discussion · edit chapter · comment · report an error 46 | C# Programming . using System. we make we can check to see if the user entered all the required arguments.WriteLine("First Name: " + args[0]). The program assumes that there will be two arguments. public class ExampleClass { public static void Main(string[] args) { Console. To make the program more robust. The first argument is the original file and the second is the location or name for the new copy. Custom console applications can have arguments as well. e. Console.Chapter 13 The above program requests the user's name and displays it back.exe. For example. The string. if(args.WriteLine(args[0]).WriteLine(args[1]). the Windows command prompt includes a copy command that takes two command line arguments.
Form { public static void Main() { ExampleForm wikibooksForm = new ExampleForm().Forms namespace allows us to create Windows applications easily.Run(wikibooksForm).Forms.Windows Forms 14 W INDOWS F ORMS live version · discussion · edit chapter · comment · report an error T he System. Your program will compile and run successfully if you comment these lines out but they allow us to add extra control to our form. Setting any of the properties Text. public class ExampleForm : Form // inherits from System. and Height is optional.Windows. icons and title bars together. wikibooksForm. // display the form } } The example above creates a simple Window with the text "I Love Wikibooks" in the title bar.Forms. menus. but it is important to know how to do so manually: using System.Form class.Forms. Width.Text = "I Love Wikibooks".Width = 400.Windows. // width of the window in pixels wikibooksForm. The Form class is a particularly important part of that namespace because the form is the key graphical building block Windows applications. It provides the visual frame that holds buttons. Custom form classes like the example above inherit from the System.Windows. // height in pixels Application.Windows. Integrated development environments (IDEs) like Visual C# and SharpDevelop can help create graphical applications. live version · discussion · edit chapter · comment · report an error Wikibooks | 47 .Height = 300.// specify title of the form wikibooksForm.
we create an Executive class that will override the GetPayCheck method. public class Employee { // we declare one method virtual so that the Executive class can // override it. Inheritance(by Mine) Subtyping Inheritance The code sample below shows two classes. and extending the functionality and state of the derived class. } // the extra method is implemented. public override void GetPayCheck() { //new getpaycheck logic here. public virtual void GetPayCheck() { //get paycheck logic here. AdministerEmployee.Chapter 15 15 I NHERITANCE live version · discussion · edit chapter · comment · report an error I nheritance is the ability to create a class from another class. We want the Executive class to have the same methods. } //Employee's and Executives both work. Employee has the following methods. so no virtual here needed. public void AdministerEmployee() { // manage employee logic here } } You'll notice that there is no Work method in the Executive class. Employee. } } Now. public void Work() { //do work logic here. it is not 48 | C# Programming . public class Executive : Employee { // the override keyword indicates we want new logic behind the GetPayCheck method. GetPayCheck and Work. Below is the creation of the first class to be derived from. Employee and Executive. Inheritance in C# also allows derived classes to overload methods from their parent class. but differently implemented and one extra method.
Inheritance();
}
Inheritance keywords
How C# inherits from another class syntacticaly is using the ":" character.); }
live version · discussion · edit chapter · comment · report an error
Wikibooks | 49
Chapter 16
16 I NTERFACES
live version · discussion · edit chapter · comment · report an error
A
n interface in C# is type definition similar to a class except that it purely represents a contract between an object and a user of the object. An interface cannot be directly instantiated as an object. No data members can be defined in an interface. Methods and properties can only be declared, not defined. For example, the following defines a simple interface:
interface IShape { void Draw(); double X { get; set; } double Y { get; set; } }
A convention used in the .NET Framework (and likewise by many C# programmers) is to place an "I" at the beginning of an interface name to distinguish it from a class name. Another common interface naming convention is used when an interface declares only one key method, such Draw() in the above example. The interface name is then formed by adding the suffix "able" to the method name. So, in the above example, the interface name would be IDrawable. This convention is also used throughout the .NET Framework. Implementing an interface is simply done by inheriting off the interface and then defining all the methods and properties declared by the interface. For example:
class Square : IShape { private double mX, mY; public void Draw() { ... } public double X { set { mX = value; } get { return mX; } } public double Y { set { mY = value; } get { return mY; } }
}
Although a class can only inherit from one other class, it can inherit from any number of interfaces. This is simplified form of multiple inheritance supported by C#. When inheriting from a class and one or more interfaces, the base class should be provided first in the inheritance list followed by any interfaces to be implemented. For example:
class MyClass : Class1, Interface1, Interface2 { ... }
50 | C# Programming
Interfaces Object references can be declared using an interface type. For example, using the previous examples:
class MyClass { static void Main() { IShape shape = new Square(); shape.Draw(); } }
Intefaces can inherit off of any number of other interfaces but cannot inherit from classes. For example:
interface IRotateable { void Rotate(double theta); }
interface IDrawable : IRotateable { void Draw(); }
Some Important Points for Interface
Access specifiers (i.e. private, internal, etc) cannot be provided for interface members. In Interface, all members are public by default. A class implementing an interface must define all the members declared by the interface as public. The implementing class has the option of making an implemented method virtual if it is expected to be overridden in a a child class. In addition to methods and properties, interfaces can declare events and indexers as well. live version · discussion · edit chapter · comment · report an error
Wikibooks | 51
the delegate is declared by the line delegate void Procedure(). in the Main() method. Next. Something concrete has now been created. DelegateDemo demo = new DelegateDemo().Method1).Method1 and DelegateDemo.Method2).WriteLine("Method 3"). (Note: the class name could have been left off of DelegateDemo. A simple example: delegate void Procedure().WriteLine("Method 1"). 52 | C# Programming . It does not result in executable code that does any work. A delegate declaration specifies a particular method signature. The assignment of someProcs to null means that it is not initially referencing any methods. It merely declares a delegate type called Procedure which takes no arguments and returns nothing. adds a non-static method to the delegate instance. someProcs += new Procedure(demo. References to one or more methods can be added to a delegate instance. the statement Procedure someProcs = null. Delegates form the basis of event handling in C#. and someProcs += new Procedure(DelegateDemo. } } In this example. The delegate instance can then be "called" which effectively calls all the methods that have been added to the delegate instance. } static void Main() { Procedure someProcs = null.Method3). } static void Method2() { Console. add two static methods to the delegate instance. This statement is a complete abstraction. someProcs(). class DelegateDemo { static void Method1() { Console.Method2 because the statement is occurring in the DelegateDemo class. instantiates a delegate. someProcs += new Procedure(DelegateDemo.Method2).Chapter 17 17 D ELEGATES Delegates AND E VENTS live version · discussion · edit chapter · comment · report an error D elegates are a construct for abstracting and creating objects that reference methods and can be used to call those methods.) The statement someProcs += new Procedure(demo.Method3). } void Method3() { Console.Method1). someProcs += new Procedure(DelegateDemo. The statements someProcs += new Procedure(DelegateDemo.WriteLine("Method 2").
Invoking a delegate instance that presently contains no method references results in a NullReferenceException. Finally.e. In C# 2. Method3() is called on the object that was supplied when the method was added to the delegate instance.Method1.. for example.Delegates and Events For a non-static method. public void SimulateClick() { if (ButtonClicked != null) { ButtonClicked(). All the methods that were added to the delegate instance are now called in the order that they were added.Method1).0. } Wikibooks | 53 .. an event declared to be public would allow other classes the use of += and -= on the event. the method name is preceded by an object reference. Events An event is a special kind of delegate that facilitates event-driven programming. calls the delegate instance. but firing the event (i. the statement someProcs(). invoking the delegate) is only allowed in the class containing the event. Note that if a delegate declaration specifies a return type and multiple methods are added to a delegate instance. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned). So. Methods that have been added to a delegate instance can be removed with the -= operator: someProcess -= new Procedure(DelegateDemo. A simple example: delegate void ButtonClickedHandler().Method1. someProcess -= DelegateDemo. class Button { public event ButtonClickedHandler ButtonClicked. When the delegate instance is called. Events are class members which cannot be called outside of the class regardless of its access specifier. adding or removing a method reference to a delegate instance can be shortened as follows: someProcess += DelegateDemo. then an invocation of the delegate instance returns the return value of the last method referenced. } } .
ButtonClicked += MyHandler. Even though the event is declared public.Forms namespace. Events are used extensively System. it cannot be directly fired anywhere except in the class containing the event. b.Chapter 17 A method in another class can then subscribe to the event by adding one of its methods to the event delegate: Button b = new Button().Windows. in GUI programming and in the live version · discussion · edit chapter · comment · report an error 54 | C# Programming .
but only to serve as a base to other classes. A class should be made abstract when there are some aspects of the implementation which must be deferred to a more specific subclass.). For example. Although it is not possible to instantiate the Employee class directly. live version · discussion · edit chapter · comment · report an error Wikibooks | 55 .g. TemporaryEmployee. both of which inherit the behavior defined in the Employee class. an Employee can be an abstract class if there are concrete classes that represent more specific types of Employee (e. An abstract class should contain at least one abstract method which derived concrete classes will implement. etc. SalariedEmployee.Abstract Classes 18 A BSTRACT C LASSES live version · discussion · edit chapter · comment · report an error A n abstract class is a class that is never intended to be instantiated directly. a program may create instances of SalariedEmployee and TemporaryEmployee.
Below is the example of a partial class. this does not make a difference as all the fragments of the partial class are grouped and the compiler treats it as a single class.cs) public class Node { public bool Delete() { } public bool Create() { } } Listing 2: Class split across multiple files (file1. To the compiler.Chapter 19 19 P ARTIAL C LASSES live version · discussion · edit chapter · comment · report an error A s the name indicates. Listing 1: Entire class definition in one file (file1. One common usage of partial classes is the separation of automatically generated code from programmer written code.cs) public partial class Node { public bool Create() { } } live version · discussion · edit chapter · comment · report an error 56 | C# Programming .cs) public partial class Node { public bool Delete() { } } (file2. partial class definitions can be split up across multiple physical files.
you can index into it. But in more complicated case with more containers in different parts of program. SomeObjectContainer container2 = new SomeObjectContainer(5). everything is clear. A List is a convenient growable array.int) every time we want to get object from such container. } Console.ReadKey(). and so on.getObject() + (int)container2. without modyfing them. } } And the usage of it would be: class Program { static void Main(string[] args) { SomeObjectContainer container = new SomeObjectContainer(25). } public object getObject() { return this. would not have a string or any other Wikibooks | 57 . we would have to take care that container.getObject()). when you need to create some class to manage objects of some type. // wait for user to press any key. Console. In such small program like this.WriteLine((int)container. supposed to have int type in it. that we have to cast back to original data type we have chosen (in this case . so we could see results } Notice. Generic Interfaces MSDN2 Entry for Generic Interfaces Generic Classes There are cases.obj. usual approach (highly simplified) to make such class would be like this: public class SomeObjectContainer { private object obj. public SomeObjectContainer(object obj) { this.obj = obj. Without Generics. The classic example is a List collection class. It has a sort method.Generics 20 G ENERICS live version · discussion · edit chapter · comment · report an error G enerics is essentially the ability to have type parameters on your type. They are also called parameterized types or parametric polymorphism.
GenericObjectContainer<int> container2 = new GenericObjectContainer<int>(5). and add <T> mark near class name to indicate that this "T" type is Generic / any type. To make our "container" class to support any object and avoid casting. } public T getObject() { return this.ReadKey(). and avoid previously mentioned problems. we could surround every unsafe area with try . // wait for user to press any key. However.WriteLine(container. we replace every previous object type with some new name. i. public GenericObjectContainer(T obj) { this. because Generics offers much more elegant solution. or we could create separate "container" for every data type we need. we will incur a performance penalty every time we access the elements of the collection.obj = obj. } } Not a big difference.Chapter 20 data type. due to the Autoboxing feature of C#. this avoids the Autoboxing for struct types. Console.getObject() + container2.e <genKey. If that happens.getObject()). While this example is far from practical. InvalidCastException is thrown. While both ways could work (and worked for many years). Note: You can choose any name and use more than one generic type for class.T. genVal> public class GenericObjectContainer<T> { private T obj. that you specify type for "container" only when creating it. and after that you will be able to use only the type you specified. so we could see results } Generics ensures. it does illustrate some situations where generics are useful: • You need to keep objects of single type in some class 58 | C# Programming . such as int. which results in simple and safe usage: class Program { static void Main(string[] args) { GenericObjectContainer<int> container = new GenericObjectContainer<int>(25). just to avoid casting.catch block. In addition. Additionally.obj. if the original data type we have chosen is a struct type. it is unnecessary now. } Console. But now you can create containers for different object types. in this case .
short. or any custom struct) in a collection class without incurring the performance penalty of Autoboxing every time you manipulate the stored elements. string.Generics You don't need to modify objects You need to manipulate objects in some way • You wish to store a "value type" (such as int. • • live version · discussion · edit chapter · comment · report an error Wikibooks | 59 .
. In many languages the solution is to explicitly close the file and dispose of the objects and many C# programmers do just that. This means that the reference count goes to zero as soon as the function ends which results in calls to the Terminate event handlers of both objects. In Visual Basic Classic this is not necessary because both objects are declared locally. If you are coming to C# from Visual Basic Classic you will have seen code like this: Public Function Read(ByRef FileName) As String Dim oFSO As FileSystemObject Set oFSO = New FileSystemObject Dim oFile As TextStream Set oFile = oFSO. In C# this doesn't happen because the objects are not reference counted. However. The finalizers will not be called until the garbage collector decides to dispose of the objects. This causes a problem because the file is held open which might prevent other processes from accessing it.finally 60 | C# Programming . Those event handlers close the file and release the associated resources. } } Behind the scenes the compiler turns the using statement into try.ReadLine End Function Note that neither oFSO nor oFile are explicitly disposed of.Chapter 21 21 O BJECT L IFETIME live version · discussion · edit chapter · comment · report an error Introduction D ifferent programming languages deal with issues of object lifetime in different ways and this must be accounted for when writing programs because some objects must be disposed of at specific moments while others can be allowed to exist until the program terminates or a garbage collector disposes of it. ForReading. there is a better way: use the using statement: public read(string fileName) { using (TextReader textReader = new StreamReader(filename)) { return textReader.ReadLine(). If the program uses very little memory this could be a long time. False) Read = oFile.OpenTextFile(FileName.
IDisposable::Dispose() IL_0024: endfinally } // end handler IL_0025: ldloc. try.maxstack 5 . RAII is a natural technique in languages like Visual Basic Classic and C++ that have deterministic finalization but usually requires extra work to include in programs written in garbage collected languages like C# and VB.IO.Object Lifetime and produces this intermediate language (IL) code: .try finally { IL_0018: ldloc.0 IL_0019: brfalse IL_0024 IL_001e: ldloc.NET.TextReader::ReadLine() IL_000d: stloc.try { IL_0007: ldloc. Add notes on RAII. Resource Acquisition Is Initialisation The application of the using statement in the introduction is an example of an idiom called Resource Acquisition Is Initialisation (RAII). live version · discussion · edit chapter · comment · report an error Wikibooks | 61 . memoization and cacheing (see OOP wikibook).0 IL_0008: callvirt instance string [mscorlib]System.TextReader V_0.ctor(string) IL_0006: stloc.0 IL_0001: newobj instance void [mscorlib]System. namely a call to the destructor of the Streamreader instance. and finally. string V_1) IL_0000: ldarg.locals init (class [mscorlib]System.method public hidebysig static string Read(string FileName) cil managed { // Code size 39 (0x27) .0 . Of course you could write the try. Work in progress: add C# versions showing incorrect and correct methods with and without using. The using statement makes it just as easy. For a thorough discussion of the RAII technique see HackCraft: The RAII Programming Idiom. See Understanding the 'using' statement in C# By TiNgZ aBrAhAm.0 IL_001f: callvirt instance void [mscorlib]System.1 IL_000e: leave IL_0025 IL_0013: leave IL_0025 } // end . The finally block includes code that was never explicitly specified in the original C# source code. Wikipedia has a brief note on the subject as well: Resource Acquisition Is Initialization.1 IL_0026: ret } // end of method Using::Read Notice that the body of the Read function has been split into three parts: initialisation.StreamReader::..finally code out explicitly and in some cases that will still be necessary.IO.IO.
A transparent copy of this document is available at Wikibooks:C Sharp Programming. The template from which the document was created is available at Wikibooks:Image:PDF template.org/wiki/C_Sharp_Programming.sxw.sxw. The SXW source of this PDF document is available at Wikibooks:Image:C Sharp Programming.wikibooks.Chapter 22 22 H ISTORY & D OCUMENT N OTES Wikibook History This book was created on 2004-06-15 and was developed on the Wikibooks project by the contributors listed in the next section. 62 | C# Programming . The latest version may be found at. PDF Information & History This PDF was created on 2007-07-15 based on the 2007-07-14 version of the C# Programming Wikibook.
Boly38. Ohms law.Authors 23 A UTHORS Principal Authors • • • • • • Rodasmith (Contributions) Jonas Nordlund (Contributions) Eray (Contributions) Jlenthe (Contributions) Nercury (Contributions) Ripper234 (Contributions) All Authors Andyrewww. Hyad. Fly4fun. Pcu123456789. Whiteknight. Zr40 Wikibooks | 63 . David C Walls. Dm7475. Orion Blastar. Mkn. Szelee. Northgrove. Darklama. Magnus Manske. Kernigh. Cpons. Jokes Free4Me. Eray. Charles Iliya Krempeaux. Dethomas. Chmohan. Scorchsaber. Arbitrary. Jonas Nordlund. Minun. Huan086. Jesperordrup. Frank. Peachpuff. Panic2k4. Bacon. Jlenthe. Yurik. Ripper234. Devourer09. Thambiduraip. Rodasmith. Herbythyme. Mshonle. Derbeth. Shall mn. Chowmeined. Nanodeath. Lux-fiat. Sytone. Plee. Nym. Bijee. Withinfocus. Nercury. Kwhitefoot. Hagindaz. Feraudyh. Luke101. Krischik. HGatta. Fatcat1111. Jguk.
51 Franklin St. because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does.2001. PREAMBLE The purpose of this License is to make a manual. and is addressed as "you".2. MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document. modify or distribute the work in a way requiring permission under copyright law. with or without modifying it. Inc. Any member of the public is a licensee. it can be used for any textual work. or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it. either commercially or noncommercially. Fifth Floor.Chapter 24 24 GNU F REE D OCUMENTATION L ICENSE Version 1. while not being considered responsible for modifications made by others. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work. 0. 64 | C# Programming . that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. refers to any such manual or work. this License preserves for the author and publisher a way to get credit for their work. which is a copyleft license designed for free software. which means that derivative works of the document must themselves be free in the same sense. You accept the license if you copy. Such a notice grants a world-wide. textbook. Boston. It complements the GNU General Public License. November 2002 Copyright (C) 2000. regardless of subject matter or whether it is published as a printed book. 1. below. unlimited in duration. but changing it is not allowed. either copied verbatim. We recommend this License principally for works whose purpose is instruction or reference. in any medium. A "Modified Version" of the Document means any work containing the Document or a portion of it. We have designed this License in order to use it for manuals for free software.2002 Free Software Foundation. The "Document". But this License is not limited to software manuals. or with modifications and/or translated into another language. to use that work under the conditions stated herein. Secondarily. royalty-free license. This License is a kind of "copyleft".
A copy made in an otherwise Transparent file format whose markup. as FrontCover Texts or Back-Cover Texts.) The relationship could be a matter of historical connection with the subject or with related matters. Wikibooks | 65 . preceding the beginning of the body of the text. and the machinegenerated HTML. and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy that is not "Transparent" is called "Opaque". in the notice that says that the Document is released under this License. Texinfo input format. Examples of suitable formats for Transparent copies include plain ASCII without markup. "Title Page" means the text near the most prominent appearance of the work's title. The Document may contain zero Invariant Sections. as being those of Invariant Sections. ethical or political position regarding them. PostScript or PDF designed for human modification. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. if the Document is in part a textbook of mathematics. The "Title Page" means. a Secondary Section may not explain any mathematics. the title page itself. (Thus. An image format is not Transparent if used for any substantial amount of text. that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor. For works in formats which do not have any title page as such. the material this License requires to appear in the title page. A "Transparent" copy of the Document means a machine-readable copy. The "Cover Texts" are certain short passages of text that are listed. SGML or XML for which the DTD and/or processing tools are not generally available. commercial. plus such following pages as are needed to hold. The "Invariant Sections" are certain Secondary Sections whose titles are designated. If the Document does not identify any Invariant Sections then there are none. for a printed book. in the notice that says that the Document is released under this License. legibly. PostScript or PDF produced by some word processors for output purposes only. or of legal. has been arranged to thwart or discourage subsequent modification by readers is not Transparent. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors. A Front-Cover Text may be at most 5 words.GNU Free Documentation License. XCF and JPG. represented in a format whose specification is available to the general public. Examples of transparent image formats include PNG. SGML or XML using a publicly available DTD. and a Back-Cover Text may be at most 25 words. and standard-conforming simple HTML. philosophical. or absence of markup. LaTeX input format.
COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document. 2. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. you may accept compensation in exchange for copies. and continue the rest onto adjacent pages. Copying with changes limited to the covers. "Endorsements". "Dedications". under the same conditions stated above. either commercially or noncommercially. and Back-Cover Texts on the back cover. but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. and that you add no other conditions whatsoever to those of this License. numbering more than 100. However. 3.Chapter 24 A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. all these Cover Texts: Front-Cover Texts on the front cover. Both covers must also clearly and legibly identify you as the publisher of these copies. as long as they preserve the title of the Document and satisfy these conditions. clearly and legibly. such as "Acknowledgements". (Here XYZ stands for a specific section name mentioned below. and the Document's license notice requires Cover Texts. If you publish or distribute Opaque copies of the Document numbering more 66 | C# Programming . You may add other material on the covers in addition. can be treated as verbatim copying in other respects. and the license notice saying this License applies to the Document are reproduced in all copies. and you may publicly display copies. the copyright notices. provided that this License. The front cover must present the full title with all words of the title equally prominent and visible.) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. These Warranty Disclaimers are considered to be included by reference in this License. If the required texts for either cover are too voluminous to fit legibly. VERBATIM COPYING You may copy and distribute the Document in any medium. or "History". you should put the first ones listed (as many as fit reasonably) on the actual cover. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. You may also lend copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. you must enclose the copies in covers that carry.
to give them a chance to provide you with an updated version of the Document. you must either include a machine-readable Transparent copy along with each Opaque copy. in the form shown in the Addendum below. Preserve its Title. G. thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above. or state in or with each Opaque copy a computernetwork location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document. that you contact the authors of the Document well before redistributing any large number of copies. free of added material. Include an unaltered copy of this License. I. F. as the publisher. but not required. as authors. immediately after the copyright notices. 4.GNU Free Documentation License than 100. with the Modified Version filling the role of the Document. if there were any. C. you must take reasonably prudent steps. You may use the same title as a previous version if the original publisher of that version gives permission. Include. Preserve the section Entitled "History". and publisher of the Wikibooks | 67 . H. If you use the latter option. if it has fewer than five). Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. new authors. E. unless they release you from this requirement. Use in the Title Page (and on the covers. year. together with at least five of the principal authors of the Document (all of its principal authors. List on the Title Page. to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. be listed in the History section of the Document). provided that you release the Modified Version under precisely this License. one or more persons or entities responsible for authorship of the modifications in the Modified Version. B. a license notice giving the public permission to use the Modified Version under the terms of this License. Preserve all the copyright notices of the Document. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. if any) a title distinct from that of the Document. It is requested. and from those of previous versions (which should. when you begin distribution of Opaque copies in quantity. D. you must do these things in the Modified Version: A. and add to it an item stating at least the title. In addition. State on the Title page the name of the publisher of the Modified Version.
and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. For any section Entitled "Acknowledgements" or "Dedications". The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. previously added by you or by arrangement made by the same entity you are acting on behalf of. year. These titles must be distinct from any other section titles. unaltered in their text and in their titles. then add an item describing the Modified Version as stated in the previous sentence. L. You may omit a network location for a work that was published at least four years before the Document itself. To do this. Preserve any Warranty Disclaimers. but you may replace the old one. K. If the Document already includes a cover text for the same cover. create one stating the title. Preserve all the Invariant Sections of the Document. M. O. add their titles to the list of Invariant Sections in the Modified Version's license notice. If there is no section Entitled "History" in the Document. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. authors. Delete any section Entitled "Endorsements". Preserve the network location. if any. J. you may not add another.Chapter 24 Modified Version as given on the Title Page. given in the Document for public access to a Transparent copy of the Document. and a passage of up to 25 words as a Back-Cover Text. You may add a passage of up to five words as a Front-Cover Text. Section numbers or the equivalent are not considered part of the section titles. These may be placed in the "History" section. Preserve the Title of the section. or if the original publisher of the version it refers to gives permission. N. provided it contains nothing but endorsements of your Modified Version by various parties--for example. you may at your option designate some or all of these sections as invariant. on explicit permission from the previous publisher that added the old one. Such a section may not be included in the Modified Version. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document. and publisher of the Document as given on its Title Page. to the end of the list of Cover Texts in the Modified Version. You may add a section Entitled "Endorsements". 68 | C# Programming . Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. and likewise the network locations given in the Document for previous versions it was based on.
under the terms defined in section 4 above for modified versions. Wikibooks | 69 . and any sections Entitled "Dedications". provided you insert a copy of this License into the extracted document. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works. or else a unique number. and that you preserve all their Warranty Disclaimers. provided that you include in the combination all of the Invariant Sections of all of the original documents. make the title of each such section unique by adding at the end of it. You must delete all sections Entitled "Endorsements. The combined work need only contain one copy of this License. and multiple identical Invariant Sections may be replaced with a single copy. and follow this License in all other respects regarding verbatim copying of that document. You may extract a single document from such a collection. forming one section Entitled "History". When the Document is included in an aggregate. in parentheses. 7. and replace the individual copies of this License in the various documents with a single copy that is included in the collection. you must combine any sections Entitled "History" in the various original documents. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License. COMBINING DOCUMENTS You may combine the Document with other documents released under this License. and list them all as Invariant Sections of your combined work in its license notice. unmodified. and distribute it individually under this License. is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. in or on a volume of a storage or distribution medium. If there are multiple Invariant Sections with the same name but different contents.GNU Free Documentation License 5. likewise combine any sections Entitled "Acknowledgements". this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. the name of the original author or publisher of that section if known." 6. In the combination.
If the Document does 70 | C# Programming . then if the Document is less than one half of the entire aggregate. revised versions of the GNU Free Documentation License from time to time.org/copyleft/. However. the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. or rights. and will automatically terminate your rights under this License. or "History". or distribute the Document except as expressly provided for under this License. Each version of the License is given a distinguishing version number. See. modify. 9. Any other attempt to copy. 8. 10. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer. TRANSLATION Translation is considered a kind of modification. you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. Such new versions will be similar in spirit to the present version. sublicense. If a section in the Document is Entitled "Acknowledgements". or the electronic equivalent of covers if the Document is in electronic form.gnu. and all the license notices in the Document. Otherwise they must appear on printed covers that bracket the whole aggregate. parties who have received copies. the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate. but may differ in detail to address new problems or concerns. You may include a translation of this License. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new. modify. and any Warranty Disclaimers. sublicense or distribute the Document is void. "Dedications". Replacing Invariant Sections with translations requires special permission from their copyright holders. but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. from you under this License will not have their licenses terminated so long as such parties remain in full compliance. so you may distribute translations of the Document under the terms of section 4.Chapter 24 If the Cover Text requirement of section 3 is applicable to these copies of the Document. If the Document specifies that a particular numbered version of this License "or any later version" applies to it. provided that you also include the original English version of this License and the original versions of those notices and disclaimers. TERMINATION You may not copy. the original version will prevail.
GNU Free Documentation License not specify a version number of this License. you may choose any version ever published (not as a draft) by the Free Software Foundation. External links • • GNU Free Documentation License (Wikipedia article on the license) Official GNU FDL webpage Wikibooks | 71 . | https://www.scribd.com/document/36484847/C | CC-MAIN-2017-09 | refinedweb | 17,068 | 52.15 |
This guide describes how to convert an existing Android app to an Android add-on. If you are building an Android add-on from scratch, build it as a stand-alone Android app first, then follow these steps to make it an Android add-on.
If you're new to Android app development you may want to begin by following the Android Developer tutorial for Building Your First Android App.
Modify your Android manifest
Exposing add-on functionality from an existing Android app is as easy as adding
an
<intent-filter> to your app's Android manifest. In your app's manifest file
, find the activity you’d like to expose as an add-on and add an
<intent-filter> tag indicating your app can handle add-on intents, as
demonstrated in this example:
<activity android: <intent-filter android: <action android: </intent-filter> </activity>
Adding this
intent-filter causes your add-on to be shown in the add-ons
Menu in the Google Sheets app. You should provide an icon and label to be shown
in the add-ons menu by specifying
android:label and
android:icon attributes
for your intent filter (see
Providing Resources
and
Accessing Resources from XML
).
To have your add-on extend Google Docs instead of Sheets, simply change the
value of the
<action> tag in the above example from:
"com.google.android.apps.docs.editors.sheets.ADDON"
to
"com.google.android.apps.docs.editors.docs.ADDON"
If your
activity
can extend both Docs and Sheets, include both
<action/> tags in the
intent-filter. Your add-on can determine at runtime which editor triggered it
using your activity's
getCallingPackage()
method.
For more background on the intent-based mechanisms Android apps use to communicate, see Intents and Intent Filters.
Provide a default launcher activity
Most Android apps define a default launcher activity in their manifest. This activity is the first one started when the app is launched from the device's Home screen, and serves as the main entry point to the app.
Always include a launcher activity, even if launching your Android add-on on its own isn't useful. This handles cases when the add-on is launched directly, for example if a user taps the install notification.
If you are extending an existing Android app to be an Android add-on, chances are you already have a launcher activity. If you don't, be sure to create one. If the add-on functionality needs context from the Docs or Sheets apps to function at all, make a simple launcher activity that explains this to the user and provides a button to close the app.
Set Android permissions
Android add-on apps must have the
GET_ACCOUNTS Android permission. This is
necessary to allow your app to receive the Google account associated with the
active document.
To request this permission, place the following tag in the
<manifest> section
of your app’s Android manifest. Many existing apps already request this
permission.
<uses-permission android:
In addition, your add-on should also make use of runtime permissions when possible and follow the runtime permission best practices.
Modify your add-on activity
When a user selects your add-on from the Add-ons menu in a
Google Workspace document editor, the activity specified in your manifest is
started. In your activity’s
onCreate method record the intent used to start
your activity as it contains:
- The document ID of the doc or sheet currently open in the editor app.
- The session state of that doc or sheet (as an encoded String).
- The account of the user calling the add-on.
You can get this intent by calling your activity’s getIntent() method. The resulting activity should resemble this example:
import android.accounts.Account; import android.app.Activity; public class MyAddOnActivity extends Activity { // Your activity... String sessionState; String docId; Account account; @Override protected void onCreate(Bundle state) { super.onCreate(state); docId = getIntent().getStringExtra( "com.google.android.apps.docs.addons.DocumentId"); sessionState = getIntent().getStringExtra( "com.google.android.apps.docs.addons.SessionState"); account = (Account) getIntent().getParcelableExtra( "com.google.android.apps.docs.addons.Account"); // Your activity’s initialization... } } }
When your activity is finished and is ready to return the user back to the
Google editor, set the result code and call your activity's
finish() method,
like so:
setResult(Activity.RESULT_OK); finish();
Use document context with the Apps Script API
Most Android add-ons make use of Apps Script API to
execute Apps Script functions. When using
the API, including the session state ensures that Apps Script functions have
the correct document context. With the document context, the API Script
functions can call Apps Script methods normally restricted to calls
from container-bound scripts. For example, passing
context of a Google Doc enbles the called function to use
DocumentApp.getActiveDocument().
In order to ensure the Apps Script API has the correct context when called from
an Android app, you just have to include the session state string when building
the
ExecutionRequest object: }
See the Apps Script API Android example for an example of how to call an Apps Script function from an Android app using the API.
Create OAuth credentials
Before your Android add-on can execute functions with the Apps Script API, you must enable the API in its associated Cloud Platform project. In addition, the add-on needs a valid Android OAuth credential, created using a SHA1 key.
You must properly sign any release build before uploading it to the Google Play Store, using a keystore you create and a key specific to that app. Because they depend on a different keystore, release builds need their own OAuth credential. This is built using the same steps used to create the debug build credential, except that you can get the SHA1 key using:
$ keytool -exportcert -alias <key_alias> -keystore <path_to_keystore_file> -list -v
This command asks you for the keystore password you set when you created the keystore (do not share this password with anyone).
Alternatively, you can also get the SHA1 keys for all your defined builds by running a signing report task from within Android Studio:
- Click Gradle on the right side of the IDE window.
- Navigate to MyApplication > Tasks > android and double-click signingReport.
- To view the report, click Gradle Console at the bottom of the IDE window.
A Cloud Platform project can support multiple Android OAuth credentials, so you can create as many as you need.
Run your unpublished add-on
Only add-ons approved through the curation process are normally visible in the editors’ menus. During development a not-yet-reviewed add-on can be treated as though it were approved by setting the app as the system debug app. Once you have an Android device in developer mode and attached to a development machine via USB, you can set your app as the debug app by running the Android Debug Bridge command:
$ adb shell am set-debug-app --persistent <YOUR_PACKAGE_NAME>
This allows both debug and release builds of your add-on to run on your device.
The system debug app can be unset with:
$ adb shell am clear-debug-app | https://developers.google.com/workspace/add-ons/mobile/android | CC-MAIN-2021-21 | refinedweb | 1,184 | 51.58 |
NAME
COPY - copy data between a file and a table
SYNOPSIS
COPY tablename [ ( column [, ...] ) ] FROM { ’filename’ | STDIN } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] ’delimiter’ ] [ NULL [ AS ] ’null string’ ] [ CSV [ HEADER ] [ QUOTE [ AS ] ’quote’ ] [ ESCAPE [ AS ] ’escape’ ] [ FORCE NOT NULL column [, ...] ] COPY { tablename [ ( column [, ...] ) ] | ( query ) } TO { ’filename’ | STDOUT } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] ’delimiter’ ] [ NULL [ AS ] ’null string’ ] [ CSV [ HEADER ] [ QUOTE [ AS ] ’quote’ ] [ ESCAPE [ AS ] ’escape’ ] [ FORCE QUOTE column [, ...] ]
DESCRIPTION PostgreSQL server to directly read from or write to a file. The file must be accessible to the server and the name must be specified from the viewpoint of the server. When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
PARAMETERS
tablename The name (optionally schema-qualified) of an existing table. column An optional list of columns to be copied. If no column list is specified, all columns of the table will be copied. query A SELECT [select(7)] or VALUES [values(7)] command whose results are to be copied. Note that parentheses are required around the query. filename The absolute path name of the input or output file. Windows users might need to use an E’’ string and double backslashes used as path separators. STDIN Specifies that input comes from the client application. STDOUT Specifies that output goes to the client application. BINARY Causes all data to be stored or read in binary format rather than as text. You cannot specify the DELIMITER, NULL, or CSV options in binary mode. an unquoted empty string in CSV mode. You might prefer an empty string even in text mode for cases where you don’t want to distinguish nulls from empty strings. Note: When using COPY FROM, any data item that matches this string will be stored as a null value, so you should make sure that you use the same string as you used with COPY TO. CSV Selects Comma Separated Value (CSV) mode. HEADER Specifies that the file contains a header line with the names of each column in the file. On output, the first line contains the column names from the table, and on input, the first line is ignored. quote Specifies the ASCII quotation character in CSV mode. The default is double-quote. escape Specifies the ASCII character that should appear before a QUOTE data character value in CSV mode. The default is the QUOTE value (usually (’’), this causes missing values to be input as zero-length strings.
OUTPUTS
On successful completion, a COPY command returns a command tag of the form COPY count The count is the number of rows copied.
NOTES
COPY can only be used with plain tables, not with views. However, you can write COPY (SELECT * FROM viewname) TO .... The BINARY key word causes all data to be stored/read as binary format rather than as text. It is somewhat faster than the normal text mode, but a binary-format file is less portable across machine architectures and PostgreSQL versions. Also, the binary format is very data type specific; for example it will not work to output binary data from a smallint column and read it into an integer column, even though that would work fine in text format. You must have select privilege on the table whose values are read by COPY TO, and insert privilege on the table into which values are inserted by COPY FROM. It is sufficient to have column privileges on the column(s) listed in the command.. COPY naming a file (normally the cluster. It is also a good idea to avoid dumping data with IntervalStyle set to sql_standard, because negative interval values might be misinterpreted by a server that has a different setting for IntervalStyle. Input data is interpreted according to the current client encoding, and output data is encoded in the the current client encoding, even if the data does not pass through the client but is read from or written to a file. as \\N). The following special backslash sequences are recognized by COPY FROM: SequenceRepresents\bBackspace (ASCII 8)\fForm feed (ASCII 12)\nNewline (ASCII 10)\rCarriage return (ASCII 13)\tTab (ASCII 9)\vVertical tab (ASCII 11)\digitsBackslash followed by one to three octal digits specifies the character with that numeric code\xdigitsBackslash x followed by one or two hex digits specifies the character with that numeric code Presently, COPY TO will never emit an octal or hex recognizes. The CSV format has no standard way to distinguish a NULL value from an empty string. PostgreSQL’s COPY handles this by quoting. A NULL is output as the NULL parameter string and is not quoted, while a non-NULL value matching the NULL parameter string is quoted. For example, with the default settings, a NULL is written as an unquoted empty string, while an empty string data value. Note: In CSV mode, all characters are significant. A quoted value surrounded by white space, or any characters other than DELIMITER, will include those characters. This can cause errors if you import data from a system that pads CSV lines with white space out to some fixed width. If such a situation arises you might need to preprocess the CSV file to remove the trailing white space, before importing the data into PostgreSQL. Note: CSV mode will both recognize and produce CSV files with quoted values containing embedded carriage returns and line feeds. Thus the files are not strictly one line per table row like text-mode files. might add a header field that allows per-column format codes to be specified. into the country table: COPY country FROM ’/usr1/proj/bray/sql/country_data’; To copy into a file just the countries whose names start with ’A’: COPY (SELECT * FROM country WHERE country_name LIKE ’A%’) TO ’/usr1/proj/bray/sql/a_list_countries.copy’; Here is a sample of data suitable for copying into a table from STDIN: AF AFGHANISTAN AL ALBANIA DZ ALGERIA ZM ZAMBIA ZW ZIMBABWE Note that the white space on each line is actually a tab character. The following is the same data, output in binary format. The data is shown after filtering through the Unix utility od -c. The table has three columns; the first has type char(2), the second has type text, and the third has type integer. All the rows have a null value in the third column. 0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0 0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A 0000040 F G H A N I S T A N 377 377 377 377 \0 003 0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I 0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0 0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0 0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377 0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I 0000200 M B A B W E 377 377 377 377 377 377
COMPATIBILITY
There is no COPY statement’ ] | http://manpages.ubuntu.com/manpages/maverick/man7/copy.7.html | CC-MAIN-2014-35 | refinedweb | 1,210 | 67.79 |
<?
<
</
View?
i created a service.cs file with the following code then tried to create proxy using svcutil comand.... but it gave error "not able to obtain metadata". After some web search i found i need to add a meta endpoint to the service. so i copied and pasted the
code... now svcutil works and creates the proxy.cs. BUT ITS ALSO CREATED A CONFIG FILE. i want to know Do i really need this config file?? if yes then can u please describe its content to me...i will be highly thankfull to you.
INITIAL CODE:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Service
{
[ServiceContract]
interface Iservice
{
[OperationContract]
string getMyDeals();
}
class Service : Iservice
{
public string getMyDeals()
{
hi
for a single proxy server we make the following changes in web.config file.
<system.net>
<defaultProxy>
<proxy proxyaddress="" bypassonlocal="true" />
</defaultProxy>
</system.net>
any help would be appreciated. | http://www.dotnetspark.com/links/38509-first-wcf-connection-slow-and-proxy-settings.aspx | CC-MAIN-2018-26 | refinedweb | 150 | 53.58 |
Feeling a little frustrated as I just spent a considerable amount of time figuring out how to retrieve an item by index from a Seq. Finally figured it out. It can be done using the lift method. This method is also supported by other collections.
This is the code snippet from REPL:
scala> Seq(1,2,3,4,5) res0: Seq[Int] = Seq(1, 2, 3, 4, 5) scala> res0 lift 452 res1: Option[Int] = None scala> res0 lift 0 res2: Option[Int] = Some(1)
From the Scala documentation:
def lift: (Int) ? Option[A] Turns this partial function into a plain function returning an Option result. returns a function that takes an argument x to Some(this(x)) if this is defined for x, and to None otherwise. Definition Classes PartialFunction See also Function.unlift
Seriously, this is meant to be helpful?
Yes it is very simple to retrieve an item by index once you know how to. Hope this saves someone else some frustration. Happy coding 🙂 | https://nidkil.me/2014/11/05/retrieving-an-item-from-a-seq-by-index/ | CC-MAIN-2021-10 | refinedweb | 167 | 65.83 |
Hot questions for Using Neural networks in vectorization
Question:
I have build a RNN language model with attention and I am creating context vector for every element of the input by attending all the previous hidden states (only one direction).
The most straight forward solution in my opinion is using a for-loop over the RNN output, such that each context vector is computed one after another.
import torch import torch.nn as nn import torch.nn.functional as F class RNN_LM(nn.Module): def __init__(self, hidden_size, vocab_size, embedding_dim=None, droprate=0.5): super().__init__() if not embedding_dim: embedding_dim = hidden_size self.embedding_matrix = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hidden_size, batch_first=False) self.attn = nn.Linear(hidden_size, hidden_size) self.vocab_dist = nn.Linear(hidden_size, vocab_size) self.dropout = nn.Dropout(droprate) def forward(self, x): x = self.dropout(self.embedding_matrix(x.view(-1, 1))) x, states = self.lstm(x) #print(x.size()) x = x.squeeze() content_vectors = [x[0].view(1, -1)] # for-loop over hidden states and attention for i in range(1, x.size(0)): prev_states = x[:i] current_state = x[i].view(1, -1) attn_prod = torch.mm(self.attn(current_state), prev_states.t()) attn_weights = F.softmax(attn_prod, dim=1) context = torch.mm(attn_weights, prev_states) content_vectors.append(context) return self.vocab_dist(self.dropout(torch.cat(content_vectors)))
Note: The
forward method here is only used for training.
However this solution is not very efficient as the code is not well parallelizable with computing each context vector sequently. But since the context vectors are not dependent on each other, I wonder if there is a non-sequential way of calculating them.
So is there is a way to compute the context vectors without for-loop so that more of computation can be parallelized?
Answer:
Ok, for clarity: I assume we only really care about vectorizing the
for loop. What is the shape of
x? Assuming
x is 2-dimensional, I have the following code, where
v1 executes your loop and
v2 is a vectorized version:
import torch import torch.nn.functional as F torch.manual_seed(0) x = torch.randn(3, 6) def v1(): for i in range(1, x.size(0)): prev = x[:i] curr = x[i].view(1, -1) prod = torch.mm(curr, prev.t()) attn = prod # same shape context = torch.mm(attn, prev) print(context) def v2(): # we're going to unroll the loop by vectorizing over the new, # 0-th dimension of `x`. We repeat it as many times as there # are iterations in the for loop repeated = x.unsqueeze(0).repeat(x.size(0), 1, 1) # we're looking to build a `prevs` tensor such that # prevs[i, x, y] == prev[x, y] at i-th iteration of the loop in v1, # up to 0-padding necessary to make them all the same size. # We need to build a higher-dimensional equivalent of torch.triu xs = torch.arange(x.size(0)).reshape(1, -1, 1) zs = torch.arange(x.size(0)).reshape(-1, 1, 1) prevs = torch.where(zs < xs, torch.tensor(0.), repeated) # this is an equivalent of the above iteration starting at 1 prevs = prevs[:-1] currs = x[1:] # a batched matrix multiplication prod = torch.matmul(currs, prevs.transpose(1, 2)) attn = prod # same shape context = torch.matmul(attn, prevs) # equivalent of a higher dimensional torch.diagonal contexts = torch.einsum('iij->ij', (context)) print(contexts) print(x) print('\n------ v1 -------\n') v1() print('\n------ v2 -------\n') v2()
which vectorizes your loop, with some caveats. First, I assume
x is 2-dimensional. Secondly, I skip taking the
softmax claiming it doesn't change the size of the input and thus doesn't affect vectorization. That's a true, but unfortunately softmax of a 0-padded vector
v is not equal to a 0-padded softmax of unpadded
v. This can be fixed with renormalization though. Please let me know if my assumptions are correct and whether this is a good enough starting point for your work.
Question:
I would like to know if the following MATLAB/Octave code can be vectorized?
function grads = compute_grads(data, ann, lambda) [~, N] = size(data.X); % First propagate the data S = evaluate(data.X, ann); G = -(data.Y - S{2}); % Second layer gradient is easy. l2g.W = G*S{1}'; l2g.b = mean(G)'; G = G' * ann{2}.W; [m, d] = size(ann{1}.W); [K, ~] = size(ann{2}.W); % I would like to vectorize this calculation. l1g.W = zeros(m, d); l1g.b = mean(G)'; for i = 1:N x = data.X(:, i); g = G(i, :); l1 = S{1}(:, i); g = g * diag(l1 > 0); l1g.W = l1g.W + g'*x'; end grads = {l1g, l2g}; for k=1:length(grads) grads{k}.W = grads{k}.W/N + 2*lambda*ann{k}.W; end end
The code computes the gradients for a two-layer neural network. The second layer has a softmax activation function as shown by line 4
G = -(data.Y - S{2});. The first layer has ReLU activation implemented by the gunk in the
for-loop which operates on each sample at a time.
As you can see, there is an explicit
for-loop in the middle. Are there any array/matrix functions one can use instead to make the looping implicit?
Answer:
The loop can be reduced to:
l1g.W = (data.X * (G .* (S{1} > 0).')).';
Explanation:
In vectorization we should avoid unnecessary operations. For example in
g = g * diag(l1 > 0);;
we can use element-wize multiplication to achieve the same thing:
g = g .* (l1.' > 0); %or g = g .* (l1 > 0).';
Using that we can place some operations outside of the loop:
l1g.W = zeros(m, d); G = G .* (S{1} > 0).'; for i = 1:N x = data.X(:, i); g = G(i, :); l1g.W = l1g.W + g'*x'; end
So we have something like this:
W=0; for i = 1:N W = W + something(i); end
that can be written as:
W = sum(something);
Our loop can be reduced to:
l1g.W = sum(some_structrue_created_by_vectorizing(g'*x'));
We can use functions such as
bsxfun to create such a structure (i.e. a 3D matrix) but often such a structure requires a large amount of memory and the loop may be more efficient than vectorization. But wait we want to do sum of product of
g and
x so we can [and should always] think about using vector-matrix or matrix-matrix multiplication because they are very fast operations.
As we are performing outer product of
g and
x so matrix-matrix multiplication is the right choice.
G = G .* (S{1} > 0).'; l1g.W = (data.X * G).'
or
l1g.W = (data.X * (G .* (S{1} > 0).')).';
Question:
The code below is correct, but I want to vectorize it (and may convert to GPU) to increase the speed.
How can I convert it to vector form?
RF = 4; inhibatory = 0; overlap=3; act_funct = 'sig'; gap = RF-overlap; Image1 = rand(30,22); Image2 = rand(27,19); % size_image2 is equal to 27x19 Image3 = rand(30,22); de_act_output = de_activate_Mat(Image1,act_funct); % finding derivative of the matrix. e.g. de_act_output = act_output.*(1-act_output) in case of sigmoid. for u=1:size(Image1,1) for v=1:size(Image1,2) sum_val=0;)); sum_sens = sum(sum(Image2(iLowMax:iHighMax,jLowMax:jHighMax))); sum_val = sum_sens(:,:) .* Image3(u,v); result(u,v) = de_act_output(u,v) .* sum_val; end end
Answer:
There is a
parallelogram-like structure of blocks you are creating inside the nested loops with
iLowMax:iHighMax,jLowMax:jHighMax which won't lead
to any easy vectorizable codes. But you can go full-throttle vectorization on that if performance is paramount for your case and seems like
convolution would be of good use there. Listing here are some tweaks to
make it faster everything around that step by pre-calculating most other stuffs and this must result in appreciable speedup. Here's the implementation -
U = 1:size(Image1,1); %// Create arrays of iteration steps V = 1:size(Image1,2); %// Calculate arrays of low-high row and column indices)); sens_sums(size(Image1,1),size(Image1,2)) = 0; %// Pre-allocation for u=1:size(Image1,1) for v=1:size(Image1,2) sens = Image2(iLowMax(u):iHighMax(u),jLowMax(v):jHighMax(v)); sens_sums(u,v) = sum(sens(:)); end end result = sens_sums.*Image3.*de_act_output; | https://thetopsites.net/projects/neural-network/vectorization.shtml | CC-MAIN-2021-31 | refinedweb | 1,374 | 60.01 |
This article assumes you have successfully installed NetBeans 4.0 and a Java SDK (also known as a JDK).
We will first explore our new IDE and one of the embedded sample applications. The first section will make
heavy use of screenshots and will let you dive right in - immediately after completing the NetBeans installation.
Then we will learn how to use NetBeans to modify, compile and run a simple Java application. As we progress,
there will be fewer screenshots and more source code. Our pace will accelerate as we learn to use some of
NetBeans' more advanced productivity-enhancing features, while adding interesting enhancements to the
"Anagram Game" sample application. By the end of this article, you will know how to use NetBeans to write
Java code that opens and parses XML documents, requests user input from simple dialogs, and much more.
Most importantly, you'll be well on your way towards creating and extending Java applications on your own.
Let's dive in!
When I first started NetBeans from the Start Menu, it finished loading in about 15 seconds. In some cases, this
may take longer the first time due to the fact that NetBeans is getting to know your system.
At this point you should feel free to nose around a bit - when in doubt, choose "Cancel"! When you're ready to proceed,
go ahead and click the "Sample Project" button under the Welcome graphic.
By default, the project location will be set to your home folder. Let's go ahead and create a folder called "code" under the C: drive,
and then a folder called "java" within it. Then use the Browse button to choose this new folder as the project's location, as shown in
the next screenshot.
After you click "Finish" in the above dialog, a "Scanning Project Classpaths" dialog appears and may last for about one minute.
Now the "Projects" tab in the left "pane" displays a single node titled "AnagramGame". The welcome splash screen is still visible
in the "main" area. Expanding the "AnagramGame" node in the "Projects" tab, and sequentially expanding all its children,
results in the following tree structure:
Above I have resized the main NetBeans window to just show the left "pane".
Of note is that this sample application is comprised of two "source packages" (one a library, the other the user interface), and
one "test package" (for the library). Also of note is that each class, in addition to Fields/Constructors/Methods, has a "Bean Patterns"
node (though this node is empty for each current class above). In this article we will not be using "Bean Pattern" nodes, though you should
know that they aid in making your code more module, flexible and re-usable through the use of
JavaBeans components.
Next we double-click on the "About.java" node - you will see something that looks like this:
If you like, you can now close the "Welcome" tab in the main area/pane. At this time you may once again wish to explore
NetBeans on your own: you can open source files, view visual "forms" for some of the user interface classes, or examine non-source
files by switching from the "Projects" to the "Files" tab of the left pane. There you can look at various .properties files and Ant build
scripts. From the "Tools" menu, the "Options" window will give you an idea of how flexible and customizable this IDE really is!
For good measure, and to make sure you are able to take a break and know how to get started again, let's go ahead and close,
then re-open NetBeans. If you do so, you should find that this time the IDE opens up with a blank main area, and the "Projects"
area will show the AnagramGame project. Now click the "Run Main Project (F6)" button in the
toolbar (it is green and yellow; you can hover to see the icon's title), and NetBeans opens an "Output" window, containing the
following text:
init:
deps-jar:
Created dir: C:\code\java\AnagramGame\build\classes
Compiling 3 source files to C:\code\java\AnagramGame\build\classes
compile:
run:
In addition, a small window pops up, namely the user interface for AnagramGame.
I got the first guess correct on my first try! I think it helped that I browsed through all the project
folders and files earlier, as I recall seeing a long list of words (the list of unscrambled words, I assume)
and that must have helped me out. Let's keep that in mind for later ...
First we will simply change the text of one of the user messages in the sample application. In the "Projects" pane,
double-click the com.toy.anagrams.ui.Anagrams node, and its source will open up as a new tab in the main window area.
The upper left corner of the tab has a "Design" and a "Source" button. Choose the "Source" button if it is not already
selected - you should now see the Java source code for the Anagrams class in the editor. Right-click in the left margin
and make sure that "Show Line Numbers" is checked. Go to line #211 (CTRL-G is quick). This line should read:
feedbackLabel.setText("Incorrect! Try again!");
We will (trivially) alter the text, compile, run the application, guess a word incorrectly, and see the modified message.
I changed mine to read:
feedbackLabel.setText("Not quite ... please try again!");
At this time, note that in the title of the editor tab there is now a small asterisk between the word "Anagrams"
and the "X" (close command). This asterisk is meant to indicate that the file has been modified but not saved.
File->Save (or CTRL-S) will save our changes. So at this time our source file has been modified and saved,
but the compiled class file still reflects the old code. Here's where NetBeans will handle two steps at once
for us: click the green/yellow "Run Main Project" icon, or just hit F6. The application will open up as before.
In the output console, however, you should see the following:
init:
deps-jar:
Compiling 1 source file to C:\code\java\AnagramGame\build\classes
compile:
run:
As you can see, prior to running the application, NetBeans (actually our Ant build script) realized that a file
had been modified and compiled it for us before executing the "run task". Go ahead and enter a guess, preferably
something incorrect. If all went as expected, the feedback message should now appear with the text that you customized above.
Go ahead and play a couple rounds - I got stock at "iccrmutsnaec". For purposes of demonstrating further
essential capabilities of NetBeans, I'm going to cheat and search the source code for the solution. This presupposes
that the jumbled versions of each word are listed in one of the project's source files, rather than being generated
each time by randomly jumbling the original word. In a minute, we'll see that this is indeed the nature of the current
implementation, later on we'll do something about that ...
In the "Projects" tab, right click on the "Source Packages" node and select "Find ..." from the context menu.
You will be presented with the following screen, called "Find":
In this screenshot, you can see that I already entered the text "iccrmutsnaec" as my search term.
We'll leave all other settings as they are and click "Search" to begin the process. A new tab will appear
next to the output console, indicating the results of the search. As you can see, one match was found,
in file "WordLibrary.java", at line #53:
Double-click on the match (the node labeled as "iccrmutsnaec", [position 63:10] above). This will open the
corresponding source file in the editor, ensure the appropriate line is within view, and highlight the matching phrase.
What you should see is that the term "iccrmutsnaec" is the sixth entry in an array of strings; this array is called
"SCRAMBLED_WORD_LIST". Now observe that immediately above this array is another array of strings, but
there the entries appear to be actual English language words. Let's see what that array is called: "WORD_LIST".
At this point I'm sure we've all figured out that the solution to the scrambled word "iccrmutsnaec" can be found
as the sixth entry of the "WORD_LIST" array. Of course, it is possible that the original author chose a less obvious mapping
between the clear-text words and their scrambled versions, but fortuitously they did not! So, looking at line #16 we
see the word "circumstance". Typing this word into the application (if you closed it in the meantime, you may play
again until you reach the appropriate point), we see the following screen:
By now we know how to open a file for editing, modify the source code, compile and run the application,
search the source code, and cheat. Let's put some of these skills together to make the AnagramGame more interesting.
We are going to implement dynamic generation of scrambled words, eliminating the need for maintaining a list of
scrambled words in the source code. As a result, we'll eliminate one way for us to cheat. In a second step we
will then ensure that the scrambled versions are generated at random, so that the game-play becomes more interesting.
Still within the WordLibrary source you will see a method called "getScrambledWord". Examining this method more closely,
we see that its implementation is extremely simple:
return SCRAMBLED_WORD_LIST[idx];
This is indeed a good place to make our modifications. Let's start by changing this line (#126) to the following:
return generateScrambledWord(idx);
NetBeans now marks this line of code with a red wavy underline and a red X icon in the margin, indicating that
there it has found a syntactic problem in our source. If we place the cursor over any part of the underlined source, a
small message appears, indicating that it does not recognize the method signature generateScrambledWord(int).
Of course, we havent created this method yet, so let's do so now. We will simply add it to the end of the class,
starting at line #147:
/**
* For a specified index, finds the corresponding word in the
* dictionary and generates a scrambled version of this word.
* @param idx index of the word to be scrambled
* @return a scrambled version of the relevant word
*/
protected static String generateScrambledWord(int idx)
{
int j = 0;
String word;
String scrambled = "";
java.util.Random r;
r = new java.util.Random();
word = getWord(idx);
for (j = 0; j <word.length(); j++)
{
if ( r.nextBoolean() )
scrambled = scrambled + word.charAt(j);
else
scrambled = word.charAt(j) + scrambled;
}
return scrambled;
}
The purpose of our generateScrambledWord(int) function is to return a scrambled version of the dictionary
entry specified by the integer argument, the index. Im sure we could think of a number of different ways to
scramble (re-order) the letters of a word, and you are free to implement the body of this method in whatever
way you deem fit. This could be as simple as reversing the order of the letters, but then the game might be too
easy (still, go ahead and give it a try). Alternatively, we could swap the position of any two adjacent letters, one
pair at a time, until we reach the end of the word. Let your imagination take hold and find an algorithm that is
fun to implement and provides for a fun game. Let me briefly explain the thought behind the implementation Ive
given in this example. I have chosen to use Javas built-in random number generation utility in such a way that the
result of scrambling a given word will look different each time it is generated. We construct the scrambled word
one letter at a time, and for each new letter, we let a random number determine whether to add the new letter
at the beginning or the end of the word fragment. In this way we construct a new word, consisting of all the letters
of the original word, but in a new and somewhat randomized sequence. At this point, go ahead and run the
application. This time around I was unable to correctly guess many of the words, but due to the randomness
of the sequencing, every now and then you can expect to see a scrambled word that closely resembles its
un-scrambled form. One thing you can try is to modify the algorithm above to re-order pairs of characters
instead of individual characters the resulting words may be a bit easier to identify. If you implement an algorithm
that makes for especially compelling game play, please share it with all the readers of this piece.
At this time, we are no longer making use of the scrambled word dictionary (the SCRAMBLED_WORD_LIST array),
so lets go ahead and remove it from the WordLibary.java source (lines 57 to 104).
If you play the new version of the game, you may (as I did) become frustrated at your inability to identify the
underlying words. What to do? Well, we know that the original words are stored in a simple dictionary, and we also
know that the game steps through that dictionary one word at a time, from start to end. So with the current code,
since we have access to the source, we can still cheat by keeping track of how many words have already been tried
and looking up the corresponding dictionary entry. When I run the game, the first scrambled word I see is noiatabsrct
and I dont immediately recognize it. But if I go to line #11 in WordLibrary.java I see that the first dictionary entry is
abstraction. Our next goal will be to randomize the order in which words are taken from the dictionary, and we will
do so again by using the Random class of the java.util package. As we are using this class twice now, lets have a
quick look at its API documentation, so that we have a basic understanding of what it does for us:.
So far, we have used the zero-argument constructor for java.util.Random, out of convenience. As the API
comments above indicate, we should take care to initialize each instance of Random with a unique seed, otherwise
repeated use of the application may not have a sufficiently random nature. Looking at the
documentation for the
zero-argument constructor, we see that it actually uses the current time (in milliseconds)
as a seed, so our existing code is okay and we can proceed on to more important things.
What changes do we need to make to randomize the order in which words are chosen from the dictionary? In our
WordLibrary class, we see that there are two methods that seem relevant: both getWord(int idx) and
getScrambledWord(int idx) accept as their argument an index into the dictionary. We will first place the cursor
within the method name of getWord, then right-click and choose the option Find Usages. We see three calls
to this method (one in WordLibraryTest, two in WordLibrary itself). Each of these is used internally by the WordLibrary
component (including its test harness) and we dont need to change anything there. Next, we will place our cursor
within the method name of getScrambledWord, then type Alt-F7. Once again we see three usages of the method,
but now two of them are within the Anagrams class let us focus our attention on these. In both cases (lines 28 and 195)
the argument value passed to getScrambledWord is a variable called wordIdx. This variable itself is declared on line 22
and initialized to zero. Let us search for usages of the wordIdx variable: there are three.
We now see that the wordIdx variable determines which word is chosen after each guess, and this variable
is only modified in one place, namely line #192 of Anagrams.java:
wordIdx = (wordIdx + 1) % WordLibrary.getSize();
To randomize the order in which words are chosen from the dictionary, we need to modify this line such that
wordIdx takes on random values falling within the lower and upper limits of the dictionary.
The java.util.Random.nextInt(int n) method does exactly this, so lets go ahead and replace
line #192 with the following line of code:
wordIdx = new java.util.Random().nextInt(WordLibrary.getSize());
To see if this achieves the desired affect, we must of course play the game once more! The first word is getting
easy by now it always seems to be a scrambled form of abstraction. Indeed, the Anagram constructor always
starts the game by choosing the first word in the dictionary since the wordIdx variable is statically initialized to a value
of zero. But once we get passed the first word of the game, all subsequent choices appear to be suitably unpredictable.
Therefore we have hopefully made the game play a bit more fun, and we have just about one more way (assuming you can
read the source code) of cheating. If you like, you can go ahead and ensure that the first word of the game is also chosen
at random from the dictionary. To do so, simply ensure that the initial value of the wordIdx variable is computed in
the same way as subsequent values - with that, line #22 of Anagrams.java becomes:
private int wordIdx = wordIdx = new java.util.Random().nextInt(WordLibrary.getSize());
If youre like me, you might guess that elxical is a scrambled form of lexical, but when confronted with
lasiugsidintinhbe youd be clicking on New Word in a hurry. What makes indistinguishable more difficult
on average than lexical? The fewer letters there are in the original word, the more likely it is that the scrambled
form will not be much different, given our current algorithm for scrambling the words. More generally, though, I find
it easier to descramble a word the shorter it is, independent of how it has been scrambled. So for someone just
starting out, a set of shorter words would be fun, while for an experienced scrabble player, a set of long words
might be appropriate. But of course there are other characteristics besides word length, such as whether the
word is rarely used, or its part of speech, language, or topic. Can we use these observations to make the game
more useful, and can we learn something new about NetBeans and Java while were at it?
In this section, we will externalize the dictionary, meaning that it will be possible to play the game with a number
of different word lists, and that the user can even supply their own customized list of words. There are of course
a number of ways to do this; we will implement this functionality by reading a file containing a list of words,
structured and formatted as XML. By the end of the section, you will know how to open and read files from
the local file-system or the web and efficiently parse a simple XML file.
We want to add a new menu item for loading an external word list. To do this, we switch to design mode.
We go from looking like this:
To this:
In design mode, we also see a panel on the right called Inspector. Initially it looks like this:
The Inspector panel shows us the hierarchical structure of the Swing components that make up our graphical
user interface. If we expand the [JFrame]" node, we see that the first component is called mainMenu [JMenuBar].
This in turn contains a fileMenu [JMenu] item, which itself contains two further nodes: aboutMenuItem [JMenuItem]
and exitMenuItem [JMenuItem]. The pattern we see here is that each node is labeled with the name of the
corresponding variable; the component type follows in square brackets. The main frame is in fact our Anagrams
class itself (it inherits from JFrame), and so the Inspector does not show an instance name for that first component.
Our goal is to add a menu command for loading an external word list, so lets use the Inspector to add a new item
between the About and Exit entries in the File menu.
Right-click the fileMenuItem node, choose Add and then JMenuItem. A new menu item is added, in third
position after the Exit item. Initially NetBeans gives this item an auto-generated name, but we will change this
to openNewListMenuItem by right-clicking the new item and choosing to Rename . Finally we right-click the
new item again and choose Move Up, which will result in the desired order.
Now we select the exitMenuItem and click the Properties button in the Properties panel immediately
below the Inspector. Amongst other things, we see the following three interesting properties: mnemonic, text,
toolTipText. For this specific menu item, the values for these are, respectively, E, Exit and Quit Team, Quit!.
Lets select our new menu item and set its corresponding properties to O, Open Word List, Choose a new word
list file, replacing the current list. respectively.
Next we wish to add code that will run whenever this menu item is selected by the user. NetBeans helps us
out here again: In the Inspector, right-click on the openNewListMenuItem node, choose Events, then Actions,
then actionPerformed from the unfolding menus. NetBeans will create an event-handler method and return you to
the Source view so that we are ready to write the necessary implementation. The new method is automatically given
the name openNewListMenuItemActionPerformed, but you can safely rename it using the Refactor commands if
you so wish. A quick aside for those of you who may have previous experience with Swing GUI designer tools: it is
refreshing and reassuring to see how clean and well the auto-generated code is structured, named and formatted.
For example, the code for our three items in the File menu maintains the same order as the menu items themselves.
Back to the task at hand: When the user selects the Open Word List menu item, we will have them choose a file on
their local file-system, and then attempt to open, parse, and use this new word list. If the file is unavailable, or does
not contain a valid word list, the game will continue to use the current word list. Here is what NetBeans has given us
to start with:
private void openNewListMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Our Loader will take a URL as its main argument, so we need to generate an appropriate URL based on the file chosen
by the user. First we create a JFileChooser instance and use it to display an Open File dialog. If the user
selects a file, we generate a URL for it by pre-pending the protocol to the absolute path name.
private void openNewListMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
/* The "initialDirectory" variable determines what directory is first displayed
* when choosing a new word list. An empty or a null string will start the chooser
* in the user's default directory, which for Windows is typically "My Documents",
* and for *nix is typically the user's home directory.
*/
String initialDirectory = "";
String fileURL;
JFileChooser chooser;
int returnVal;
chooser = new JFileChooser(initialDirectory);
returnVal = chooser.showOpenDialog((Component) evt.getSource());
if ( returnVal == chooser.APPROVE_OPTION )
{
/* To create a URL for a file on the local file-system, we simply
* pre-pend the "file" protocol to the absolute path of the file.
*/
fileURL = "" + chooser.getSelectedFile().getAbsolutePath();
this.loadWordList(fileURL);
}
}
The above method demonstrates how you can present the user with a file chooser dialog; it then
calls the as-yet-unknown method loadWordList. This method should take as an argument the address
of a word list file and, assuming the file is okay, replace the current word list. Heres what that method looks like:
/**
* Attempts to open and parse an XML file containing a
* word list. If successful, this list of words will be
* used in place of the current list.
* The URL can for example point to a document on the local file-system,
* such as "", or to a document on the World Wide Web,
* such as "".
*
* @param url Address of an XML document containing a word list.
*/
protected void loadWordList(String url)
{
/* Create an instance of the loader */
com.toy.anagrams.lib.WordListFileLoader wlfl = new com.toy.anagrams.lib.WordListFileLoader();
/* Open and parse the file, replace the current word list with the newly loaded list. */
WordLibrary.setWordList(wlfl.loadList(url));
/* Since the new word list's number of entries may be different from the old,
* we make sure that the current value of wordIdx is valid for the new list.
*/
wordIdx = new java.util.Random().nextInt(WordLibrary.getSize());
}
We see that there is a new class in play, called WordListFileLoader. In addition, the WordLibrary
class has a new method called setWordList. I added this method at line #125, it is very simple:
public static void setWordList(String[] wordList)
{
if ( wordList != null )
WORD_LIST = wordList;
}
The entire source to the new WordListFileLoader class is available here,
but we will step through the important parts, one at a time. This new class has one significant method, as well as an inner class
that inherits from org.xml.sax.helpers.DefaultHandler. An instance of WordListFileLoader is intended to
open, read, parse and evaluate the contents of an XML file from a local file-system, or from an XML
document accessible via HTTP. Lets look at a high-level description of what the WordListFileLoader.loadList
method does:
There are a variety of ways to parse an XML document in Java. The pervasive DOM (Document Object Model)
approach results in an in-memory hierarchical model of the XML documents node-set. In our case the structure of
our data-set is simple (a list of words) and we will immediately convert the parsed list into a String[] array, so
maintaining an in-memory XML document is of little value. SAX is an event-based approach a handler class
listens for parser events that occur when the parser encounters an XML element, or an attribute, or the end of
an element. The handler can choose to process or disregard any such events. If suitable to the purpose, the SAX
based approach tends to be preferable as it can handle very large documents with ease.
public String[] loadList(String url)
{
InputStream is;
try {
URL u = new URL(url);
is = u.openConnection().getInputStream();
} catch (IOException ioe) {
report("Unable to open or find the specified wordlist.");
is = null;
}
if (is == null)
{
report("Unable to load the requested wordlist. An error occurred while opening the file.");
return null;
}
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser;
try {
parser = parserFactory.newSAXParser();
} catch ( ParserConfigurationException pce ) {
report("Error setting up the XML Parser. The parser is not properly configured. Loading aborted.");
return null;
} catch ( SAXException saxe ) {
report("Error setting up the XML Parser. Loading aborted.");
return null;
}
try {
WordListHandler handler = new WordListHandler();
parser.parse(is, handler);
} catch ( Exception e ) {
report("Unable to load the list, probably while performing SAX parsing.");
return null;
}
return this.list;
}
As described above, a SAX handler must implement various event handlers, in our case there are exactly three:
starting an element, the contents of an element, and closing an element. The resulting code looks as follows:
public class WordListHandler extends DefaultHandler
{
protected String nodeType;
protected ArrayList al;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( qName == "word" )
{
nodeType = "word";
} else if ( qName == "wordlist" ) {
al = new ArrayList();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
if ( qName == "word" )
{
nodeType = null;
} else if (qName == "wordlist" ) {
/* Cast the ArrayList to a an array of String objects. */
list = (String[]) this.al.toArray(new String[al.size()]);
}
}
public void characters(char[] chars, int start, int length) throws SAXException
{
if ( this.nodeType == "word" )
{
this.al.add(new String(chars, start, length).trim());
}
}
}
Our word list document structure contains just two types of XML element: <word> and <wordlist>. In this
code listing, you can see that the actual work of adding a new word to the list occurs within the characters method.
The other two methods keep track of what node we are currently reading, and perform appropriate setup and clean-up
actions, such as initializing the new word list and updating the outer class list field, respectively.
The entire WordListFileLoader Java source is available here. A sample
word list document is available here or might look like this:
<?xml version="1.0" encoding="utf-8" ?>
<wordlist>
<word>welcome</word>
<word>jacuzzi</word>
<word>elefant</word>
<word>abracadabra</word>
</wordlist>
So now you are able to create your own word lists by creating and editing XML files in a word processor or the like.
Given some time, Im sure you will come up with a number of fun, themed word lists. Wouldnt you like to share them
with others? Would you like to use word lists created by other people, perhaps to make guessing the words more
challenging for you? The good news is weve almost implemented just that. The bad news is I wont walk you through
each step this time around. First you should create a new menu item (maybe called Download File List) in the same
way we created the Open File List command. Add a method for the corresponding actionPerformed action (as before)
and use the following code to implement said method:
private void downloadNewListMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
String listURL;
String prompt = "Enter the URL to an XML word list:";
String initialValue = "http://";
listURL = (String) javax.swing.JOptionPane.showInputDialog(prompt, initialValue);
/* Perform some simple validation before attempting to download the new word list */
if (listURL != null && listURL.length() > 0 && listURL != initialValue)
{
this.loadWordList(listURL);
}
}
Thats as far as well go in this article, but I hope you have seen how straightforward and efficient it is
to build clean, correct graphical user interface code using NetBeans form designer. Of course weve only
just scratched the surface of whats possible, but we have enhanced the AnagramGame application in useful
ways and you now have a simple platform, which you can use to try out new concepts and learn more about
NetBeans. Youll have the most fun if you implement your own ideas, but here are a few to get you started: | https://netbeans.org/competition/win-with-netbeans/get-started-with-nb.html | CC-MAIN-2014-15 | refinedweb | 5,056 | 68.6 |
Hi, I am currently working on a project about pipeline parallelism which is based on DeepSpeed. In this project, we are trying to dynamically change the pipeline size in a very efficient way.
In a simplified setting of 3 machines and a model with 12 layers, each node computes 4 layers. And then node 1 may die at any moment. Before node 1 dies, it has 2 minutes to transfer data out. (Like spot instances on AWS).
So before node 1 dies,
node 0: layer 0-3, node 1: layer 4-7, node 2: layer 8-11
After,
node 0: layer 0-5, node 2: layer 6-11
But node 1 may have computed several forward passes. To avoid recomputation, I will send out the intermediate tensors to other nodes and I want other nodes to finish the backward pass based on the information they receive from node 1. I wonder if it is possible.
The background may be confusing. Let me put a code snippet. And is it possible to make backward update the “linear” model on the “to_rank”?
def remapping_layer(self, from_rank, to_rank): if self.global_rank == from_rank: #doing forward pass linear = nn.Linear(4, 5).to(self.device) optimizer = torch.optim.SGD( linear.parameters(), lr=0.1, momentum=0.9) optimizer.zero_grad() x = torch.tensor( [[1, 2, 3, 4.]], requires_grad=True).to(self.device) y = linear(x) self.coord_com.setTensor('y', y) #Send tensor through TCP Store self.coord_com.setStateDict("linear", linear.state_dict()) #Send state dict through TCP Store exit() if self.global_rank == to_rank: # Receive tensors and continue to do the backward pass # Doesn't work since the 'y' received from from_rank doesn't associate the parameter of liner model on this machine linear = nn.Linear(4, 5).to(self.device) optimizer = torch.optim.SGD( linear.parameters(), lr=0.1, momentum=0.9) optimizer.zero_grad() y = torch.zeros(1, 5).to(self.device) y = self.coord_com.getTensor('y') # Get tensor from TCP Store state_dict = self.coord_com.getStateDict("linear") # Get state dict of linear linear.load_state_dict(state_dict) print(f'rank:{to_rank},{y}') #rank:0,tensor([[ 1.8351, -0.8024, 0.7445, 2.3400, 0.4823]], device='cuda:0', requires_grad=True) z = torch.tensor([2, 3, 4, 5., 6], requires_grad=True).to(self.device) loss = (z-y).sum()/5 loss.backward() print(f"rank: 0, before {list(linear.parameters())}") # let it = statement A optimizer.step() print(f"rank: 0, {list(linear.parameters())}") # print the same thing as statement A exit() | https://discuss.pytorch.org/t/run-forward-on-machine-a-and-run-backward-on-machine-b/115411 | CC-MAIN-2022-21 | refinedweb | 410 | 53.58 |
Follow these steps to create an AWS AppSync API that connects to a React client-side application using the new AWS Amplify CLI
With the release of the new AWS Amplify CLI, developers now have the ability to scaffold AWS AppSync GraphQL APIs from the command line.
In this post, we’ll learn how to use the CLI to create an AWS AppSync API, as well as how to connect your new API to a client-side web or mobile application.
The CLI can automatically create a fully functional GraphQL API including datasources, resolvers, & additional schema for mutations, subscriptions, & queries. We can also update & delete the schema, datasources, & resolvers in our API directly from our local environment.
Amplify GraphQL Transform
We also have the ability to add powerful features such as Elasticsearch, user authorization, & data relations using the Amplify GraphQL Transform library directly from the CLI in our local environment.
Amplify GraphQL Transform is a library for simplifying the process of developing, deploying, and maintaining GraphQL APIs. With it you define your API using the GraphQL Schema Definition Language (SDL) and then pass it to the library where it is transformed and implements your API’s data model in AWS AppSync.
While the library comes with transformers to do most of the work you would need to build a typical API, you can also even write your own GraphQL Transformer.
For example, if we wanted to scaffold out a GraphQL API that created a data-source, resolvers, schema, & then streamed all data to Elasticsearch we could create the following type & push it up using the AWS Amplify CLI:
type Pet @model @searchable { id: ID! name: String! description: String }
In the above schema, the annotations
@model &
@searchable will create the datasources & all of the resources automatically for us.
There is also a
@connection annotation that allows you to specify relationships between
@model object types & an
@auth annotation that allows you to specify authorization schemes within your GraphQL API.
Let’s look at how to create a new AWS Appsync API using the Amplify CLI with the Amplify GraphQL Transform library & connect it to a client-side React application.
1. Install & configure the CLI
First, we’ll install the AWS Amplify CLI:
npm i -g @aws-amplify/cli
With the AWS Amplify CLI installed, we now need to configure it with an IAM User:
amplify configure
For a video walkthrough of how to configure the AWS Amplify CLI, click here.
2. Connect the API to a client app
Next, we’ll create a new React app & change into the new directory:
npx create-react-app blog-app cd blog-app
Now we’ll need to install the AWS Amplify client libraries:
yarn add aws-amplify aws-amplify-react # or npm install --save aws-amplify aws-amplify-react
3. Initialize the AWS Amplify project
From within the root directory or the newly created React app, let’s initialize a new AWS Amplify project:
amplify init
When asked if you’d like to use an AWS profile, choose Yes, using the profile we created when we configured the project earlier.
Once the project has been initialized, we’ll add the GraphQL API feature to our Amplify project:
amplify add api
This will walk us through the following steps to create the AWS AppSync GraphQL API:
- Please select from one of the below mentioned services: GraphQL
- Provide API name: blogapp
- Choose an authorization type for the API: API_KEY
- Do you have an annotated GraphQL schema?: N
- Do you want a guided schema creation? Y
- What best describes your project: One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
- Do you want to edit the schema now? Y
This will open a pre-populated Schema in your editor of choice & also give you the local file path of the new schema that was created.
Let’s take a look at the Schema. We’ll also make a small update by adding the
content field to the
Post type. Once you’ve updated the Schema, go ahead and save the file:
type Blog @model { id: ID! name: String! posts: [Post] @connection(name: "BlogPosts") } type Post @model { id: ID! title: String! content: String! blog: Blog @connection(name: "BlogPosts") comments: [Comment] @connection(name: "PostComments") } type Comment @model { id: ID! content: String post: Post @connection(name: "PostComments") }
In the above schema, we see that the
Blog types have the
@model annotation. Object types that are annotated with
@model are top-level entities in the generated API. When pushed, they will create DynamoDB tables as well as additional Schema & resolvers to hook everything together.
To learn more about the @model annotation, click here.
We also see the
@connection annotation used in the types. The
@connection annotation enables you to specify relationships between
@model object types. Currently,
@connection supports one-to-one, one-to-many, and many-to-one relationships. An error is thrown if you try to configure a many-to-many relationship.
To learn more about the
@connectiontype, click here.
With the schema ready to go, we can now push everything to execute the creation of the resources:
amplify push
Once the resources are created, we’re ready to create the app & begin interacting with the API.
We can also now view the API in the AWS AppSync dashboard by clicking on the new API name.
From the AWS AppSync dashboard we can also begin executing queries & mutations by clicking on Queries in the left menu:
Let’s try to create a new blog with posts & comments & then query for the blog data.
In the AWS AppSync dashboard, click on Queries.
First, we’ll create a new blog:
mutation createBlog { createBlog(input: { name: "My Programming Blog" }) { id name } }
Next, we’ll create a new post in this blog (replace the
postBlogId with the id returned from the above mutation):
mutation createPost { createPost(input: { title: "Hello World from my programming blog" content: "Welcome to my blog!" postBlogId: "bcb298e6-62ec-4614-9ab7-773fd811948e" }) { id title } }
Now, let’s create a comment for this post (replace
commentPostId with the ID returned from the above mutation):
mutation createComment { createComment(input: { content: "This post is terrible" commentPostId: "ce335dce-2c91-4fed-a953-9ca132f129cf" }) { id } }
Finally, we can query the blog to see all articles & comments (replace the ID with the id of your blog):
query getBlog { getBlog(id: "bcb298e6-62ec-4614-9ab7-773fd811948e") { name posts { items { comments { items { content } } title id content blog { name } } } } }
4. Connect to the API from React
To connect to the new API, we first need to configure our React project with our Amplify project credentials. You will notice a new file called
aws-exports.js located in the src directory. This file holds all of the information our local project needs to know about our cloud resources.
To configure the project, open
src/index.js & add the following below the last import:
import Amplify from '@aws-amplify/core' import config from './aws-exports' Amplify.configure(config)
Now, we can begin performing mutations, queries & searches against the API.
The definitions for the GraphQL mutations that we will be executing will look like the this:
// Create a new blog const CreateBlog = `mutation($name: String!) { createBlog(input: { name: $name }) { id } }` // Create a post and associate it with the blog via the "postBlogId" input field const CreatePost = `mutation($blogId:ID!, $title: String!, $content: String!) { createPost(input:{ title: $title, postBlogId: $blogId, content: $content }) { id } }` // Create a comment and associate it with the post via the "commentPostId" input field const CommentOnPost = `mutation($commentPostId: ID!, $content: String) { createComment(input:{ commentPostId: $commentPostId, content: $content }) { id } }`
The definition for the GraphQL query that we will be executing will look like this:
// Get a blog, its posts, and its posts comments const GetBlog = `query($blogId:ID!) { getBlog(id:$blogId) { id name posts { items { id title content comments { items { id content } } } } } }`
5. Configure the client application
The first thing to do is configure Amplify with your web application. In the root of your app (in React this will be
src/index.js), below the last import, add the following code:
import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config)
Now, we can begin executing operations agains the API.
6. Perform mutations from the client
Creating a new blog:
// import the API & graphqlOperation helpers as well as the mutation import { API, graphqlOperation } from 'aws-amplify' import { CreateBlog } from './your-graphql-definition-location' // next, we create a function to interact with the API state = { blogName: '' } createBlog = async () => { const blog = { name: this.state.blogName } await API.graphql(graphqlOperation(CreateBlog, blog)) console.log('blog successfully created') }
Creating a post for a blog:
// import the API & graphqlOperation helpers as well as the mutation import { API, graphqlOperation } from 'aws-amplify' import { CreatePost } from './your-graphql-definition-location' // next, we create a function to interact with the API state = { postTitle: '' , postContent: '' } createBlog = async () => { const post = { title: this.state.postTitle, content: this.state.postContent, postBlogId: this.props.blogId // Or where your blogId data lives } await API.graphql(graphqlOperation(CreatePost, post)) console.log('post successfully created') }
Commenting on a post:
// import the API & graphqlOperation helpers as well as the mutation import { API, graphqlOperation } from 'aws-amplify' import { CommentOnPost } from './your-graphql-definition-location' // next, we create a function to interact with the API state = { content: '' } createBlog = async () => { const comment = { content: this.state.content, commentPostId: this.props.commentPostId // Or where your commentPostId data lives } await API.graphql(graphqlOperation(CommentOnPost, comment)) console.log('comment successfully created') }
7. Perform queries from the client
Listing blog with posts & post comments:
// import the API & graphqlOperation helpers as well as the query import { API, graphqlOperation } from 'aws-amplify' import { GetBlog } from './your-graphql-definition-location' // next, we create a function to interact with the API getBlog = async () => { const data = await API.graphql(graphqlOperation(GetBlog, { id: this.props.blogId })) console.log('blog successfully fetched', data) }
8. Modify the schema
If at any time you would like to modify the schema to add, update or delete anything, you can open the file where the schema is located, make your edits, & then run
amplify push to update your AWS AppSync API.
Video Walkthrough
In this video walkthrough, we create an AWS AppSync GraphQL API using the Amplify CLI & connect it to a React application.
If you’re interested in learning more about building GraphQL APIs using AWS AppSync, follow Adrian Hall & check out his post Build a GraphQL Service the easy way with AWS Amplify Model Transforms.
To learn more about AWS Amplify, check out the docs or Github.
My Name is Nader Dabit . I am a Developer Advocate at AWS Mobile working with projects like AWS AppSync and AWS Amplify, the author of React Native in Action, & the editor of React Native Training & OpenGraphQL. | https://acloudguru.com/blog/engineering/8-steps-to-building-your-own-serverless-graphql-api-using-aws-amplify | CC-MAIN-2021-04 | refinedweb | 1,781 | 51.18 |
Multisync
The first thing to discuss is what I call "multisync" for lack of a better term. Suggestions for a better term for this would be greatly appreciated. A "multisync" photo is simply a set of photos layered to show (or hide) a subject across multiple moments in time. A tripod makes it relatively trival to do so. Here's one of my personal favorites:
Here you see Virginia at 2 years old, clearly walking towards a goal. At the time I had something like this in mind, but when the opprotunity presented itself, it was a quck rush to get into position and holding down the shutter to get a continous stream of photos. The results were amazing to me. It's not often that something truely original results from an experiment, but this time I feel like it did.
I didn't have a tripod at the time, so the images were all taken with slightly different angles. I used Hugin to align them, because that is the tool I feel most comfortable with. It's a matter of trading time post-exposure for pre-exposure setup. I'm very happy with this particular trade.
Synthetic aperture
Once I learned about synthetic aperture, I was hooked. This is the thing that got me started on this thread of experimentation. I still tip my hat to Marc Levoy for his work and demos that got me interested.
The basic idea is to trade your time and effort to replace a very large lens to create your own short depth of field. Here's an example:
The basic process is can be reduced to these basic steps:
- take a lot of almost identical photos from slightly different positions
- spend minutes or hours manually adding control points using Hugin
- output the remapped images to a series of TIFF formattted images
- average the results using a python script written for the purpose
Again, here I use Hugin to trade off pre-exposure alignment for time post exposure. However, in the case of virtual focus, it's pretty much impossible to align things pre-exposure. I imported the photos into Hugin, and chose 4 points on the face as alignment points and allowed Hugin to optimize for Roll, Pitch, Yaw, Zoom and X/Y offset. I'm pleased with the results, though I do wonder how many photos it would take to get a creamy bokeh.
Virtual Focus
Another way to combine photos is to take them from widely varying locations, to create images that would otherwise be impossible to capture using film, because it combines photos taken non-continous locations.
Here is a good example of an otherwise impossible shot using multiple exposures taken while receeding from the subject at 30+ miles per hour:
The compression of distance as the magnification becomes greater to keep the relative size shows so very interesting artifacts in the photo, and in fact I use this shot to help explain the process to others who commute with me.
Hugin - The Process
The process is pretty simple, if tedious. Import all of your exposures into Hugin, using the Images tab to avoid the auto-alignment process. Then manually enter control points between image pairs that are in your desired plane of focus.
Once you've gotten enough points entered and you've managed to optimize the error to an acceptable level (I try to get below 1 pixel of error), you then use the following option on the Stitcher tab:
Output : Remapped images
In remapper options I turn off the "saved cropped images" because my script can't handle them cropped. You then tell it to stitch now, and it will ask for a prefix, I always use the underscore character _ because it's easy to remember.
I usually then run the resulting image through one of the scripts I've written to average the frames. Lately, I use trail.py a lot, because it shows all of the intermediate steps. Here is a listing of the script:
import os, sys
import fnmatch
import Image
mask = sys.argv[1]
count = 0
# Program to average a set of photos, producing merge.jpg as a result
#
# version 0.01
# Michael Warot
#
print mask
for file in os.listdir('.'):
if fnmatch.fnmatch(file, mask):
print file
count = count + 1
in2 = Image.open(file)
if count == 1:
in1 = in2
in1 = Image.blend(in1,in2,(1.0/count))
in1.save("trail"+str(count)+".jpg","JPEG")
in1.save("merge.jpg","JPEG")
You need to be warned that this script overwrites the output files without asking, so be careful. It also requires the python image library, which might not be installed by default.
Once done, you'll have a set of jpeg images which show the intermediate results, along with merge.jpg which is the average of all frames.
Summary
So, I hope this has been of help. Please feel free to ask additional questions, or point out errors or omissions. Thanks for your time and attention.
8 comments:
I recently saw your Virtual Focus - Howto on Flickr which was a link someone posted in the autopano pro forum and I was amazed. I have been reading through your whole blog and going through your Flickr page trying to understand the process. I am so glad you finally went into more detail. I am not familiar with python. What image types can your script handle? is there a specific naming convention I should follow? I have more questions, is this where I should ask them?
The python script accepts one input, which is the file name mask, I usually use _*.tif myself, but it should work with jpegs as well.
It's a quick and dirty tool to get an average of a set of pictures and has some pretty severe limitations, including one that all of the pictures must be the same dimensions.
It outputs images trail00.jpg through whatever count it reaches, along with merge.jpg. It overwrites these without asking, so please be careful.
oh ok, I understand know... how about actually capturing the images, do you change the yaw at all as you move the tripod?
how does one go about using your script?
Raz,
None of the examples above involved a tripod. They were all shot handheld, the last while looking out the back of a moving train. I use Hugin to make up for the lack of a tripod in some instances.
The clock photos involved moving the viewpoint to change the yaw angle slightly by moving left and right... It's easier for me to move forward and backward than up or down to change the pitch (with an small change in zoom as a result).
As far as the script goes, my usual command line is
\photos\source\2008\trail.py _*.tif
This is because the script lives in my \photos\source\2008 folder (I haven't moved it yet to this year) and I want to create the trail of images sourced by _*.tif which is the set of files that Hugin outputs.
The resulting set of files includes:
merge.jpg
trail1.jpg
trail2.jpg
etc..
To get used to it, the script and a copy of your photos in a folder, and give it a spin. Be careful with your filenames because it could eat it's tail if you manage to include it's own output. 8)
I hope this helps.
ok, so you don't rotate the camera at all... you pretty much hold it and move your body around slightly, is that right. I thought maybe there was some rotation happening with the camera. I want to thank you for taking the time to answer my questions, and for pretty much introducing me to this type of photography.
Excuse me Mike, why the script stop at first image? If I have a set of image like DSC1.jpg DSC2.jpg DSCn.jpg the script works only on the first (DSC1) image?
Excuse me Mike, why the script stop at first image? If I have a set of image like DSC1.jpg DSC2.jpg DSCn.jpg the script works only on the first (DSC1) image?
The script expects a wildcard parameter, thus you would tell it DSC*.jpg, and it would find all of them. | http://mikewarot.blogspot.com/2009/01/computational-imaging-experiments-to.html | CC-MAIN-2014-35 | refinedweb | 1,387 | 72.36 |
I use PsExec to deploy small .exe files to my workstations. Sometimes the .exe, for some reason, is incompatible with the system and opens a popup window with an error or some other message.
Is there any way to know when the executable is 'stuck' there requiring user interaction? On my side I just have psexec running and waiting for the .exe to return (which will never return because the popup is stuck there).
Since I run PsExec programmatically and I automate all the executions, when this Popup thing happens I find myself with hundreds of psexec processes stuck there and have no result back from them..
What's the best way to handle this sort of issue?
Thanks.
As a last resort try using one of the other automation tools in addition to PsExec to deal with the popups. Like AutoIt.
I would guess that this will have to be the way forward for you since there is no standard that each software must adhere to.
psexec has an -i option that should work.
-i Run the program so that it interacts with the desktop of the
specified session on the remote system. If no session is.
Also, you could use some sort of pslist.exe script to monitor the process spawned on their system and see how long it's been there. If msiexec is hanging for 5 mins, that probably means it's hung.
The best way to handle this sort of situation is to test before trying to apply automation.
One easy, albeit brutal, way to deal with the stuck processes is to run a separate batch using pslist and pskill at a later time when the psexec processed that would complete normally would have done so. Use pslist to test for psexec still running on the remote machine and pskill to terminate any that | http://serverfault.com/questions/170497/psexec-what-if-the-exe-you-run-remotely-requires-user-interaction | crawl-003 | refinedweb | 309 | 72.05 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.