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
|
|---|---|---|---|---|---|
Juan Manuel Diaz wrote:Hi fellows!! I am trying to create a login form for my webapp using richfaces in a facelets page, but i cant did it! If I use the auto-config <login-form /> in my security-context.xml, the ugly login form from spring is rendered and works fine, but I want my own login form! If someone can help it will be good for me!
Regards and thanks in advance!,
JM
PS.> Sorry for my child's english!
Juan Manuel Diaz wrote:At the moment, I am at work. When I came back to home I will post the security-context.xml, login.xhtml and faces-config.xml files!
Regards,
JM
Juan Manuel Diaz wrote:I made it works!
I understand that my login.xhtml page is just that... a login page. I was pointing to it in my welcome-file of the web.xml file... now I point to /faces/home.xhtml and everything looks works fine!
But I needed to use a <form> tag to the form... the effect of use this tag is a message telling:
Warning: This page calls for XML namespace declared with prefix form but no taglibrary exists for that namespace.
I supose that i need a loginBean to use a <h:form> tag and <h:commandButton> right?
Thanks,
JM
|
http://www.coderanch.com/t/536641/Spring/Login-Form-Spring-Security-JSF
|
CC-MAIN-2015-14
|
refinedweb
| 220
| 86.71
|
WikiGraph
MetaWiki-like service delivered via JavaScript. See 2012-12-01-BuildingWikiGraph
Short-term goals: Visible Backlinks and Twin Pages for this WikiLog.
Longer-term goals
- WikiWeb
- encourage use of Smashed Together Words (contra Free Link-s) for Automatic Linking in other WikiEngines
- 2016 update: WikiGraph With FreeLinks
- WikiGraphBrowser
Building with WebPy to run on my Linode.
Data in 3 SQL tables: spaces, pages, mentions
Scraped page lists by hand from a number of my Sister Sites
- My WikiLog has 15664 pages.
- Ignoring Free Link-s cases and other bad URL-s (like Smallest Federated Wiki) for now, as I'm the client.
For Visible Backlinks, started with 2003 file giving graph of my space (only 2804 pages at that time!) - good enough for starting to build.
Jan20'2013 - get static pieces working together
- edit
/MoinMoin/theme/__init__.page_info()
html += """\n<div id="backlinks"></div> <script src=""></script> <noscript>Please enable JavaScript to view the BackLinks</noscript>""" html += """\n<div id="twin_pages"></div> <script src=""></script> <noscript>Please enable JavaScript to view the Twin Pages</noscript>"""
- routes
urls = ( '/twinpages.js','twinpages', '/backlinks.js','backlinks',
- code
class backlinks: def GET(self): web.debug('calling backlinks') resp = '' backlinks = db.select('mentions',%s</a> | ' % ('', backlink.page_name, backlink.page_name) resp = resp[:-3] else: resp = 'No backlinks!' web.debug(len(resp)) return """ document.write('\ <div>\ <p>%s</p>\ </div>'); """ % (resp)
- focus on serving my WikiLog (and maybe Private Wiki)
- so no need to pass general params
- then move on to WikiGraphBrowser, since that shows the real power of WikiWord-s vs Free Link-s.
Feb26: buy ThirdPartyJavaScript book by Ben Vinegar and Anton Kovalyov (DisQus guys)
Feb27: get dynamic version of code working, using Http Referer and
document.write()
Mar01: done styling content with inline div styles (how tacky).
Next: figure out how to parse all my current WikiLog pages for Visible Backlinks database.
- Mar10: done writing/testing locally
- Mar11: running against production.
Mar12: suck 96634 mentions into local db
- have some weird UTF8 issues, cleaned up file by hand
- convert SQLite to PostgreSQL format - see 2012-10-16-SettingUpHostingForSimplestThing
- get whole service deployed at Linode
Setting up hosting
Make a
/srv/www/wikigraph.net/* beside
/srv/www/simplest-thing.com/* - do chown/chmod bits.
- cp
/srv/.../app/start_uwsgi_app.shto parallel directory. Edit (port 9002).
Copy
/etc/default/uwsgi to
/etc/default/uwsgi_wg, edit the latter to set
PYTHONPATH to
/srv/www....
Edit
/opt/nginx/conf/nginx.conf - add a header section for hostless-domain redirect and a header for the host that points to the right place and uses port 9002 for uwsgi.
Copy WebPy
code.py to server.
Restart nginx. Kill/restart the uwsgi app for Simplest Thing. Start the uwsgi_wg app for WikiGraph.
Try to hit - get "uWSGI Error - Python application not found"
- hit same point in setting up Simplest Thing, but had already handled tweaks from that learning here, so don't know what issue is...
Tweak
start_uwsgi_app.sh to call
uwsgi_wg instead of just
uwsgi. Kill/restart uwsgi.
Try to hit - get 502 Bad Gateway. Realize didn't get the new uwsgi processes. Change the bash back. Get the "uWSGI Error" again.
Check the logs
- access.log - looks like status 500
- uwsgi_app.log - ah, notes that
import formsfailed (because not using that in this app yet, so hadn't copied it to server).
Tweak code.py, copy up, kill/restart uwsgi, hit page again. It does a redirect to
/static/... based on code copied from Simplest Thing, but I don't have that directory, so get 404 error.
Comment-out that check_authorized code, copy/restart/etc - now works!
Mar14: convert SQLite dump file to PostgreSQL
Mar20
- copy converted dump file to server
- create db
- import dump file; do some
COUNTto confirm data in there
- change laptop MoinMoin to point to production server JavaScript; reload page. Neither call returns data.
tail uwsgi_app.log-
ProgrammingError: permission denied for relation spaces- just like in 2012-10-16-SettingUpHostingForSimplestThing
- do the
GRANTthing - now it works!
- copy MoinMoin template file to Blue Host (after various file games).
- It's working! Now displaying Visible Backlinks and Twin Pages!
Apr15: tweak to let my local Private Wiki call it. Automatically works for creating-new page process so I can see if Twin Page already exists in my WikiLog and decide whether to add a Private page or stay public.
Future:
- have WikiLog "page does not exist yet" page include Twin Pages.
- WikiGraphBrowser!
- make way for backlinks-search to call db. Also change fulltext-search to call Google or maybe call WikiGraph.
- check scraper code for WikiWords with adjacent punctuation (like for italics)
- update lists
- support Free Link spaces (Phil Jones/SFW, Chris Dent/Tiddly Space...)
- 2016: WikiGraph With FreeLinks
Jul'2013 update: tweaked scraper code to catch some cases being missed before, re-ran
- 15963 pages
- 100451 mentions (6.3 mentions/page) (was 6.1 before - of course since both pieces changed it's hard to be sure...)
Twin Pages: pondering addition of Wikipedia
- 5M English articles, so don't feel like doing that
- 1000 "vital" articles, but suspect most wiki sites wouldn't have matches against very many of those (but maybe that's ok)
- could also do a hack, and always include a Wikipedia link that just generates a search...
- since Wikipedia is so unlike every other wiki, it actually sounds like a bad fit
Edited: | Tweet this! | Search Twitter for discussion
|
http://webseitz.fluxent.com/wiki/WikiGraph
|
CC-MAIN-2022-33
|
refinedweb
| 897
| 66.33
|
It should be looking in the class path, not the file system.
On Oct 18, 2013, at 12:42 PM, Dan Kaplan <dank@mirthcorp.com> wrote:
> I tried using that, but it "didn't work". Probably because "includes"
> still looks on the file system?
>
>
> On Thu, Oct 17, 2013 at 11:10 PM, Andreas Gudian
> <andreas.gudian@gmail.com>wrote:
>
>> Check the "dependenciesToScan" property in the latest Failsafe version. It
>> tells the plugin to scan for the test class patterns in the specified
>> artifacts.
>>
>>
>> Am Freitag, 18. Oktober 2013 schrieb Dan Kaplan :
>>
>>> I've found an "ok" solution. I just extend the class in the module I
>> plan
>>> to run the tests in and include the child. It works the way I want.
>>>
>>>
>>> On Thu, Oct 17, 2013 at 4:58 PM, Dan Kaplan <dank@mirthcorp.com> wrote:
>>>
>>>> RunWith:
>>>>
>>>> * When a class is annotated with <code>@RunWith</code>
or
>> extends a
>>>> class annotated
>>>> * with <code>@RunWith</code>,
>>>>
>>>> AllTests:
>>>>
>>>> Runner for use with JUnit 3.8.x-style AllTests classes
>>>> * (those that only implement a static <code>suite()</code>
>>>> * method). For example:
>>>> * <pre>
>>>> * @RunWith(AllTests.class)
>>>> * public class ProductTests {
>>>> * public static junit.framework.Test suite() {
>>>> * ...
>>>> * }
>>>> * }
>>>>
>>>> So this class will use AllTests as a runner. All tests will call the
>>>> suite() method on this class. The suite() method collects integration
>>>> tests from the classpath and runs them. I'm sorry I'm not answering
>>>> directly, but I can't because I don't know what terminology to use.
>> I'll
>>>> show you some of the code:
>>>>
>>>> @RunWith(AllTests.class)
>>>> public class DistributedIntegrationTestRunner {
>>>>
>>>> private static Logger log =
>>>> LoggerFactory.getLogger(DistributedIntegrationTestRunner.class);
>>>>
>>>> public static TestSuite suite() {
>>>> TestSuite suite = new TestSuite();
>>>>
>>>> ClassesFinder classesFinder = new
>>>> ClasspathFinderFactory().create(true,
>>>> new String[]{".*IntegrationTest.*"},
>>>> new SuiteType[]{SuiteType.TEST_CLASSES},
>>>> new Class[]{Object.class},
>>>> new Class[]{},
>>>> "java.class.path");
>>>>
>>>> int nodeNumber = systemPropertyInteger("node.number", "0");
>>>> int totalNodes = systemPropertyInteger("total.nodes", "1");
>>>>
>>>> List<Class<?>> allTestsSorted =
>> getAllTestsSorted(classesFinder);
>>>> allTestsSorted = filterIgnoredTests(allTestsSorted);
>>>> List<Class<?>> myTests = getMyTests(allTestsSorted, nodeNumber,
>>>> totalNodes);
>>>> log.info("There are " + allTestsSorted.size() + " tests to
>>> choose
>>>> from and I'm going to run " + myTests.size() + " of them.");
>>>> for (Class<?> myTest : myTests) {
>>>> log.info("I will run " + myTest.getName());
>>>> suite.addTest(new JUnit4TestAdapter(myTest));
>>>> }
>>>>
>>>> return suite;
>>>> }
>>>>
>>>>
>>>> None of my tests use the @RunWith annotation, only this class does. I
>>>> don't think I can add that to the tests because
>>> DistributedIntegrationTestRunner
>>>> does not implement Runner so the code won't compile if I put
>>>> @RunWith(DistributedIntegrationTestRunner.class) on a test. Even if it
>>>> would work, I don't want to have to put that annotation on every test
>>>> because someone will forget and their tests will be silently skipped.
>>>>
>>>> *If* this class is in the same project as the rest of the integration
>>>> tests, I can put this in the pom.xml:
>>>>
>>>> <plugi
>>
>
>
>
> --
> Thanks,
> Dan
>
> --
>.
-----------------
Author, Getting Started with Apache Maven <>
Come read my webnovel, Take a Lemon <>,
and listen to the Misfile radio play <>!
|
http://mail-archives.apache.org/mod_mbox/maven-users/201310.mbox/%3C17C71EDE-5AC5-46D2-B5F3-BDD519FD218A@gold-family.us%3E
|
CC-MAIN-2015-18
|
refinedweb
| 482
| 53.27
|
Introduction: Real Python AI
this is is an instructable that will teach you how to make a python AI.(for real!!!!!!!!!!!)
Step 1: Programing Your AI
here is how to make him. first you have to import random then add different speech categories. like greetings or questions. later you can add categories to your software but for now you will have three. then put while True:
userinput = raw_input is very important so it takes what you put in and only what you put in. The rest is simple, all that you have to do is put: if userInput in greetings:
random_greetings = random.choice(greetings)
print(random_greeting)
to do the other stuff like the questions, all that you have to do is put elif instead of if.
if you are confused the picture at the top might help you.
Be the First to Share
Recommendations
10 Discussions
Question 1 year ago
i have typed out the above, im just stuck at how can i actually ask the questions
2 years ago
how can I apply this into a simple AI
3 years ago
what version of python is this?
Reply 3 years ago
I think they've used Python 2.7. In 3.5, the method to take user input is input() rather than raw_input().
3 years ago
This is so cool.
import random
greetings = ['hola','hello','hi','Hi','hey!','hey','sup','whats up?',]
questions = ['how are you?','how are you doing?']
responses = ['Okay',"I'm fine" 'i am great!']
while True:
userInput = raw_input(">>> ")
if userInput in greetings:
random_greetings = random.choice(greetings)
print(random_greeting)
elif userInput in question:
random_response = random.choice(responses)
print(random_response)
else :
print("I did not understand what you said")
4 years ago
Basic, but I like it; it's good to get you started in the right direction.
4 years ago
it is very basic but i feel some times you need basics to get people to want to do it.
so what would you like your next step to be build a dictionary of question you can ask with a talking reply and a run bash or shell script to do things like open web sits ect...
4 years ago
this is immensly basic. The most basic python algorithm that you can call AI would be tic tac toe or a ping pong game.
5 years ago on Introduction
thanks
5 years ago on Introduction
This is great! I'd love to see the output on a screen!
|
https://www.instructables.com/id/real-python-AI/
|
CC-MAIN-2020-40
|
refinedweb
| 412
| 73.37
|
I am running a query that needs to exclude all previously seen items and return a certain number of items (10 in this case). The list of items is sent in a querystring parameter and are uuid4 strings separated by '&'.
With a possible very large database, I don't think it makes sense to add the exclude statement with the query as most of the results wont be in the alreadySeenItems list and the database is pretty hefty.
Which of the following methods would be faster, assuming that the alreadySeenList can be pretty large >1000 items in some case.
Note: I would normally just use the first one, but since I need an exact match and I know where each word starts, it might make sense to do otherwise
def getItems(request, alreadySeenItems):
newItems = []
allPossibleItems = # unrelated heinous sql query
# method 1
for item in allPossibleItems:
if item not in alreadySeenItems:
newItems.append(item)
if len(newItems) > 10:
return newItems
# method 2
alreadySeenItemsList = alreadySeenItems.split('&')
for item in allPossibleItems:
if not checkForItemInList(item, alreadySeenItems)
newItems.append(item)
if len(newItems) > 10:
return newItems
def checkForItemInList(item, items):
for tmp in items:
if item == tmp:
return True
return False
Whatever you are doing will be much faster if you use Python's built in
set data structure. Checking for inclusion then is very fast, if you have some memory available, but 1k items is nothing. see
Not to dodge the original question, but we also can't be sure if your database is truly large. Have you added indexes to your table? As far as most of the results being of one nature or another leading to some inefficiency, some systems (Postgresql at least) allow for "partial indexing" which allows you to build an index on just some values, which can make things a little leaner - but I'm not completely sure if this is relevant to you.
|
https://codedump.io/share/qdfjwh1W7Pgn/1/efficiency-of-checking-for-string-in-querystring-parameters-in-python
|
CC-MAIN-2016-50
|
refinedweb
| 316
| 62.82
|
Creating a movie website with GraphQL and React (2 Part Series)
In part one we created the GraphQL API. Now we are going to create a react application that makes use of that API.
Before we move on, just because I thought it to be cool, we could use an HTTP client, like axios, to make requests to our GraphQL server! Check this out:
const query = `{ newMovies { id title } }` const url = ''+query; axios.get(url) .then(res => console.log(res.data.data.newMovies))
If you are interested, you can see that setup in action by paying attention to the url changes when using the graphQL interface - we worked on in part one
However, to make production easier and pleasant, instead of using an HTTP client there are GraphQL clients which we can use.
There are few clients to pick from. In this tutorial I am going to use the Apollo Client. Apollo provides a graphQL server as well but we already created that with
express-graphql so we are not using that part of Apollo, but the Apollo Client, as the name suggests is the part which gives us the ability to write GraphQL in react.
In a nut shell
If you want to follow along you should clone the repository from github, checkout the branch name
Graphql-api and since we're going to focus on react side now, all the code is going to be writen in the
client directory, which is the react application code.
Clearly this is not a beginner's tutorial. If you don't know react but are interested in learning the basics I've writen an introduction to it.
First install the following packages.
npm install apollo-boost react-apollo graphql-tag graphql --save
The game plan is to wrap our react app with an
ApolloProvider which in turn adds the GraphQL client into the react props. Then make graphQL queries through
graphql-tag.
At the moment, in
./client/index.js you see this setup
import React from 'react'; import ReactDOM from 'react-dom'; import './style/style.scss'; const App = () => { return <div>Hello World2</div> } ReactDOM.render( <App />, document.querySelector('#root') );
First step, wrap the entire app with the
ApolloProvider. The provider also needs a GraphQL client to pass to react.
import { ApolloProvider, graphql } from 'react-apollo'; ... const client = new ApolloClient({ uri: "" }); ReactDOM.render( <ApolloProvider client={client}> <App /> </ApolloProvider> , document.querySelector('#root') );
The
ApolloClient requires a
uri if the GraphQL server doesn't point at
/graphql. So in our case leaving it out and just using
new ApolloClient() would work
Now that we have access to the client we can make queries llike so:
import { ApolloProvider, graphql } from 'react-apollo'; import gql from 'graphql-tag'; import ApolloClient from 'apollo-boost'; const AppComponent = (props) => { if(props.data.loading) return '<div>loading</div>'; return <div>{props.data.newMovies[0].title}</div> } const query = gql`{ newMovies { title } }`; const App = graphql(query)(AppComponent)
We wrap the
AppComponent with
graphql, we also inject the query into the props so then
props.data.newMovies gives us the movie results.
Let's get started
Because the application we are building is bigger then the above example of displaying a single title, lets split it out.
Start from
./client/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; import { HashRouter, Switch, Route } from 'react-router-dom' import NewMovies from './components/NewMovies'; import './style/style.scss'; const client = new ApolloClient(); const Root = () => { return ( <HashRouter > <ApolloProvider client={client}> <Switch > <Route exact path="/" component={NewMovies} /> </Switch> </ApolloProvider> </HashRouter> ) } ReactDOM.render( <Root />, document.querySelector('#root') );
Simple, a couple of routes. the imported component (
NewMovies) don't exist yet but that's all the code required in
./client/index.js.
Again, all the components that we would ever use would be specified within the
Switch component. Therefore the entire app is wrapped with in the
ApolloProvider, exactly the same as in the nutshell section.
Getting top movies
Let's create a file at
./client/components/NewMovies.js, and start by importing the required packages
import React, { Component} from 'react' import gql from 'graphql-tag' import { graphql } from 'react-apollo'
Next, inject the
newMovies GraphQL query results into the
NewMovies Component
class NewMovies extends Component { ... } const query = gql` { newMovies { id poster_path title } } ` export default graphql(query)(NewMovies);
With that setup, an object array gets injected into the
NewMovies component props and can be accessed by
this.props.data.newMovies. Let's make use of them:
class NewMovies extends Component { Movies(){ return this.props.data.newMovies.map(movie => { return ( <article key={movie.id} <img src={movie.poster_path} /> <h1>{movie.title}</h1> </article> ); }) } render() { if(this.props.data.loading) return <div>loading</div> return this.Movies() } }
There we have it. Things to note are
- The react component loads before the
newMoviesresults are fetched.
- graphql gives us a
truewhilst data is fetched, and
falsewhen the data is ready to be used
Before we move on to another component, lets wrap the movie posters with an anchor so that we get more information when one poster is selected.
To do so we'll use the
Link component from the
react-router-dom package.
import { Link } from 'react-router-dom' class NewMovies extends Component { Movies(){ return this.props.data.newMovies.map(movie => { return ( <article key={movie.id} <Link to={"/info/"+movie.id}> <img src={movie.poster_path} /> </Link> ...
Whenever a poster is clicked we are directed to
/info/1 for example.
We need to head back to
./client/index.js and add a router which catches that route.
... import MovieInfo from './components/MovieInfo'; ... const Root = () => { return ( <HashRouter > <ApolloProvider client={client}> <Switch > <Route exact path="/" component={TopMovies} /> <Route exact path="/info/:id" component={MovieInfo} /> </Switch> ...
Of course, that's the power of react routing (covered here before).
Let's work on
MovieInfo Component
Start by creating the file at
./client/components/MovieInfo.js then add the following:
import React, { Component } from 'react' import gql from 'graphql-tag' import { graphql } from 'react-apollo' class MovieInfo extends Component { render(){ if(this.props.data.loading) return <div>loading</div> return ( <div>{this.props.data.movieInfo.title}</div> ) } } const query = gql` {movieInfo(id: "284054") { title }}`; export default graphql(query)(MovieInfo);
It sort of works right?
We are querying an
id that we hard coded and that's not what we want, instead we want to pass an ID from our react component props to the graphql query. The
react-apollo gives us a
Query component that enables us to do that.
import { Query, graphql } from 'react-apollo' class MovieInfo extends Component { render(){ const id = this.props.match.params.id; return ( <Query query={query} variables={{id}} > { (({loading, err, data}) => { if(loading) return <div>loading</div> return ( <div>{data.movieInfo.title}</div> ) }) } </Query> ) } } const query = gql` query MovieInfo($id: String) { movieInfo(id: $id) { title } } `;
Almost the exact same thing but with
Query we are able to pass it variables.
Now let's develop the rest of the component. Inside the
Query return the following code
return( <div> <header style={{backgroundImage: 'url("'+data.movieInfo.poster_path+'")'}}> <h2 className="title">{data.movieInfo.title}</h2> </header> <article className="wrapper"> <p className="description">{data.movieInfo.overview}</p> <div className="sidebar"> <img src={""+data.movieInfo.poster_path} <ul> <li><strong>Genre:</strong> {data.movieInfo.genres}</li> <li><strong>Released:</strong>{data.movieInfo.release_date}</li> <li><strong>Rated:</strong> {data.movieInfo.vote_average}</li> <li><strong>Runtime:</strong> {data.movieInfo.runtime}</li> <li><strong>Production Companies:</strong> {data.movieInfo.production_companies}</li> </ul> <div className="videos"> <h3>Videos</h3> {/* videos */} </div> {/* reviews */} </div> {/* credits */} </article> </div> )
As you can see we are trying to access query properties which we haven't requested. If you run that it will give you a 404 error as the requests fail. Hence, we need to update the query to request more then the
title property:
query MovieInfo($id: String) { movieInfo(id: $id) { title overview poster_path genres release_date vote_average runtime production_companies } } `;
With that update and with the css that is going to be available in the git repository, the section we've been working on would look something like this:
As you can see in the code comments we need to add videos, reviews and credits on the page.
Adding videos
Remember the way we designed the GraphQL query in part one gives us the ability to fetch the videos within the
movieInfo query. Let's do that first:
const query = gql` query MovieInfo($id: String) { movieInfo(id: $id) { ... videos { id key } } } `;
These videos come as an array - as sometimes there's more then one. So the best way to deal with these arrays is to create a separate method inside the
MovieInfo component and let it return all the videos.
class MovieInfo extends Component { renderVideos(videos){ return videos.map(video => { return ( <img key={video.id} onClick={()=> this.videoDisplay(video.key)} className="video_thumbs" src={`{video.key}/0.jpg`} /> ) }) } render(){ ... {/* videos */} {this.renderVideos(data.movieInfo.videos)} ...
As we've covered in the first tutorial the
key in the
videos object refers to the youtube video ID. Youtube gives us the ability to use a screenshot image using that particular format (passed in the
src attribute). also, as we previously mentioned, we took the ID exactly because we knew we need something unique for the
key - required by React.
When the user clicks on these thumbnail images I want to load a youtube video in the screen, hence
onClick={()=> this.videoDisplay(video.key)}. Lets create that functionality.
The way we are going to implement this is by changing the state
class MovieInfo extends Component { constructor(){ super(); this.state={ video: null } } videoDisplay(video){ this.setState({ video }) } videoExit(){ this.setState({ video: null }) } ...
When the page loads
video state is
null, then when the thumbnail is clicked and
videoDisplay is triggered,
video state takes the youtube video
key as a value. As we'll see, if the
videoExit method is triggered, the
video state resets back to
null
Finally we need a way to display the video upon state change, so lets create another method. Just under the above methods, add this method:
videoToggle(){ if(this.state.video) return( <div className="youtube-video"> <p onClick={() => this.videoExit()}>close</p> <iframe width="560" height="315" src={`//{this.state.video}` } frameborder="0" allowfullscreen /> </div> ) }
Then simply have it render anywhere on the page
<div className="videos"> {this.videoToggle()} <h3>Videos</h3> {this.renderVideos(data.movieInfo.videos)} </div>
Again, if the
video state is
null,
{this.videoToggle()} does nothing. If the state isn't null - if
video has a key, then
{this.videoToggle()} renders a video.
Adding Movie credits and reviews
I decided to put the movie reviews and movie credits in their own separate component. Let's create the empty component files, import and use them inside the
MovieInfo component and also update the query.
Inside
./client/components/MovieInfo.js add these changes
import MovieReviews from './MovieReviews' import MovieCredits from './MovieCredits' class MovieInfo extends Component { ... {/* reviews */} <MovieReviews reviews={data.movieInfo.movieReviews} /> </div> {/* credits */} <MovieCredits credits={data.movieInfo.movieCredits} /> </article> } ... const query = gql` query MovieInfo($id: String) { movieInfo(id: $id) { ... movieReviews { id content author } movieCredits{ id character name profile_path order } } } `; ...
We get the data from the
movieReviews and
movieCredits query, we pass them to their respective components. Now we just quickly display the data
Movie credits component
Add the following code to
./client/components/MovieCredits.js
import React, { Component } from 'react' export class MovieCredits extends Component { renderCast(credits){ return credits.map(cast => { return ( <li key={cast.id}> <img src={`{cast.profile_path}`} /> <div className="castWrapper"> <div className="castWrapperInfo"> <span>{cast.name}</span> <span>{cast.character}</span> </div> </div> </li> ) }) } render() { return (<ul className="cast">{this.renderCast(this.props.credits)}</ul>) } } export default MovieCredits
Nothing new to explain from the above
Movie reviews component
Add the following code to
./client/components/MovieReviews.js
import React, { Component } from 'react' class MovieReviews extends Component { renderReviews(reviews){ return reviews.map(review => { return ( <article key={review.id}><h4>{review.author} writes</h4> <div>{review.content}</div> </article> ) }) } render() { return( <div className="reviews"> {this.renderReviews(this.props.reviews)} </div> ) } } export default MovieReviews;
And that's it. This is how the credits, videos and reviews would appear.
Conclusion
The full application, such as it stands can be found at the same repository, and you can view the demo here. It has three branches react-app branch and the master branch have the full code, each tutorial building on top of each other. Where as the Graphql-api branch has the code covered in the first tutorial
Creating a movie website with GraphQL and React (2 Part Series)
Posted on Nov 12 '17 by:
aurel kurtula
I love JavaScript, reading books, drinking coffee and taking notes.
Discussion
Hi. Thanks for reading!
That port is used by livereload. It's not our problem, you don't need to use that. Everything we need is at port
4000
I read the tutorial again and try to make it clear that we are working in port 4000.
Thanks for the question. Let me know if that answers the question
(To test this I cloned the master branch as well and added the api key to
.env)
I have
babel-cliinstalled globally and always take it for granted to mention it :)
Fantastic.
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/aurelkurtula/creating-a-movie-website-with-graphql-and-react---part-two-3ahf
|
CC-MAIN-2020-29
|
refinedweb
| 2,198
| 58.08
|
Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.
Example
int i = 5000; float gpa = 13.65; double mask = 0xaf;
However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class.
And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package.
Following is an example of boxing and unboxing −
Example
public class Test { public static void main(String args[]) { Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); } }
This will produce the following result −
Output
15
When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer.
|
http://blogs.binarytitans.com/2016/04/java-numbers-class.html
|
CC-MAIN-2018-13
|
refinedweb
| 236
| 53.51
|
Setting the "Stage" for the JavaFX SDK!
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Jacek Furmankiewicz replied on Thu, 2008/07/10 - 4:42am
I don't want to sound like a broken record, but could you post a sample of how to accomplish the same thing by calling the underlying JavaFX APIs from pure Java instead? I am actually really interested in seeing that and so is probably a lot of people who have invested a lot into Java and are thinking maybe of enhancing existing Swing apps to have this sort of functionality.
Thank you
Peter Thomas replied on Thu, 2008/07/10 - 10:01am
Collin Fagan replied on Thu, 2008/07/10 - 10:58am
Jim Weaver replied on Thu, 2008/07/10 - 12:07pm
Jacek. No problem on sounding like a broken record. I *really* have valued your input! I fully expect a version of GridPanel, for example, that contains graphics nodes and *is* a graphical node (like HBox is, for example). It would be located in the javafx.scene.layout package. Does that address your concern?
Thanks,
Jim Weaver
Jacek Furmankiewicz replied on Thu, 2008/07/10 - 12:20pm
in response to:
Jim Weaver
Are there any docs how to use any of the internal JavaFX APIs from Java in general? It would be *great* if all the funky JavaFX examples were accompanied by the equivalent pure Java example.
I think it would go a long way to disspelling some of the negativity many Java developers have towards JavaFX (or to be more precise, how it seems to be getting all the features we've wanted in Java for years, e.g. easy data binding).
Thank you, I appreciate your response.
Tom Ball replied on Thu, 2008/07/10 - 2:53pm
it seems to be getting all the features we've wanted in Java for years, e.g. easy data binding
For that you want Beans Binding (JSR 295), which has been around for (a few) years:. You won't find any "internal FX API" that is easier to use. As for access to Nodes and the like, the FX runtime relies on the Scene Graph Project at.
Not everything written in JavaFX Script gets converted into Java calls, however. There is no API to build an object literal declaritively like Jim's Frame example above, for example; instead, the compiler generates all the necessary code to create and initialize each element it contains.
GeekyCoder coder replied on Thu, 2008/07/10 - 3:27pm
Hi Tom,
I understand that you are openjfx compiler lead (), and I have question to ask pertaining tosome developers' need to know and learn the underlying Swing code correspond to JavaFX..
Tom Ball replied on Thu, 2008/07/10 - 3:40pm
Have you actually used Beans Binding on its own (i.e. without Netbeans generating all the code for you?).
Sure, its architect and I are teammates. Binding is hard to do in Java because the language doesn't hide any of the necessary plumbing -- that's one of the major reasons why JavaFX Script was created. FX doesn't call some "internal JFX API" to handle all binding, it generates a lot of code and relies on a small runtime, similar to what Beans Binding involves. The difference is that with Beans Binding you write the glue code, with JFX its compiler does, and with Flex it's done by the JavaScript interpreter using reflection.
There is no magic bullet for binding; the glue code has to come from somewhere. Chris Oliver (JavaFX Script's creator) has stated that he never set out to create a new language, he just wanted to write Swing apps much more quickly. If there was a way to write a binding library that didn't require all the client code you hate, he'd have written that library instead of a new language.
BTW, it should be possible to access Flex from Java, using the scripting API. This should reduce the glue code overhead, as long as performance isn't an issue.
Tom Ball replied on Thu, 2008/07/10 - 4:02pm ?
Not quite: Chris Oliver wrote a true interpreter, not a compiler. This interpreter made Java calls, just like any other Java application. The JavaFX compiler doesn't output Java, it outputs JVM class files; while it can create pseudo-Java files useful for debugging (as I mentioned earlier), JFX cannot map directly to Java because it needs things like block expressions. In theory it's possible to take a pseudo-Java dump file and turn it into a Java file (just like early C++ compilers output C intermediate files), but that's a lot of work compared to just writing JFX directly..
The Flex compiler generates JavaScript to be run by an interpreter that supports things like first-class functions, so it's more of a code generator than a traditional compiler (it's still a great piece of engineering work, of course). We compiler directly to the JVM without any interpretation, reflection, or other features available from JavaScript; that's great for performance and lower footprint (eventually), but makes intermediate code reuse impossible.
Tom
Jim Weaver replied on Thu, 2008/07/10 - 10:45pm
cfagan,
I think that layout managers and a dynamic node based system can work well together. IMO the primary reasons for layout managers are:
An example of the latter point is the Tetris game shown in the Watch for Falling Blocks: Take TetrisJFX for a Spin! post. It is handy to use the BorderPanel and FlowPanel to place those image buttons, as well as using other layout panels to place the playing field (where the blocks fall) next to the components to the right of it. When the application is resized, things are adjusted accordingly. See the the Game Over: Improving upon the Compiled JavaFX Tetris Program post for JavaFX code that illustrates this. Within the layout panels, nodes for the playing field, next piece in play, etc. are graphical nodes that have strict positioning requirements (for example locations of tetrominoes as they are falling). In that code example, whenever a node is placed within a layout panel, a Canvas must be used to adapt between the component and the node "worlds". On the other hand, when JavaFX completes the migration to a node-centric approach, adapting between the two worlds won't be necessary.
Thanks!
Jim Weaver
Peter Thomas replied on Fri, 2008/07/11 - 1:25am
I'm not sure I follow most of the detailed discussion above but:
So what I understand is I *have* to learn a new language if I want to use JavaFX. Not that I'm complaining, but hmm.
Tom Ball replied on Fri, 2008/07/11 - 1:53am
You only need to learn JavaFX Script if you want its compiler to generate the necessary plumbing code instead of writing it by hand (similar to the Beans Binding example Jacek wrote above). The same is true for Flex, which outputs JavaScript which could have been written by hand. It's much easier to use the JavaFX platform using JavaFX Script, but all the platform requires is JVM classfiles making the right calls to it.
Jacek Furmankiewicz replied on Fri, 2008/07/11 - 3:51am
in response to:
Tom Ball
Tom, I think you guys did a great job with Beans Binding...it's not the library that's the issue, but the fact that the JavaBean standard is woefully verbose compared to more modern languages.
This cannot be fixed by a library...it needs to be fixed via changes to the language itself to bring its features into the 21st century and compete more with its more nimble, recent competitors
Kevin Daly replied on Fri, 2008/07/11 - 9:05am
Leave Java alone!
Why all of this "change the language" bs!
We need to consider the JVM as the crown jewel of the "Platform", with things such as Java, JavaFX, JRuby, Groovy, JPython and whatever other language runtime they want to squeeze into the JVM.
Java has it's place, and if you want all of the syntatic sugar use Groovey or FX, it's no different to learning Flex & Actionscript, just you have access to the richness of the Java Platform, instead of Adobes limited API. It's the best of both worlds.
It always amazes me that people will complain that language xxx has this and language yyy has that, and they are going to leave Java for Language xxx or yyy, but they seem upset that they have to learn a new JVM language that has the features they want. I don't get it, if you are going to learn something new anyways, why not a language in the environment that you are familiar with.
Jacek Furmankiewicz replied on Fri, 2008/07/11 - 9:10am
in response to:
Kevin Daly
It's called being realistic. In the comfort of my home I like to learn any language there is.
But any corporations prefers to have one standard language that they know can do it all and they don't have to keep retraining people.
Moving people off one language to learn another is a huge investment for any employer and it better be worth it.
And let's be honest here...if Java can't do RIA, I think it is MUCH MORE likely that a corporation would look at Flex rather than JavaFX. It's called first-mover advantage and existing developer mindshare.
So there is a lot of benefit to take advantage of the massive number of Java developers who know the language inside out and make sure they can do RIAs in the tool they already know.
There's nothing stopping you from learning Groovy, Jython or JRuby at home. But try convincing your employer to re-train let's say 500 or a 1000 developers in a new language and you'd better have a damn good convincing business case. And as I said...they're probably more likely to look at Flex at that point, such is the reality of Java being so behind everyone else in the RIA space.
Kevin Daly replied on Fri, 2008/07/11 - 9:40am
in response to:
Jacek Furmankiewicz
I agree with you as far as Jython & JRuby training, but FX and Groovy are very tightly bound to Java almost to the point that they are simply extensions to the Java Language that should be part of any competent developers toolbox.
Groovy is trivial to learn since it is so close to Java & FX is not any different than a Microsoft developer having to learn XAML. I don't think that it is unreasonable to expect developers to learn these technologies as part of the "keeping current" part of learning a platform.
We as developers need to stop thinking in terms of languages, we need to have a broad based toolset that can be used to solve business problems, and we need to apply the correct tools to the problems at hand.
I acknowledge that people will look at Flex instead of FX or Java 6 Update 10 applets due to the fact that that is where the current mindshare rests, but the point I'm trying to make is that retraining is going to occur anyways, so why not choose technologies that are closer to the skill sets of Java developers such as FX / Groovy SwingBuilder or even just plain Swing Applets.
As to the common cry of "Java can't do RIA", I think that's bullshit, java applets were the original RIA tools, and although they've had a rough ride (somtimes unfairly), Java 6 Update 10 will re-juvinate applets and exceed what is possible with Flash/Flex. Take a look at pivot as well it's new, but it shows huge promise.
Jacek Furmankiewicz replied on Fri, 2008/07/11 - 9:54am
in response to:
Kevin Daly
I hope you are right...but from what I am seeing the RIA train has taken off and neither Java nor JavaFX are even on it.
And to be frank with you...I've seen Microsoft Expression Blend on the desks of some .net guys here...and nothing I've seen from JavaFX comes even close in terms of a graphical dev environment. I hope Sun can deliver some serious tooling for this and not only for NetBeans, but for Eclipse too.
And as for Java6u10...my first experiences with it were so so...it prompted me for proxy passwords on Firefox3 (unlike Flex or Silverlight) and on IE the Scenegraph applets would not even load...they were getting ActiveX errors!
So, I am happy for your optimism...but right now we are way behind both Flash and Silverlight. I hope JavaFX/Java6u10 can turn the tide, but they're so late already the window of opportunity may be closing.
Kevin Daly replied on Fri, 2008/07/11 - 10:41am
Last post, i've got tons of code to write.
I agree that expression blend is awsome, but It's not cross platform, so it's a non starter for me.
As far as being "behind", its all a matter of perspective, once Update 10 is out Java will be "ahead" in many ways. I'd love to see an OpenGL game such as the one based on Quake that was presented at JavaOne (don't remember the name), run in Flash or Silverlight. I'd love to see someone drag and drop an applet out of the browser like was demonstrated at JavaOne.
The JRE is much more compete than the Flex API & much more mature than Silverlight (it is also cross platform as well), so we're ahead there now.
Java has a vibrant open source community for components/frameworks such as Hibernate/Echo/Spring/Pivot etc etc etc. so we're ahead there as well.
etc etc.
Michael Bien replied on Fri, 2008/07/11 - 12:59pm
in response to:
Kevin Daly
[quote=kedaly]I'd love to see an OpenGL game such as the one based on Quake that was presented at JavaOne (don't remember the name), run in Flash or Silverlight.[/quote]
its called Jake2 and is a 1:1 port of Quake2 to java using JOGL (or LWJGL) as OpenGL binding.
original website:
the demo applet you saw @ J1 is here:
hassen karkar replied on Sun, 2008/08/03 - 8:30am
I'am working with javafx using javafx plugin for eclipse. i don't know how can i use the javafx compiler to run applications.
i used "javafx.ui" package and now when i import "javafx.ext.swing" there are errors even i had added the jars from "openjfx-compiler-tp1\dist\lib" to my project source path.
code :
import javafx.ext.swing.*;SwingFrame {
height: 600
width: 500
visible: true
}
error : incompatible types: expected com.sun.javafx.runtime.location.IntVariable, found Integer in width: 500
|
http://java.dzone.com/articles/setting-stage-javafx-sdk
|
CC-MAIN-2014-35
|
refinedweb
| 2,513
| 67.69
|
.
template < typename DataType, template < typename > class Storage >
class SomeClass
{
Storage<DataType> data;
};
Select all
Open in new window
This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.
template <
typename ptrT, // The type of pointer
typename mutexT, // The type of mutex used by the thread policy (could be shared/timed/unique)
template <typename> class ThreadPolicy // Thead policy (might be single or multi thread)
>
class SharedPointer : ThreadPolicy<mutexT>
{
// Implementation goes here
};
#include <vector>
template < typename DataType, template < typename T > class Storage >
class SomeClass
{
Storage<DataType> data;
};
int main()
{
SomeClass<int, std::vector> someClass;
}
#include <vector>
template < typename DataType, template < typename T, typename A = std::allocator<DataType> > class Storage >
class SomeClass
{
Storage<DataType> data;
};
int main()
{
SomeClass<int, std::vector> someClass;
}
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.
template<typename A, typename /* never used so it has no name*/ >
class CMyClass{
A var1;
};
int main()
{
CMyClass<int, float> c
template < typename DataType, class Storage >
This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.
template<typename Storage>
class SomeClass{
Storage data;
};
SomeClass<vector<int>>
?
Open in new window
Hm, sadly I'm not understanding the purpose of that - mainly because I know nothing about threads... :(
Thanks,
Uni.
Ok, well a smart pointer has to be thread safe (in other words it must be protected from 2 threads trying to change it at the same time) and that protection is provided by a mutex (mutual exclusion) object but there are many different types that behave in different ways and have different semantics. Also, they are expensive in terms of performance. By allowing the mutex and the threading policy to be passed seperately we allow the caller to decide if they want a shared mutex (many readers but only 1 writer) or a timed mutex (block for a period of time and if still no access throw an error) or unique (block forever, never give up waiting for exclusive access). Meanwhile, the threading policy will be different depending upon if you know your application uses multipl;e threads or not. If you are using single threads your threading policy will most likely to nothing if it's using multipel threads the policy will implement aggressive mutual exclusion access to critical sections of the shared pointers code. The idea is these related but not bound together policies can be passed in as template param and template template param and they get bound together at the point of instgantiation. This mean, you can have many different smart pointers behaving in different ways to suit your needs all with the use of a simple typedef...
typedef SharedPointer<int, Shared, Multi> SM_SharedPointer;
typedef SharedPointer<int, Unique, S> SS_SharedPointer; // A little pointless maybe?
typedef SharedPointer<int, Timed, Multi> TM_SharedPointer;
It doesn't matter if you don't fully understand the concepts of threading or mutexes. The important thing is it gives you the flexibility to avoid binding things until the point of instantiation so you can implement your template class using policies rather than concrete types.
>> template <typename> class ThreadPolicy
...perhaps that would help me better understand it...?
When writing generic code using templates we use the terms concept and model (something that will be enforceable in C++0X but for now it's a convention). So a concept is something that a template is designed to work with... it's like the interface it expects. A model is something that implements this so it models the concept. If you write a class that allows callers to specify the storage type your class will expect a storage type that models the concept that your class is designed to work with. This is true of all template parameters whether they are template templates or template types.
It basically says, this template parameter is a template class, that I have named Thread Policy, that takes 1 template parameter. It can be instantiated like this...
ThreadPolicy<mutext_type> threadPolicy;
Will not work with
template < typename DataType, template < typename > class Storage >
class SomeClass
{
Storage<DataType> data;
};
...because template < typename > class Storage does not define a concept modeled by a vector. Kudos to who can tell me why this is (if not I'll tell you) :)
Great book... but I think a little too advanced for Uri (in fact most C++ programmers :) ) right now. I'm thinking C++ Templates by Vandevoorde & Josuttis is a better place to start.
Ooohhh... My head really hurts. :(
The problem of SomeClass<vector<int>> is that SomeClass does not see the int (in case of vector it actually does, using vector<int>::value_type, but STL is very specific in this). In most cases you need to see that int as well.
Right... That's slightly clearer... So consider the following example::
--------------------------
template<typename TContainerType>
class CStorage{
TContainerType storageArea;
};
CStorage<vector<int>> object;
will work fine, but the problems within the CStorage class is that it is impossible for me to tell:
a) What container type I'm using.
b) What data type that container is using.
which is sometimes good to know, is that correct?
--------------------------
--------------------------
template<typename TContainerType, typename TDataType>
class CStorage{
TContainerType<TDataType> storageArea;
};
CStorage<vector, int> object;
This too will work fine providing:
1) The container type I pass in is compatible with the TDataType, of which I have no assurance?
Is that correct?
--------------------------
Kudos to who can tell me why this is
I think you can guess who can't tell you why! ;)
I'm afraid I'm still not quite grasping the concept of having a template within a template. :( I'm trying to get to grips with it by working on the principle of handling a container and it's data type.
template < typename DataType, template < typename > class Storage >
I THINK I see the purpose of this, but I'm still struggling with the syntax. :(
I'm thinking C++ Templates by Vandevoorde & Josuttis is a better place to start.
That reminds me, that should have been delivered today after you recommended it to me a couple of days ago! Must follow that up on Monday....
Thank you,
Uni.
typeid(TContainerType)
>> b) What data type that container is using.
typeid(TContainerType::val
>> The container type I pass in is compatible with the TDataType, of which I have no assurance
Sure you do... if it wasn't then the compiler would error -- if it doesn't that's your assurance :)
>> I think you can guess who can't tell you why! ;)
Look at the other question I just answered for you... look at how vector is defined (you already now this) and now look at that template template parameter and see what it expects... see the difference? Go on Uri, I know you'll get this.
>> I'm afraid I'm still not quite grasping the concept of having a template within a template
it's just a way of telling the compiler what template type to used rather than it being hard coded into the class. So, if you have a stack, for example, you could implement it with a list or a vector or a dequeue. Each has pros and cons. Your stack can take the concrete type as one template param (the type you wish to store in the container) and the storage container type as the template template. Of course, this could eb done by just taking one concrete type of the container already defined to take, for example an int, but doing it as 2 separate params gives the user more flexibility. The type bing store and the container being used might not be decided in the same part of the calling code so the decision of which of these two to use might happen at different times.
>> I THINK I see the purpose of this, but I'm still struggling with the syntax. :(
You define a template this...
template <typename T>
You define a template template thus
template < template <typename> class TemplateTemplateName >
It's just a template declaration within another template declaration(except the class keyword follows it with the name you wish to give the template template -- this is arbitrary and up to you just like the name of any template parameter.
>> That reminds me, that should have been delivered today after you recommended it to me a couple of days ago! Must follow that up on Monday...
I used to have 2 copies :) I can also recommend C++ Template Metaprogramming (concepts, tools and techniques from Boost and Beyind) by David Abrahams and Aleksey Gurtovey.
**** Build of configuration Debug for project scratchcpp ****
make -k all
Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp"
../main.cpp: In function int main():
../main.cpp:13: error: type/value mismatch at argument 2 in template parameter list for template<class DataType, template<class T> class Storage> class SomeClass
../main.cpp:13: error: expected a template of type template<class T> class Storage, got template<class _Tp, class _Alloc> class std::vector
../main.cpp:13: error: invalid type in declaration before ; token
../main.cpp:13: warning: unused variable someClass
make: *** [main.o] Error 1
make: Target `all' not remade because of errors.
Build complete for project scratchcpp
Open in new window
BTW: The reason I'm letting you figure out my little puzzle is because it will aid your understanding if you can figure it out for yourself.
Thank you. Your help with this is really appreciated! :)
Night dude.
Later.
Uni.
Which Part? Me, Luton (25 miles north of London).
>>Which Part?
Newcastle. :)
Anyways, I think I may be a little closer to understanding things... :) So if we've got something like:
template < typename TDataType, template < typename TNullDataType > class TContainerType >
then TDataType specifies what data type the container (which is specified with TContainerType) will hold. The TNullDataType isn't used at all, but is required because a vector (and most other containers) are declared as follows:
vector<TDataType>
So we need the TNullDataType to satisfy the way containers are declared. What I'm not quite grasping is why we must specify the data type for the container twice, why can't we just use TNullDataType and not have the first parameter (TDataType)?
Thanks,
Uni
template < typename TDataType, template < typename TNullDataType > typename TContainerType >
Why the need to replace the last typename with class? I know you (evilrix) mentioned it in passing in a previous question but it was not relevant then for it to be explained why.
Thanks,
Uni
Just a quick holding post. I am quite busy today (Saturday's eh?) but I will try and get back to you later.
Meanwhile, here are some links I think might help you out a little...
..I'll try and respond to you fully tonight.
>> Newcastle. :)
Geordie eh? "Shy Bairns Get Nae Sweeties" (apparently that's a Geordie thing to day). Great place to go drinking ;)
>> then TDataType specifies what data type the container (which is specified with TContainerType) will hold
Well, no. It just specifies the type passed in as the first parameter, that doesn't mean it'll be used to define a concrete type of TContainerClass, which could be defined using any type.
TContainerClass<int> intContainer;
TContainerClass<char> charContainer;
>> The TNullDataType isn't used at all
I never bother to specify the name, it's just a signature and the name isn't required...
template < typename TDataType, template < typename > class TContainerType >
...just like with a function signature you can leave of the parameter names...
void foo(int i, float f, char c);
void foo(int, float, char);
>> but is required because a vector (and most other containers) are declared as follows:
heh. that's not how vector is defined. Remember my little puzzle I set you and your question about allocators? But, other than that, yes TContainerClass defines a template template parameter that will accept any template defined thus
TContainer< TParam > // This is NOT how a vector is defined, so vector cannot be used here
But this is not going to work for a vector because a vector has a signature of template<typename valueT, typename allocatorT> vector<valueT, allocatorT> (see code below)
>> What I'm not quite grasping is why we must specify the data type for the container twice
You're not, the first type and the template type are unrelated, just because you might use the template type to define a concrete instance of the container doesn't mean you have too. The type parameter TDataType and the template parameter TContainerType are completely 2 different unassociated entities unless you bind them together in a definition to create a concrete type of TContainerType<TDataType>
template < typename TDataType, template < typename > class TContainerType >
void foo()
{
TContainerType<TDataType> tContainer; // Now we bind them together (but we don't have to)
TContainerType<int> intContainer;
}
>> Why the need to replace the last typename with class?
Because that's the syntax... you are not declaring a type here you are declaring a template class
Although often used interchangeably, there is a semantic difference between the template class and class template
". "
Open in new window
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
>>Right... I'm back. Yesterday was just too busy for me to get online.
Hehe, not a problem mate. :)
>>...just like with a function signature you can leave of the parameter names...
I'm not quite sure about this part. If we have:
template<typename, typename>
class A{};
how can class A ever use anything within the template as there are no parameter names to associate with?
If it's not being referenced there is no need to name it. Instantiations still have to conform to that signature though. In the case of a template template parameter we're just telling the compiler the template must conform to that signature but since we're not using the template parameters themselves we don't need to provide them.
Open in new window
Thanks very much,
Uni.
|
https://www.experts-exchange.com/questions/24561682/templated-templates.html
|
CC-MAIN-2018-39
|
refinedweb
| 2,420
| 59.84
|
A first hand look from the .NET engineering teams
In this post, we will look at the improvements that have been made for Windows Phone apps in Windows Phone 8. These improvements deliver major benefits in startup time and app responsiveness to end-users.
Today, we are happy to announce the availability of .NET for Windows Phone 8 and the Windows Phone SDK 8.0! We have made major updates to the .NET Framework runtime and code generation process that have resulted in startup time improvements as high as 50%. We have also included the new async programming model from .NET Framework 4.5 and the world-class garbage collector in the CoreCLR for better app responsiveness. Your customers will enjoy the big improvements that they see in your app running on Windows Phone 8.
Windows Phone 8 is built on a shared core with Windows 8. This stable, high-performance core has been used by hundreds of millions of end-users around the planet and is now the core of Windows Phone. CoreCLR is the core of the common language runtime (CLR) in the .NET Framework, which also delivers stability and high performance in .NET Framework apps to hundreds of millions of end-users around the planet. It made sense to include CoreCLR on top of the Windows Phone OS core to deliver this same promise for Windows Phone apps, so CoreCLR is now the core of Windows Phone apps.
For this release, we updated the Windows Phone OS and app platform to take advantage of multicore processing and to improve battery life. Most new devices are now multicore and come with the expectation that the OS and the apps will be faster because of that technology. Both Windows Phone 8 and CoreCLR take advantage of multiple cores and use modern software technologies and patterns. Users always appreciate any way that we can improve battery life. Our new approach to code generation removes a whole category of battery use for Windows Phone apps. Together, the new Windows Phone OS core and CoreCLR deliver lean and parallel experiences to end-users.
You can read the overview of the Windows Phone 8 release on the Windows Phone Developer blog. You can read more about the Windows Phone SDK 8.0 on the Visual Studio blog and Soma’s blog. Please visit the Windows Phone SDK 8.0 download page to install the tools, and read the article Getting Started with Windows Phone Development to start building a Windows Phone app if you haven’t built one before.
We’ve made many changes to the .NET Framework libraries and runtime in Windows Phone 8, including the introduction of the new async model. We also made substantial changes to the .NET Framework engine and to our ARM compiler. As a result, we’ve observed major performance improvements both in the lab and with actual Windows Phone Store apps. On average hardware, we have seen apps start up twice as fast as on Windows Phone 7.1 devices. End-users will notice and really appreciate the speed of your apps. We hope your apps see similar gains.
The most important recent advance in the .NET Framework is the new async programming model, introduced by C# 5, Visual Basic 11 in .NET 4.5. We’ve enabled the task-based async model on Windows Phone 8, with changes to both the CoreCLR and the .NET Framework libraries. This change is particularly relevant since Windows Phone 8 will run on multicore hardware. You can take advantage of these improvements by using the new async and await language keywords or by also using the popular Task Parallel Library. As a result, it is now much easier to provide a highly responsive UI experience for your users by leveraging both the async model and the multiple cores on end-user devices.
We added many new task-based async methods across the .NET Framework libraries to enable you to create asynchronous code without much effort. Much of the .NET Framework is now async, and we can expect that some new APIs will be async-only. You can create the responsive apps that your users want simply by moving to the new async APIs that we’ve added to the .NET Framework libraries. In addition, you can now use async APIs exposed in third-party libraries. Phone apps are a perfect candidate for the asynchronous programming model, so we encourage you to take advantage of these features to provide a much better user experience.
Most of the async methods in the .NET Framework are included in the Windows Phone SDK; however, a few of them are available via NuGet. We encourage you to download the additional async methods (specifically, System.Net APIs) via the Microsoft.Bcl.Async NuGet package to ensure that you have all of the .NET Framework async APIs available when you build Windows Phone 8 apps. More information is available here.
Windows Phone 8 includes the CoreCLR engine instead of the .NET Compact Framework. The CoreCLR includes many of the same features and optimizations as the CLR in the .NET Framework 4.5. As a result, it is a lot faster and more efficient than the .NET Compact Framework. In particular, the CoreCLR includes our world-class auto-tuning garbage collector. These changes result in reduced startup time and higher responsiveness in your apps.
For Windows Phone 8, we adopted a new code generation approach that is much better suited to the phone, both to deliver higher performance and to save battery life. Windows Phone 8 apps are compiled to high-quality ARM code before they are downloaded and deployed on end-user devices. They are compiled in the Windows Phone Store, with an optimizing compiler that does not have to satisfy the time and power constraints of a just-in-time (JIT) compiler. As a result, end-users will enjoy very fast app launch times on Windows Phone 8.
These changes are specific to Windows Phone 8, but they also improve launch times for Windows Phone 7.x apps. Both Windows Phone 7.x and 8 apps can be pre-compiled to high quality ARM code in the Windows Phone Store, before being downloaded and installed on Windows Phone 8 devices. You and your customers get the benefits of pre-compilation, without requiring you to make changes to your app. You can test out the pre-compiled binaries on your own Windows Phone 8 devices using Visual Studio 2012.
While these changes provide significant performance improvements for end-users, they also help battery life. In Windows Phone 7.x, app code was compiled every time the app was launched, and the CPU was used to compile that code, requiring battery power. With the new code generation approach in Windows Phone 8, apps are compiled in the Windows Phone Store with AC power generated from the Columbia River in Washington. That’s a better battery to use than yours! As you can see, we’ve removed an entire category of battery use on end-user devices.
Windows Phone 8 is designed to run existing Windows Phone apps unchanged. We’ve put in significant effort into maintaining application compatibility to ensure that your Windows Phone 7.1 app continues to run on the new Windows Phone 8 devices. It is recommended that you test your 7.1 app using the Windows Phone 8 device or emulator to ensure that you are getting a compatible experience.
In advance of new Windows Phone 8 devices coming to market, you may want to consider upgrading your existing Windows Phone 7.1 app to Windows Phone 8 to leverage new updates to the platform. The Windows Phone SDK 8.0 makes it easy to upgrade projects in Visual Studio 2012. Keep in mind that when you upgrade your existing Windows Phone 7.x app to Windows Phone 8, you may see changes in API behavior (serialization and isolated storage are the major categories in .NET to watch for) when the upgraded app is run on the Windows Phone 8 device or emulator. You can read more about compatibility on the Windows Phone app platform compatibility MSDN page.
Windows Phone 8 provides major new improvements for developers. I have already talked about the adoption of C# 5 and Visual Basic 11, particularly around async, which you can use in Windows Phone 8 apps. Another major improvement is Windows Runtime interop. You can call Windows Runtime APIs in your code to get access to new native OS APIs and third-party native APIs.
I expect that many of you are building both Windows Phone 8 apps and Windows Store apps. In many cases, you will be building versions of those apps that differ only slightly between the Windows Phone and the various Windows 8 form factors. You should find that you can share a significant degree of your app logic between these platforms.
Windows Phone 8 exposes a new type of native API through the Windows Phone Runtime, much like the Windows Runtime in Windows 8, if you are familiar with that new API technology. Many new APIs exposed in Windows Phone 8, like the Windows Phone Runtime Location API, are exposed by the Windows Phone Runtime. The CoreCLR engine has been updated to enable you to call Windows Phone Runtime APIs in your apps. In addition, native code developers can expose Windows Phone Runtime APIs, making their native code functionality available to .NET Framework developers. You will notice that you can call Windows Phone Runtime APIs just as naturally as you would call any managed APIs.
The Windows Phone Runtime enables you to call native APIs in both the Windows Phone SDK and as exposed by third parties. In Windows Phone 8, you cannot expose .NET Framework code via the Windows Phone Runtime.
Notice below that the Windows Phone XAML and Direct3D app project template is using this functionality. The Direct3DInterop class derives from IDrawingSurfaceManipulationHandler, which is defined in the Windows.Phone.Input.Interop namespace, which is a Windows Runtime namespace.
Additionally, you can call native code from within a managed app, as long as the native code is packaged and exposed to callers as a Windows Runtime type. We expect that several third-party native gaming engines will be leveraged this way. Note that we do not enable you to create Windows Runtime APIs using C# or Visual Basic in this release of Windows Phone.
We've simplified the way .NET Framework security works on Windows Phone 8. For those of you who've used .NET Framework Security Transparency Annotations in the past, you'll know that it takes a bit of work to correctly annotate assemblies, types, and methods. On Windows Phone 8, security is being enforced at the OS level and not by the managed runtime. This means that for apps authored for Windows Phone 8, you don't need to use security attributes in your code if you don't want to. For instance, you can call Windows Phone Runtime APIs without needing to annotate the method that's making this call as SecurityCritical. If, however, you have code that is shared between Windows Phone and other target .NET Framework platforms such as Desktop Windows or Silverlight, and you do use security annotations, the .NET security model will enforce those.
I talked earlier about the new code generation strategy. Your app is pre-compiled to high-quality ARM code in the Windows Phone 8 Store. You will want the opportunity to see and test the same experience that your customers will see. Using Visual Studio 2012, you can deploy your application to a Windows Phone 8 device by using the Start Without Debugging option (Ctrl+F5) in the Debug menu, as shown in the screen illustration below. When you select that option, application binaries will be pre-compiled to ARM code and deployed to your device. Your app is also pre-compiled and deployed when you choose the Start Performance Analysis option (Alt+F2) in the Debug menu. In both cases, you will see the same experience as your customers.
If you want pre-compiled binaries to be deployed to the device in debug mode (using the Start Debugging option (F5) under the Debug menu), choose Options and Settings in the Debug menu, and make sure that the Enable Just My Code check box is selected and the Suppress JIT optimization on module load (Managed only) check box is cleared.
We recognize that many of you have a C# XAML Windows Store app or plan to write one soon, and it may well be similar in form and function to the companion Windows Phone 8 app. To enable you to share code across the two apps, you can use a feature we announced a little while ago – Portable Class Libraries. Visual Studio 2012 Professional and Ultimate SKUs have built-in support for creating Portable Class Libraries. If you have not explored using Portable Class Libraries before, the Targeting Multiple Platforms with Portable Code blog post has a good overview. You can read more about how to architect your code and leverage Portable Class Libraries in the MSDN Magazine article titled Create a Continuous Client Using Portable Class Libraries.
Windows Phone 8 is an exciting new release for developers. We are happy about releasing the .NET Framework as a part of the SDK for Windows Phone 8. We’ve made significant improvements for start-up time performance and application responsiveness. As part of that, we’ve enabled you to use C# 5 and Visual Basic 11 features in your code, such as the async programming model. We’ve also enabled you to call Windows Phone Runtime APIs in the same natural way as managed APIs. We’ll be giving you a much more detailed look into many of these features in the coming months on this blog as well as at various sessions at the //Build Conference.
As always, we would like to hear from you. Please don’t hesitate to post a comment on the blog or at one of the forums that we monitor: Connect (report bugs), UserVoice (request features), and MSDN Forums (ask for help).
I can only hope that the CoreCLR is much better than its misery-inducing predecessor, .NET Compact.
Thanks for the great description.
Any plans to offer similar native code compilation capabilities for the desktop brother of .NET (besides NGEN)?
What is the story with Async for people who need to target 7.5 as well? For example if I have a service library can it use the Async features and be shared between 7.5 and 8?
Clint,
For async support in 7.5 projects, you must add an additional package using NuGet. See this post for details: blogs.msdn.com/.../using-async-await-without-net-framework-4-5.aspx
What's the deal with F# code on Windows Phone 8? Can it run portable DLLs? Can F# access WinMD libraries yet?
(note F# 2.0 introduced the Async programming model in 2010... I've used it on Windows Phone 7)
Thanks for supporting Await in VS2012 for WP7. I had been trying to convert the code to use Reactive extensions, but it was not going well. Now, I can revert those changes and continue with the codebase with minimal code differences between WP7 and WP8! Thanks!
In general how similar is this to Windows Mobile 6.0, Compact .Net Framework?
If I have a Windows Mobile 6.0, Compact Framework app (that has P-Invokes), how hard (or possible) will it be to port to Windows Phone 8?
@Moondevil - glad to know you liked the post! For .NET 4.5, NGen is currently our only native code compilation solution.
@clint - Jeremy's response is correct. Please look at blogs.msdn.com/.../using-async-await-without-net-framework-4-5.aspx to understand how to use Async on 7.5. We're quite excited about bringing that support downlevel.
Can hobbiest developers distribute apps without the expensive Windows Store yet (aka sideloading)? I see that there will be a capability for enterprises to do that, but right now this is an area where Android is still on top -- it's just a checkbox to allow non-store apps on the phone.
@Timothy, for the next six days, developer registration is going to be only $8. Look at blogs.windows.com/.../announcing-the-new-windows-phone-8-developer-platform.aspx for more details. You do need to go through the Windows Phone store or have an enterprise account to load apps.
@Stephen - Windows Mobile 6.0 and Windows Phone 7/8 are completely different application platforms. For instance, writing an app for WinMo involved using Windows Forms and heavy use of P/Invokes. On Windows Phone, the UI is all XAML based and P/Invokes are not supported (you use Windows Runtime to invoke native components).
@Ben--
Unfortunately, the Microsoft Visual F# tools do not support the use of F# on Windows Phone 8. We expect that some of you will manage to reference portable F# libraries from C# Phone 8 apps, and there may be other avenues to using F# on Windows Phone 8, including through other commercial products or by contributing to the F# open source release. However, these are not scenarios that we support or test.
How about a more helpful article - one that explains how many basic methods and classes are absent from .Net for Phone 8?
Trying to port even a rudimentary library is proving very hard - ArrayList is missing, XPathSelectElement is missing from XElement and the Socket class supports ONLY async and so on.
Your article opens with "many of the investments we’ve made across all platforms and years of incubation." well we too have invested in our own support/utility libraries only to find the code simply cannot be used.
Compounding this is the lackluster support for those trying to setup and use Dev accounts for phone development, things don't work, account validation takes months, phone unlocking is error prone and so on.
The good is very good - but there is a lot if bad too - so please spare a thought for those of us who do not work at Microsoft and must struggle with bewilderment on a daily basis.
Thanks
|
http://blogs.msdn.com/b/dotnet/archive/2012/10/30/announcing-the-release-of-the-net-framework-for-windows-phone-8.aspx
|
CC-MAIN-2014-42
|
refinedweb
| 3,057
| 64.81
|
Fabulous Adventures In CodingEric Lippert's Erstwhile Blog Evolution Platform Developer Build (Build: 5.6.50428.7875)2012-06-05T12:55:00ZA new fabulous adventure<div class="mine"> <p>Tomorrow, the 30th of November, 2012, is the first day of my fifth decade here on Earth, and my last day at Microsoft. (*)</p> <p>I've been working at Microsoft full-time since 1996 and had two years of internships before that. <strong>Microsoft is an awesome company.</strong>.</p> <p <a href="">ericlippert.com</a>. <strong>Please subscribe to the RSS feed</strong>, which is at <a title="" href=""></a>. (**)</p> <p>I also intend to finally start "tweeting" occasionally; if you haven't already, please follow me on Twitter where I am <a href="">@ericlippert</a>.</p> <p <a href="">the first post on my new blog</a>. As you'll see, I am very pleased that it will still involve supporting the C# development community, just in a different way.</p> <p. (***) <strong>Thank you all; I hope to continue to work with you in the future.</strong></p> <p>And thanks to you all, who have been reading this blog these past nine years. Your comments, praise and always constructive criticism have helped me learn what customers need and helped everyone here shape C# into the amazing tool it is today. <strong>I hope we can continue sharing this adventure;</strong> see you at <a href="">ericlippert.com</a>.</p> <p>Eric Lippert</p> <p><strong>UPDATE:</strong> Holy goodness, the outpouring here, on the new blog, on reddit, hacker news and twitter of both well-wishing and FUD is delightful for the former and distressing for the latter.</p> <p>Regarding the former: thank you all for your kind thoughts; I appreciate it very much.</p> <p>To dispel some of the rumours that are floating around regarding the latter: </p> <p>. </p> <p>.</p> <p>And finally:</p> <p>(3) The first day of my first decade was the day I was born. So tomorrow being the first day of my fifth decade makes me 40, not 50.</p> <p>Thank you again for your kind thoughts.</p> <p>Eric</p> <hr /> <p>(*) That timing is not coincidental.</p> <p>(**) Since I will no longer have the ability to reply to comments, they are shut off as of now. If you have comments, please leave them on the new blog. Thanks!</p> <p>(***) The most hilarious job title at Microsoft as far as I'm concerned.</p> </div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert is deriving a public class from an internal class illegal?<div class="mine"> <p. </p> <p>Suppose you and your coworker Alice are developing the code for assembly Foo, which you intend to be fully trusted by its users. Alice writes:</p> <p class="code">public class B<br>{<br> public void Dangerous() {...}<br>}</p> <p>And you write</p> <p class="code">public class D : B<br>{<br>... other stuff ...<br>}</p> <p <a href="">principle of least privilege</a>, Alice changes B to:</p> <p class="code">internal class B<br>{<br> public void Dangerous() {...}<br>}</p> <p>Alice need not change the accessibility of Dangerous, because of course "public" means "public to the people who can see the class in the first place".</p> <p <strong>when the intention is unclear, the compiler brings this fact to your attention by failing</strong>. The compiler is identifying yet another form of the Brittle Base Class Failure, which long-time readers know has <a href="">shown up in numerous places in the design of C#</a>. </p> <p>Rather than simply making this change and hoping for the best, you and Alice need to sit down and talk about whether B really is a sensible base class of D; it seems plausible that either (1) D ought to be internal also, or (2) D ought to <a href="">favour composition over inheritance</a>. Which brings us to my more general point:</p> <p><strong>More generally</strong>: the inheritance <strong>mechanism</strong> is, <a href="">as we've discussed before</a>, simply the fact that all heritable members of the base type are also members of the derived type. But the inheritance relationship <strong>semantics</strong>. </p> <p>In short, this rule of the language encourages you to use inheritance relationships to <strong>model the business domain semantics</strong> rather than as a <strong>mechanism for code reuse</strong>. </p> <p>Finally, I note that as an alternative, <strong>it <em>is</em> legal for a public class to implement an internal interface</strong>..</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert's still essential!<div class="mine"> <p><a href=""><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="EssentialCover" border="0" alt="EssentialCover" align="left" src="" width="240" height="240"></a>I am pleased to announce that <u>Essential C# 5.0</u> by Mark Michaelis, and, new for this edition, <em>yours truly</em>, is <a href="">available for pre-order now</a>. It will be in stores in early December.</p> <p>As long-time readers of this blog know, I was one of the <a href="">technical editors</a> for <u>Essential C# 4.0</u> and <u>Essential C# 3.0</u>.! Many thanks to Mark, as well as to Joan and everyone else at Addison-Wesley who made this process so smooth; you are all a pleasure to work with. Special thanks also to my coworker, C# specification guru Mads Torgersen, who wrote a very nice foreword for us, and to my colleague Stephen Toub who thoroughly reviewed the chapters dealing with asynchrony.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert contagion, part two<div class="mine"> <p><a href="">Last time I discussed how "dynamic" tends to spread through a program like a virus</a>: if an expression of dynamic type "touches" another expression then that other expression often also becomes of dynamic type. Today I want to describe one of the least well understood aspects of method type inference, which also uses a contagion model when "dynamic" gets involved.</p> <p>Long-time readers know that <a href="">method type inference is one of my favourite parts of the C# language</a>; for new readers who might not be familiar with the feature, let me briefly describe it. The idea is that when you have a method, say, <span class="code">Select<A, R>(IEnumerable<A> items, Func<A, R> projection)</span>, and a call to the method, say <span class="code">Select(customers, c=>c.Name)</span>, then we infer that you meant to say <span class="code">Select<<font style="background-color: #ffff00">Customer, string</font>>(customers, c=>c.Name)</span>, rather than making you spell it out. In that case, we would first infer that the list of customers is an <span class="code">IEnumerable<Customer></span>.</p> <p>The problem that the language designers faced when deciding how method type inference works with dynamic is exacerbated by <a href="">our basic design goal for dynamic, that I mentioned two weeks ago</a>:!</p> <p>What a mess. How do we get out of this predicament? The spec is surprisingly short on details; it says only:</p> <blockquote> <p class="spec">Any type argument that does not depend directly or indirectly on an argument of type dynamic is inferred using [the usual static analysis rules]. The remaining type arguments are <em>unknown. </em>[...] Applicability is checked according to [the usual static analysis rules] ignoring parameters whose types are <em>unknown. </em>(*)</p></blockquote> <p. </p> <p>For example, if we have:</p> <p class="code">void M<T, U>(T t, L<U> items)</p> <p>with a call </p> <p class="code">M(123, dyn);</p> <p>Then type inference infers that T is int from the first argument. Because the second argument is of dynamic type, and the formal parameter type involves type parameter U, we "taint" U with the "unknown type". </p> <p.</p> <p>But where does the transitive closure of the dependency relationship come into it? In the C# 4 and 5 compilers we did not handle this particularly well, but in Roslyn we now actually cause the taint to spread. Suppose we have:</p> <p class="code">void M<T, U, V>(T t, L<U> items, Func<T, U, V> func)</p> <p>and a call</p> <p class="code">M(123, dyn, (t, u)=>u.Whatever(t));</p> <p>We infer T to be int and U to be unknown. We then say that V depends on T and U, and so infer V to be unknown as well. Therefore type inference succeeds with an inference of <span class="code">M<int, unknown, unknown></span>. </p> <p.</p> <p><strong>Next time</strong> on Fabulous Adventures in Coding: <strong>Fabulous Adventures</strong>!</p> <hr> <p>(*) That last clause is a bit unclear in two ways. First, it really should say "whose types are <em>in any way</em> unknown". L<unknown> is considered to be an unknown type. Second, along with skipping applicability checking we also skip constraint satisfaction checking. That is, we assume that the runtime construction of L<unknown> will provide a type argument that satisfies all the necessary generic type constraints. </p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert contagion, part one<div class="mine"> <p><a href=""><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="biohazard" border="0" alt="biohazard" align="left" src="" width="240" height="231"></a. </p> <p <a href="">Cross Site Scripting</a> (XSS) attack waiting to happen right there. A common way to mitigate the XSS problem is to use <a href="">data tainting</a>,. </p> <p. </p> <p.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert method group of one<div class="mine"> <p>I'm implementing the semantic analysis of dynamic expressions in Roslyn this week, so I'm fielding a lot of questions within the team on the design of the dynamic feature of C# 4. A question I get fairly frequently in this space is as follows:</p> <p class="code">public class Alpha<br>{<br> public int Foo(string x) { ... }<br>}<br>...<br>dynamic d = whatever;<br>Alpha alpha = MakeAlpha();<br>var result = alpha.Foo(d);</p> <p>How is this analyzed? More specifically, what's the type of local result?</p> <p.</p> <p.</p> <p?</p> <p>That appears to be a reasonable question, but think about it a bit more. If you and I and the compiler know that overload resolution is going to choose a particular method then <em>why are we making a dynamic call in the first place?</em>.</p> <p>That's reason enough to not do the proposed feature, but let's think about it a bit more deeply by exploring a variation on this scenario that I glossed over above. Eta Corporation produces:</p> <p class="code">public class Eta {}</p> <p>and Zeta Corporation extends this code:</p> <p class="code">public class Zeta : Eta<br>{<br> public int Foo(string x){ ... }<br>}<br>...<br>dynamic d = whatever;<br>Zeta zeta = new Zeta();<br>var result = zeta.Foo(d);</p> <p>Suppose we say that the type of result is int because the method group has only one member. Now suppose that in the next version, Eta Corporation supplies a new method:</p> <p class="code">public class Eta <br>{<br> public string Foo(double x){...}<br>}</p> <p>Zeta corporation recompiles their code, and hey presto, suddenly result is of type dynamic! Why should Eta Corporation's change <strong>to the base class</strong> cause the semantic analysis of code that uses a <strong>derived</strong> class to change? This seems unexpected. C# has been carefully designed to avoid these sorts of "Brittle Base Class" failures; <a href="">see my other articles on that subject for examples of how we do that.</a></p> <p>We can make a bad situation even worse. Suppose Eta's change is instead:</p> <p class="code">public class Eta <br>{<br> protected string Foo(double x){...}<br>}</p> <p>Now what happens? Should we say that the type of result is int when the code appears outside of class Zeta, because overload resolution produces a single applicable candidate, but dynamic when it appears inside, because overload resolution produces two such candidates? That would be quite bizarre indeed.</p> <p. <strong>If you want static analysis then don't turn it off in the first place.</strong></p> <p><strong>Next time:</strong> the dynamic taint of method type inference.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert C# a strongly typed or a weakly typed language?<div class="mine"> <p>Presented as a dialogue, as is my wont!</p> <p><strong>Is C# a strongly typed or a weakly typed language?</strong></p> <p>Yes.</p> <p><strong>That is unhelpful.</strong></p> <p>I don't doubt it. Interestingly, if you rephrased the question as an "and" question, the answer would be the same.</p> <p><strong>What? You mean, is C# a strongly typed <em>and</em> a weakly typed language? </strong></p> <p>Yes, C# is a strongly typed language and a weakly typed language.</p> <p><strong>I'm confused.</strong></p> <p>Me too. Perhaps you should tell me precisely what you mean by "strongly typed" and "weakly typed".</p> <p><strong>Um. I don't actually know what I mean by those terms, so perhaps that is the question I should be asking. What does it <em>really</em> mean for a language to be "weakly typed" or "strongly typed"?</strong></p> <p>"Weakly typed" means "<em>this language uses a type verification system that I find distasteful</em>", and "strongly typed" means "<em>this language uses a type system that I find attractive</em>".</p> <p><strong>No way!</strong></p> <p>Way, dude.</p> <p><strong>Really?</strong></p> <p>These terms are meaningless and you should avoid them. <a href="">Wikipedia</a> lists <em><a href="">eleven</a></em>.</p> <p><strong>But surely they mean <em>something</em> other than "unattractive" or "attractive"!</strong></p> <p>I do exaggerate somewhat for comedic effect. So lets say: a more-strongly-typed language is one that has some <em>restriction</em> in its type system that a more-weakly-typed language it is being compared to lacks. That's all you can really say without more context.</p> <p><strong>How can I have sensible conversations about languages and their type systems then?</strong></p> <p>You can provide the missing context. Instead of using "strongly typed" and "weakly typed", actually describe the restriction you mean. For example, C# is <em>for the most part</em> a <strong>statically typed</strong> language, because the compiler determines facts about the types of every expression. C# is <em>for the most part</em> a <strong>type safe</strong> language because it prevents values of one static type from being stored in variables of an incompatible type (and other similar type errors). And C# is <em>for the most part </em>a <strong>memory safe</strong> language because it prevents accidental access to bad memory.</p> <p>Thus, someone who thinks that "strongly typed" means "the language <em>encourages</em> static typing, type safety and memory safety <em>in the vast majority of normal programs</em>" would classify C# as a "strongly typed" language. C# is certainly more strongly typed than languages that do not have these restrictions in their type systems.</p> <p <em>absolutely positively guarantees </em>static typing, type safety and memory safety <em>under all circumstances</em>" would quite rightly classify C# as "weakly typed". C# is not as strongly typed as languages that do enforce these restrictions all the time.</p> <p.</p> </div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Altitude<div class="mine"> <p>No computer programming stuff today; just some fun for Friday.</p> <p>As I'm writing this <a href="">Felix Baumgartner's attempt to set the world record for skydiving height by diving from a helium balloon has been scrubbed due to bad weather</a>. This attempt has got me thinking of my good friend JB, who back in 1982 <a href="">set the world record</a> (*) for hang gliding height by similarly using a helium balloon. </p> <p.</p> <p>Anyway, I recently learned that JB has uploaded the short film his brother Bims made to document the successful attempt at the record. Check it out, and enjoy the hairstyles of the 1980s: <a href=""><strong>Project Hang Glide</strong></a></p> <hr> <p>(*) It's in the 1988 Guinness Book of World Records. </p> <p>(**) His microgravity experiment ended up flying on the <a href="">Vomit Comet</a> rather than the shuttle. </p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Not Compute<div class="mine"> <p>One.</p> <p>So here's an interesting question: are there functions which cannot be computed, even in principle on a machine with arbitrarily much storage, by <em>any</em> C# program (*)? </p> <p>We already know the answer to that question. <a href="">Last year I pointed out that the Halting Problem is not solvable by any computer program</a>,.</p> <p.</p> <p. </p> <p>So then how many rules do we need to come up with for our Turing machine? A Turing machine with n bits of internal state has 2<sup>n</sup> possible states, and there are two possibilities for the value at the "current position" in the external state. (**) So that means that there are 2<sup>n+1</sup> state transition rules. Each transition rule will have to encode three things: (1) what are the n bits of the new internal state? (2) what value should the external state be changed to? and (3) how should we update the current position?</p> <p<sup>n</sup> x 3 possibilities. There are 2<sup>n+1</sup> state transition rules. Therefore the total number of possible Turing Machines that have n bits of internal storage is 3 x 2<sup>n+1 </sup> raised to the 2<sup>n+1 </sup>power, which, yes, grows pretty quickly as n gets large, but which is clearly a finite number. </p> <p.</p> <p. </p> <p <strong>slowest</strong> of the n-bit machines that actually terminates, when it is started with empty external storage.</p> <p><strong>Is S a computable function? </strong>Can we write a computer program that computes it?</p> <p>Your intuition should be telling you "no", but do you see why?</p> <p>.</p> <p>.</p> <p>.</p> <p>.</p> <p>.</p> <p>.</p> <p>.</p> <p>.</p> <p><a href="">Because if S were computable then H would be computable too!</a> <em>if it takes more than S(n) steps then we know that it must have been one of the n-bit Turing machines that runs forever</em>. We'd then be able to reliably compute H in finite time. Since we already know that H is not reliably computable in finite time then we know that S must not be computable either.</p> <p>The argument that I'm advancing here is known as the "Busy Beaver" argument because the n-bit Turing Machine that runs the longest is the "busiest beaver". I've tweaked the way that it is usually presented; rather than the <strong>n-bit</strong> Turing Machine that <strong>runs the longest</strong> before terminating, the "busiest beaver" is traditionally defined as the <strong>k-state</strong> Turing Machine that <strong>produces the largest output</strong>. The two characterizations are essentially equivalent though; neither version of the function is computable. </p> <p>An interesting fact about the busy beaver function (either way you characterize it) is that the function grows <em>enormously fast</em>. It's easy to think of functions that grow quickly; even simple functions like n! or 2<sup>n</sup> grow to astronomical levels for relatively small values of n, like 100. But our busiest beaver function S(n) grows faster than <em>any</em> computable function. That is, think of a function that grows quickly where you could write a program to compute its value in finite time; the busiest beaver function grows <em>faster</em> than your function, no matter how clever you are in coming up with a fast-growing function. Do you see why? You've got all the information you need here to work it out. (****)</p> <hr> <p>(*) Of course, there is nothing special about C#; it is a general-purpose programming language. We'll take as given that if there is a function that cannot be computed in C# then that function cannot be computed by any program in any programming language.</p> <p>(**) Of course, we don't need to state transitions from the halting state, but, whatever. We'll ignore that unimportant detail.</p> <p>(***) Of course, there could be a tie for longest, but that doesn't matter.</p> <p>(****).</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert do we ensure that method type inference terminates?<div class="mine"> <p>I missed the party. I was all set to be on that <a href="">massive</a> wave of <a href="">announcements</a> about <a href="">TypeScript</a>, and then a family emergency kept me away from computers from Thursday of last week until just now, and I did not get my article in the queue. Suffice to say that I am <strong>SUPER EXCITED</strong> about TypeScript. Long-time readers of this blog know that I <a href="">have a long history with ECMAScript</a>, and I've wanted features like this for quite some time. Since I've missed the first wave I'm going to digest some of the initial reactions and hopefully post something a bit more thoughtful farther down the road.</p> <p>Therefore, rather than talking about TypeScript today, here's a question I got from a coworker recently: since it is obviously important that the C# compiler not go into infinite loops, <strong>how do we ensure that the method type inference algorithm terminates?</strong></p> <p>The answer is quite straightforward actually, but if you are not familiar with method type inference then this article is going to make no sense. Check out my <a href="">type inference archive</a>, and specifically <a href="">this video</a>, if you need a refresher.</p> <p>Method type inference since C# 3.0 basically works like this: we create a set of <strong>bounds</strong>. </p> <p "<a href="">larger</a>". (*)</p> <p>The interesting part of method type inference is how we deal with lambdas. Suppose we have a method <span class="code">Select<A, R>(I<A>, Func<A, R>)</span> where the second argument is <span class="code">c=>c.Name</span>..)</p> <p>The type inference algorithm, at a high level, goes like this:</p> <ul> <li>Add bounds to type parameters based on all non-lambda arguments, and all lambda arguments where the delegate type has no type parameters in its inputs. <li>Loop <ul> <li>Is every type parameter fixed? <ul> <li>Type inference has succeeded. Terminate the algorithm.</li></ul> <li>Is there any lambda argument converted to a delegate type where the inputs of the delegate type are all known and the output type involves an unfixed type parameter? <ul> <li>Deduce the return type of all such lambdas and make inferences that add bounds to the corresponding delegate's output types.</li></ul> <li>Is there any unfixed, bounded type parameter that does not appear in an output type of a delegate that has unfixed input types? <ul> <li>Fix all such type parameters and go back to the top of the loop.</li></ul> <li>Is there any unfixed, bounded type parameter such that an unfixed type parameter depends on it, directly or indirectly? <ul> <li>Fix all such type parameters and go back to the top of the loop.</li></ul> <li>If we make it here then we failed to make progress; we have just as many fixed type parameters as we started with. Type inference fails. Terminate the algorithm.</li></ul></li></ul> <p>So, for example, if we had <span class="code">Select(customers, c=>c.Name);</span> where customers implements I<Customer> then we start by inferring that A has a lower bound of Customer (**). We have no lambda arguments that correspond to formal parameters where the delegate type has no type parameters in its inputs, so we enter the loop. </p> <p>Is every type parameter fixed? No. </p> <p>Is there any lambda argument converted to a delegate type where the inputs are known and the output involves an unfixed type parameter?</p> <p>No. There is a lambda argument converted to a delegate type, and the output involves unfixed type parameter R, but the input type is A and A is not fixed. So we have no inferences to make.</p> <p>Is there an unfixed type parameter that has bounds and does not appear in an output type of a delegate that has unfixed input types?</p> <p>Yes. A has bounds and does not appear as an output type, period.</p> <p>Therefore we fix A. It has only one bound, Customer, so we fix it to Customer. We have made progress, so we go back to the top of the loop.</p> <p>Is every type parameter fixed? No.</p> <p>Is there any lambda argument converted to a delegate type where the inputs are known and the output involves an unfixed type parameter? Yes!</p> <p>So now we make an inference. A is fixed to Customer, so we add the type of Customer.Name, say, string, as a lower bound to R.</p> <p>Now we must fix something. Is there an unfixed type parameter that has bounds and does not appear in an output type of a delegate that has unfixed input types?</p> <p>Yes. R is unfixed, it has bounds, and it appears as an output type of a delegate that has fixed input types, so it is a candidate for fixing. We fix R to its only bound, string, and start the loop again.</p> <p>Is every type parameter fixed? Yes. So we're done.</p> <p>This technique of preventing infinite loops by requiring that each loop iteration make progress is quite useful, and clearly in this case it guarantees that the algorithm executes the loop no more times than there are type parameters to fix. </p> <p <a href="">already know that analyzing lambdas is, worst case, an NP-HARD problem</a><sup>2</sup>) dependency relationships that each cost O(n) to analyze, and we could go through the loop n times, for an extremely unlikely worst case of O(n<sup>4</sup>). The implementation of this algorithm is actually O(n<sup>2</sup>) in the common case; because n is likely to be small, as I said, we have not put the effort into more sophisticated algorithms that can solve these graph problems even faster in the asymptotic case.</p> <hr> <p>(*).</p> <p>(**) Assuming that the type I<T> is covariant in T. If it were contravariant then we would deduce an upper bound, and if it were invariant then we would deduce an exact bound. <a href="">See my series on variance if that is not clear.</a> </p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert September 2012 CTP is now available<div class="mine"> <p.</p> <p <a href="">msdn.com/roslyn</a>.</p> <p>We would love to get your feedback on the <a href="">forum</a> or on <a href="connect.microsoft.com/visualstudio">connect.microsoft.com/visualstudio</a>.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert analysis of "is"<div class="mine"> <p>Before I get into the subject of today's fabulous adventure, I want to congratulate the whole rest of Developer Division on <a href="">the tremendously exciting product that we are formally launching today</a>. (I've done very little actual coding on Visual Studio 2012 and C# 5.0, being busy with the long-lead <a href="">Roslyn project</a>.) <a href="">Asynchronous programming support</a> in C# and VB is of course my favourite feature; there are far, far too many new features to mention here. Check out the <a href="">launch site</a>, and please do <a href="">send us constructive feedback</a> on what you do and do not like. We cannot respond in detail to all of it, but it is all appreciated. <hr> <p>Returning now to the subject we started discussing last time on FAIC: sometimes the compiler can know via "static" analysis (that is, analysis done knowing only the compile-time types of expressions, rather than knowing their possibly more specific run-time types) that an "is" operator is guaranteed to produce a particular result. </p> <p>But before we get into that, let's briefly review the meaning of "is" in C#. The expression</p> <p class="code">x is T</p> <p>for an expression x and a type T produces a bool. Generally speaking, if there is a <strong>reference, boxing or unboxing conversion</strong> from the <em>runtime</em> value of x to the type T then the result is true, otherwise the result is false. Note that in particular<strong> user-defined conversions are not considered</strong>. The intention of the operator is to determine if the <em>runtime</em> value of x is <strong>actually a useful value</strong> of the type T, (*) and therefore we add a few additional caveats:</p> <ul> <li>T may not be a pointer type <li>x may not be a lambda or anonymous method <li>if x is classified as a method group or is the null literal (**) then the result is false <li>if the runtime type of x is a reference type and its value is a null reference then the result is false <li>if the runtime type of x is a nullable value type and the HasValue property of its value is false then the result is false <li>if the runtime type of x is a nullable value type and the HasValue property of its value is true then the result is computed as though you were checking x.Value is T</li></ul> <p>So, knowing that, try to think of some situations in which you know for certain that "x is T" is going to always produce true, or always produce false. Here are a few that you and I know are always true:</p> <p class="code">int i = 123;<br>bool b1 = i is int;<br>bool b2 = i is IComparable;<br>bool b3 = i is object;<br>boolour criteria for when to make a warning</a>:. </p> <p.</p> <p>There are a lot more situations where you know that the result will always be false. Can you think of some? Here are just a few off the top of my head:</p> <p class="code">bool b5 = M is Func<object>; // M is a method group<br>bool b6 = null is object;<br>bool b7 = b5 is IEnumerable;<br>bool b8 = E.Blah is uint; // E is an enum type<br>bool b9 = i is double;</p> <p>The first two follow the rules of the spec. The latter three are cases where we can know via static analysis that the value cannot possibly be converted to the given type by a reference, boxing or unboxing conversion. We produce a warning for all these trivially-analyzed cases. (Though of course again some of these examples -- b6 in particular -- are unlikely to show up in real code.)</p> <p <em>cannot</em> possibly be true as a result. There are lots of cases where you and I know that a given expression will never be of a given type, but these cases can get quite complex. Let's look at three complex ones:</p> <p class="code">class C<T> {}<br>...<br>static bool M10<X>(X x) where X : struct { return x is string; }<br>static bool M11<X>(C<X> cx) where X : struct { return cx is C<string>; }<br>static bool M12<X>(Dictionary<int, int> d) { return d is List<X>; }</p> <p>In case M10 we know that X will always be a value type and no value type is convertible to string via a reference, boxing or unboxing conversion. The type check must be false.</p> <p.</p> <p>In case M12 we know that there is no way to make an object that inherits from both the dictionary and list base classes, no matter what X is. The type check must be false.</p> <p>In all these cases.</p> <p>Where is that line? The heuristic we actually use to determine whether or not to report a warning <strong>when we detect that there is no compile-time conversion from x to T</strong> is as follows:</p> <ul> <li>If neither the compile time type of x nor the type T is an open type (that is, a type that involves generic type parameters) then we know that the result will always be false. There's no conversion, and nothing to substitute at runtime to make there be a conversion. Give a warning. <li>One of the types is open. If the compile time type of x is a value type and T is a class type then we know that the result will always be false (***). (This is case M10 above.) We give a warning. <li>Otherwise, give up on further analysis and do not produce a warning.</li></ul> <p>This is far from perfect, but it is definitely in the "good enough" bucket. And "good enough" is, by definition, good enough. Of course, this heuristic is subject to change without notice, should we discover that some real user-impacting scenario motivates changing it. <hr> <p>(*) And not to determine the answers to other interesting questions, like "is there any way to associate a value of type T with this value?" or "can the value x be legally assigned to a variable of type T?"</p> <p>(**) There are some small spec holes here and around these holes are minor inconsistencies between the C# 5 compiler and Roslyn. We do not say what to do if the expression x is a namespace or a type; those are of course valid <em>expressions</em>. <em>does</em> say that "x is T" is an error if T is a static type; the C# 5 compiler erroneously allows this and produces false whereas the Roslyn compiler produces an error. </p> <p>(***) <strong>This is a lie</strong>; there is <strong>one</strong>?</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert "is" operator puzzle, part two<div class="mine"> <p>As I said <a href="">last time</a>, that was a pretty easy puzzle: either FooBar, or the type of local variable x, can be a type parameter. That is:</p> <p class="code">void M<FooBar>()<br>{<br> int x = 0;<br> bool b = x is FooBar; // legal, true if FooBar is int.<br> FooBar fb = (FooBar)x; // illegal<br>}</p> <p>or</p> <p class="code">struct FooBar { /* ... */ }<br>void M<X>()<br>{<br> X x = default(X);<br> bool b = x is FooBar; // legal, true if X is FooBar<br> FooBar fb = (FooBar)x; // illegal<br>}</p> <p <a href="">the dual nature of casts that I've mentioned before</a>: a cast can mean "<em>I know that this value is of the given type</em>, even though the compiler does not know that, the compiler should allow it", and a cast can mean "<em>I know that this value is not of the given type</em>; generate special-purpose, type-specific code to convert a value of one type to a value of a different type."</p> <p? </p> <em>dynamic</em>. </p> <p><strong>Next time:</strong> we'll explore the question "under what circumstances will the "is" operator give a warning at compile time stating that the "is" is unnecessary?"</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Adventures In Casting<div class="mine"> <p>I've <a href="">written a lot about casting over the years in this blog</a>,.</p> <p>I have no experience whatsoever with any kind of metalworking, so I'm learning as I go here and making mistakes along the way. I'm going to document the results of these experiments on my new blog, <a href="">Fabulous Adventures In Casting</a>. If this subject interests you, check it out!</p> <p>We now return to our regularly scheduled discussion of the "is" operator in C#.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert "is" operator puzzle, part one<div class="mine"> <p>It is possible for a program with some local variable x:</p> <p class="code">bool b = x is FooBar;</p> <p>to assign true to b at runtime, even though there is no conversion, implicit or explicit, from x to FooBar allowed by the compiler! That is,</p> <p class="code">FooBar foobar = (FooBar)x;</p> <p>would not be allowed by the compiler in that same program.</p> <p>Can you create a program to demonstrate this fact? This is not a particularly hard puzzle but it does illustrate some of the subtleties of the "is" operator that we'll discuss in the next episode.</p> </div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert ensues<div class="mine"> <p>No tech today, but this is too funny to not pass along, so consider this your fun for Friday. <br><br>What would happen if <a href="">Anders Hejlsberg</a> and <a href="">Barbara Liskov</a> were forced to <a href="">share an apartment</a> in an "odd couple" sitcom? (*)</p> <p>Apparently I'm the "Kramer" of this sitcom. I hope I'm played by <a href="">Ryan Gosling</a>. Additional suggestions on casting the principal roles can be left in the comments.</p> <hr> <p>(*) A single-threaded apartment, I'd assume.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert parameters and LINQ do not mix<div class="mine"> :</p> <p><a href=""><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="WP_000062" border="0" alt="WP_000062" src="" width="721" height="542"></a></p> <p>The whole thing was chock full of immense lightning arcs which unfortunately I did not capture in the image. This is certainly the largest isolated thunderstorm I've ever seen from the outside. Notice the characteristic anvil shape; <a href="">as I've described before</a>, we've got a huge heat engine here that is extracting the latent heat from the gaseous and liquid water, and then using that heat to power the updraft that sucks more warm water vapor upwards. Quite beautiful.</p> <p>Well, enough chit-chat about the weather. Today: <strong>what's wrong with this code?</strong></p> <p class="code">var seq = new List<string> { "1", "blah", "3" };<br>int tmp;<br>var nums = <br> from item in seq<br> let success = int.TryParse(item, out tmp)<br> select success ? tmp : 0;</p> <p>The intention is pretty clear: take a sequence of strings and produce a sequence of numbers by turning the elements that can be parsed as numbers into those numbers and the rest into zero.</p> <p>The C# compiler will give you a definite assignment error if you try this, which seems strange. Why does it do that? Well, think about what code the compiler will translate the last statement into:</p> <p class="code">var nums = <br> seq.Select(item=>new {item, success = int.TryParse(item, out tmp)})<br> .Select(transparent => transparent.success ? tmp : 0);</p> <p <em>definitely assigned</em> before it is read, this program is an error.</p> <p:</p> <p class="code">int tmp = 0;<br>var nums = <br> from item in seq<br> let success = int.TryParse(item, out tmp)<br><font style="background-color: #ffff00"> orderby item</font><br> select success ? tmp : 0;<br>foreach(var num in nums) { Console.WriteLine(num); }</p> <p>Now what happens? </p> <p.</p> <p <strong>it uses the current value of tmp</strong>, not the value that tmp was back in the distant past!</p> <p>So what is the right thing to do here? The solution is to write your own extension method version of TryParse the way it would have been written had there been nullable value types available in the first place:</p> <p class="code">static int? MyTryParse(this string item)<br>{<br> int tmp;<br> bool success = int.TryParse(item, out tmp);<br> return success ? (int?)tmp : (int?)null;<br>} <p>And now we can say:</p> <p class="code">var nums = <br> from item in seq<br> select item.MyTryParse() ?? 0;</p> <p>The mutation of the variable is now isolated to the activation of the method, rather than a side effect that is observed by the query. <strong>Try to always avoid side effects in queries.</strong></p> <hr> <p>Thanks to Bill Wagner for the question that inspired this blog entry.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert C# warn on null dereference?<div class="mine"> <p>As you probably know, the C# compiler does flow analysis on constants for the purposes of finding unreachable code. In this method the statement with the calls is known to be unreachable, and the compiler warns about it.</p> <p class="code">const object x = null;<br>void Foo()<br>{<br> if (x != null)<br> {<br> Console.WriteLine(x.GetHashCode());<br> }<br>}</p> <p>Now suppose we removed the "if" statement and just had the call. </p> <p class="code">const object x = null;<br>void Foo()<br>{<br> Console.WriteLine(x.GetHashCode());<br>}</p> <p>The compiler does <em>not</em> warn you that you're dereferencing null! The question is, as usual, <strong>why not?</strong></p> . </p> <p>Something I find helpful when thinking about a particular feature is to ask "<strong>is this a specific case of a more general feature?</strong>", <a href="">as we've already discussed</a>. But even without that, we do not want to give a warning every time we know that an exception must be thrown; that would then make this program fragment produce a warning:</p> <p class="code">int M()<br>{<br> throw new NotImplementedException();<br>}</p> <p>The whole point of throwing that exception in the first place is to make it clear that this part of the program doesn't work; giving a warning saying that it doesn't work is counterproductive; warnings should tell you things you don't already know.</p> <p>So let's just think about the feature of detecting when a constant null is dereferenced. How often does that happen, anyway? I occasionally make null constants; perhaps because I want to be able to say things like "<span class="code">if (symbol == InvalidSymbol)</span>" where <span class="code">InvalidSymbol</span> is the constant null; it makes the code read more like English. And maybe someone could accidentally say "<span class="code">InvalidSymbol.Name</span>" and the compiler could warn them that they are dereferencing null. </p> <p>We've been here before; in fact, <a href="">I made a list</a>. So let's go down it. </p> .</p> <p>Could we perhaps then generalize the feature in a different way? Perhaps instead of constants we should detect any time that the compiler can reasonably know that <em>any </em>dereference is probably a null dereference. Solving the problem perfectly is, again, equivalent to solving the Halting Problem, which we know is impossible, but we can use some clever heuristics to do a good job. </p> <p.</p> <p.</p> <p>What it really comes down to me for this feature is that last item on my list. Yes, it is always better to catch a bug at compile time, but that said, null dereference bugs <em>that the compiler could have told you about with certainty</em> are the easiest ones to catch at runtime <em>because they always happen the moment you test the code</em>. So that's some points against the feature.</p> <p. <strong>It's a lovely feature and I'd be happy to have it in the compiler, but it's just not big enough bang for the design, development and testing buck,</strong> and we have many higher priorities.</p> <p!</p> <p> </p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert is a cast not a cast?<div class="mine"> <p>I'm asked a lot of questions about conversion logic in C#, which is not that surprising. Conversions are common, and the rules are pretty complicated. Here's some code I was asked about recently; I've stripped it down to its essence for clarity:</p> <p class="code">class C<T> {}<br>class D<br>{<br> public static C<U> M<U>(C<bool> c)<br> {<br> return <strong>something</strong>;<br> }<br>}<br>public static class X<br>{<br> public static V Cast<V>(object obj) { return (V)obj; }<br>}</p> <p>where there are three possible texts for "<strong>something</strong>":</p> <p>Version 1: <span class="code">(C<U>)c</span><br>Version 2: <span class="code">X.Cast<C<U>>(c);</span><br>Version 3: <span class="code">(C<U>)(object)c</span></p> <p>Version 1 fails at compile time. Versions 2 and 3 succeed at compile time, and then fail at runtime if U is not bool. </p> <p><strong><font color="#646b86">Question: Why does the first version fail at compile time?</font></strong></p> <p. </p> <p><strong><font color="#646b86">Question: Then why does the second version succeed at compile time?</font></strong></p> <p>Because the compiler has no idea that a method named <span class="code">X.Cast<V></span>.</p> <p><strong><font color="#646b86">Question: So what about the third version? Why does it not fail like the first version?</font></strong></p> <p>This one is actually the same thing as the second version; all we've done is inlined the call to <span class="code">X.Cast<V></span>, <i>including the intermediate conversion to object!</i> That conversion is relevant.</p> <p><font color="#646b86"><strong>Question: In both the second and third cases, the conversion succeeds at compile time because there is a conversion to object in the middle?</strong></font></p> <p>That's right. The rule is: if there is a conversion from a type S to object, then there is an explicit conversion from object to S. (*) </p> .</p> <p><strong><font color="#646b86">Question: So this explains why compile-time type checking doesn't seem to work quite right on LINQ expressions?</font></strong></p> <p>Yes! You would think that the compiler would disallow nonsense like:</p> <p class="code">from bool b in new int[] { 123, 345 } select b.ToString();</p> <p>because obviously there is no conversion from int to bool, so how can range variable b take on the values in the array? Nevertheless, this succeeds because the compiler translates this to</p> <p class="code">(new int[] { 123, 345 }).Cast<bool>().Select(b=>b.ToString())</p> <p>and the compiler has no idea that passing a sequence of integers to the extension method <span class="code">Cast<bool></span> is going to fail at runtime. That method is a black box. You and I know that it is going to perform a cast, and that the cast is going to fail, but the compiler does not know that. </p> <p>And maybe we do not actually know it either; perhaps we are using some library other than the default LINQ-to-objects query provider that <em>does</em> know how to make conversions between types that the C# language would not normally allow. This is actually an extensibility feature masquerading as a compiler deficiency: it's not a bug, it's a feature!</p> <hr> <p>(*) You'll note that I did not say "there is an explicit conversion from object to every type", because there isn't. Can you think of a type S that cannot be converted to object?</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Best Advice I Ever Got<div class="mine"> <p>Just a quick link today:</p> <p>The super nice people over at InformIT (*) are running a series of short articles with the theme "the best advice I ever got", which I think should prove to be an interesting series. They were kind enough to ask me to give <a href="">an example of some good advice I got that helped my programming career</a>, though as you'll see it is not <em>actually</em> about programming at all.</p> <hr> <p>(*) You may recall that they also recently asked me for my advice <a href="">on good books for C# programmers</a>. In the interests of full disclosure, I note that in my spare time I write and edit C# programming books for Addison-Wesley, which is owned by the same company that owns InformIT.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert consistency is foolish<div class="mine"> <p>Once again today's posting is presented as a dialogue, as is my wont.</p> <blockquote> <p><strong><font color="#646b86">Why is var sometimes <em>required</em> on an implicitly-typed local variable and sometimes <em>illegal</em> on an implicitly typed local variable?</font></strong></p></blockquote> <p>That's a good question but can you make it more precise? Start by listing the situations in which an implicitly-typed local variable either must or must not use var.</p> <blockquote> <p><strong><font color="#646b86">Sure. An implicitly-typed local variable must be declared with var in the following statements:</font></strong></p> <p class="code">var x1 = whatever;<br>for(var x2 = whatever; ;) {}<br>using(var x3 = whatever) {}<br>foreach(var x4 in whatever) {}<br></p> <p><strong><font color="#646b86">And an implicitly-typed local variable must not be declared with var in the following expressions:</font></strong></p> <p class="code">from c in customers select c.Name<br>customers.Select(c => c.Name)</p> <p><strong><font color="#646b86">In both cases it is not legal to put var before c, though it would be legal to say:</font></strong></p> <p class="code">from Customer c in customers select c.Name<br>customers.Select((Customer c) => c.Name)</p> <p><strong><font color="#646b86">Why is that?</font></strong></p></blockquote> <p>Well, let me delay answering that by criticizing your question further. In the query expression and lambda expression cases, are those in fact implicitly typed locals in the first place?</p> <blockquote> <p><strong><font color="#646b86".</font></strong></p></blockquote> <p>Can you expand on that last point a bit?</p> <blockquote> <p><strong><font color="#646b86">Sure. When you say </font></strong></p> <p class="code">from Customer c in customers select c.Name </p> <p><strong><font color="#646b86">that is not transformed by the compiler into </font></strong></p> <p class="code">customers.Select((Customer c) => c.Name)</p> <p><strong><font color="#646b86">Rather, it is transformed into </font></strong></p> <p class="code">customers.Cast<Customer>().Select(c => c.Name) </p></blockquote> <p>Correct. Discussing why that is might be better left for another day. </p> <blockquote> <p><strong><font color="#646b86">Indeed; the point here is that regardless of whether a type appears in the query expression, the lambda expression in the transformed code is going to have an untyped formal parameter.</font></strong></p></blockquote> <p>So now that we've clarified the situation, what is your question?</p> <blockquote> <p><strong><font color="#646b86">C# is inconsistent; var is <em>required</em> on an implicitly-typed local variable (regardless of the "container" of the local declaration), but var is <em>illegal</em> on an implicitly-typed lambda parameter (regardless of whether the lambda parameter is "natural" or is the result of a query expression transformation). Why is that?</font></strong></p></blockquote> <p>You keep on asking "why?" questions, which I find difficult to answer because your question is secretly a "why not?" question. That is, the question you really mean to ask is "<em>I have a notion of how the language obviously ought to have been designed; why is it not like that?</em>" But since I do not know what your notion is, it's hard to compare its pros and cons to the actual feature that you find inconsistent. </p> <p. </p> <p>I can see three ways to address that inconsistency. First, make var <em>required</em> on lambdas and query expressions, so that it is consistently required. Second, make var <em>illegal</em> on all locals, so that it is consistently illegal. And third, make it <em>optional</em> everywhere. What is the real "why not?" question?</p> <blockquote> <p><strong><font color="#646b86">You're right; I've identified an inconsistency but have not described how I think that inconsistency could be removed. I don't know what my real "why not?" is so let's look at all of them; what are the pros and cons of each? </font></strong></p></blockquote> <p>Let's start by considering the first: require var everywhere. That would then mean that you have to write:</p> <p class="code">from var c in customers join var o in orders...</p> <p>instead of</p> <p class="code">from c in customers join o in orders...</p> <p>And you have to write</p> <p class="code">customers.Select((var c) => c.Name)</p> <p>instead of </p> <p class="code">customers.Select(c => c.Name)</p> <p>This seems clunky. What function does adding var in these locations serve? It does not make the code any more readable; it makes it less readable. We have purchased consistency at a high cost here. The first option seems untenable.</p> <p>Now consider the second option: make var illegal on all locals. That means that your earlier uses of var on locals would become:</p> <p class="code">x1 = whatever;<br>for(x2 = whatever; ;) {}<br>using(x3 = whatever) {}<br>foreach(x4 in whatever) {}</p> <p>The last case presents no problem; we know that the variable declared in a foreach loop is always a new local variable. But in the other three cases we have just added a new feature to the language; we now have not just implicitly <em>typed</em> locals, we now have implicitly <em>declared</em> locals. Now all you need to do to declare a new local is to assign to an identifier you haven't used before.</p> <p.</p> <p>The third option -- make var optional everywhere-- is just a special case of the second option; again, we end up introducing implicitly declared locals. </p> <p>Design is the art of compromising amongst various incompatible design goals. In this case, consistency is a goal but it loses to more practical concerns. This would be a foolish consistency.</p> <blockquote> <p><strong><font color="#646b86">Is the fact that there is no good way out of this inconsistency an indication that there is a deeper design problem here?</font></strong></p></blockquote> <p <em></em></p> <p class="code"><em>type identifier <strong>;</strong> </em></p> <p>This is not a great statement syntax in the first place. Suppose C# 1.0 had instead said that a local variable must be declared like this:</p> <p class="code"><em><strong>var</strong> identifier <strong>: </strong>type <strong>;</strong> </em></p> <blockquote> <p><font color="#646b86"><strong>I see where you are going; JScript.NET does use that syntax, and makes the type annotation clause optional. And of course Visual Basic uses the moral equivalent of that syntax, with Dim instead of var and As instead of :.</strong></font></p></blockquote> <p>That's right. So in typing-required C# 1.0 we would have</p> <p class="code">var x1 : int = whatever;<br>for(var x2 : int = whatever; ;) {}<br>using(var x3 : IDisposable = whatever) {}<br>foreach(var x4 : int in whatever) {}</p> <p>This is somewhat more verbose, yes. But this is very easy to parse, both by the compiler and the reader, and is probably more clear to the novice reader.<em> It is crystal clear that a new local variable is being introduced by a statement</em>. And it is also nicely reminiscent of base class declaration, which is a logically similar annotation. (You could have just as easily asked "<em>Why does the constraining type come to the left of the identifier in a local, parameter, field, property, event, method and indexer, and to the right of the identifier in a class, struct, interface and type parameter?</em>" Inconsistencies abound!)</p> <p>Then in C# 3.0 we could introduce implicitly typed locals <em>by simply making the annotation portion optional</em>, and allowing all of the following statements and expressions:</p> <p class="code">var x1 = whatever;<br>for(var x2 = whatever; ;) {}<br>using(var x3 = whatever) {}<br>foreach(var x4 in whatever) {}<br></p> <p class="code">from c in customers select c.Name<br>from c : Customer in customers select c.Name<br>customers.Select(c => c.Name)<br>customers.Select((c : Customer) => c.Name)</p> <blockquote> <p><font color="#646b86"><strong>If this syntax has nicer properties then why didn't you go with it in C# 1.0? </strong></font></p></blockquote> <p>Because we wanted to be familiar to users of C and C++. So here we have one kind of consistency -- consistency of experience for C programmers -- leading a decade later to a problem of C# self-consistency. </p> <p>The moral of the story is: good design requires being either impossibly far-sighted, or accepting that you're going to have to live with some small inconsistencies as a language evolves over decades.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Rambles On About C#, Again<div class="mine"> <a href="">here</a>, and the video has also been posted to YouTube <a href="">here</a>. </p> <p!</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert behaviour<div class="mine"> <p>As I've mentioned several times on this blog <a href="">before</a>, C# has been carefully designed to eliminate some of the "undefined behaviour" and "implementation-defined behaviour" that you see in languages like C and C++. But I'm getting ahead of myself; I should probably start by making a few definitions. </p> <p>Traditionally we say that a programming language idiom has <strong>undefined behaviour</strong>!) <p.</p> <p>By contrast, an idiom that has <strong>implementation-defined behaviour</strong>. <p>All that said, for the rest of this article I'm not going to make a strong distinction between these two flavours of underspecified behaviour. The question I'm actually interested in addressing today is: <p><strong>What are some of the factors that lead a language design committee to leave certain language idioms as undefined or implementation-defined behaviours?</strong> <p>The first major factor is: <strong>are there two existing implementations of the language in the marketplace that disagree on the behaviour of a particular program?</strong> If FooCorp's compiler compiles <span class="code">M(A(), B())</span>. <em>Particularly this is the case if FooCorp and BarCorp both have representatives on the committee.</em> <p>The next major factor is: <strong>does the feature naturally present many different possibilities for implementation, some of which are clearly better than others?<<br> <p class="code">from c in customers<br>from o in orders<br>where c.Id == o.CustomerId<br>select new {c, o} <p>and<br> <p class="code">from c in customers<br>join o in orders on c.Id equals o.CustomerId<br>select new {c, o} . <p>By contrast, the C# specification says that the <span class="code">foreach</span> loop should be treated as the equivalent <span class="code">while</span> loop inside a <span class="code">try</span> <span class="code">GetEnumerator</span>.</p> <p>A third factor is: <strong>is the feature so complex that a detailed breakdown of its exact behaviour would be difficult or expensive to specify?</strong>. <p>A fourth factor is: <strong>does the feature impose a high burden on the compiler to analyze?</strong> For example, in C# if you have:</p> <p class="code">Func<int, int> f1 = (int x)=>x + 1; <br>Func<int, int> f2 = (int x)=>x + 1; <br>bool b = object.ReferenceEquals(f1, f2); </p> <p>Suppose we were to <em>require</em> b to be true. <em>How are you going to determine when two functions are "the same"<. <p>A fifth factor is: <strong>does the feature impose a high burden on the runtime environment?</strong> <p. <p>A sixth factor is: <strong>does making the behaviour defined preclude some major optimization</strong>? For example, C# defines the ordering of side effects <em>when observed from the thread that causes the side effects</em>.. <p>Those are just a few factors that come to mind; there are of course many, many other factors that language design committees debate before making a feature "implementation defined" or "undefined".</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert, Facades and Roslyn's Red-Green Trees<div class="mine"> <p>We decided early in the Roslyn design process that the primary data structure that developers would use when analyzing code via Roslyn is the <strong>syntax tree</strong>.: <ul> <li>Immutable. <li>The form of a tree. <li>Cheap access to parent nodes from child nodes. <li>Possible to map from a node in the tree to a character offset in the text. <li><strong>Persistent</strong>.</li></ul> <p>By <em>persistence</em> I mean the ability to <em>reuse most of the existing nodes in the tree</em> when an edit is made to the text buffer. Since the nodes are immutable, there's no barrier to reusing them, <a href="">as I've discussed many times on this blog</a>.. <p>When you try to put all five of those things into one data structure you immediately run into problems: <ul> <li>How do you build a tree node in the first place? The parent and the child both refer to each other, and are immutable, so which one gets built first? <li>Supposing you manage to solve that problem: how do you make it persistent? You cannot re-use a child node in a different parent because that would involve telling the child that it has a new parent. But the child is immutable. <li>Supposing you manage to solve that problem: when you insert a new character into the edit buffer, the absolute position of <em>every node that is mapped to a position after that point</em> changes. This makes it very difficult to make a persistent data structure, because any edit can change the spans of most of the nodes!</li></ul> <p>But on the Roslyn team we routinely do impossible things. We actually do the impossible by keeping <em>two</em> parse trees. The "green" tree is immutable, persistent, has no parent references, is built "bottom-up", and every node tracks its <em>width</em> but not its <em>absolute position</em>. When an edit happens we rebuild only the portions of the green tree that were affected by the edit, which is typically about O(log n) of the total parse nodes in the tree. <p>The "red" tree is an immutable <em>facade</em> that is built around the green tree; it is built "top-down" <em>on demand</em> and thrown away on every edit. It computes parent references by <em>manufacturing them on demand as you descend through the tree from the top</em>. It manufactures absolute positions by computing them from the widths, again, as you descend. <p>You, the consumer of the Roslyn API, only ever see the red tree; the green tree is an implementation detail. (And if you use the debugger to peer into the internal state of a parse node you'll in fact see that there is a reference to <em>another</em> parse node in there of a different type; that's the green tree node.) <p>Incidentally, these are called "red/green trees" because those were the whiteboard marker colours we used to draw the data structure in the design meeting. There's no other meaning to the colours. <p.</p> <hr> <p>(*) Determining what those portions of the tree are is quite tricky; I might blog about that at a later date. An edit that, for example, adds "<span class="code">async</span>" to a method can cause the parse of "<span class="code">await(foo);</span>" in the method body to change from an invocation to a usage of the <span class="code">await</span> contextual keyword.</p></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert Microsoft Roslyn June 2012 CTP<p class="mine">Good afternoon all, I am happy to announce that we are releasing a <strong>second</strong> Community Technology Preview release of Roslyn, the project I actually work on, today. I am super excited!</p> <p class="mine">So, let's cut to the chase. Key facts:</p> <div class="mine"> <ul> <li>Roslyn is a library of code analysis APIs useful for building compilers, development environments, refactoring engines and so on. It supports lexical, grammatical and semantic analysis of C# and Visual Basic. And it is awesome. <li>This version of the CTP works well with the <a href="">Visual Studio 2012 Release Candidate that was recently made available for download</a>. <li>The C# semantic analysis engine <a href="">now supports most, but not all, the C# language features</a>. In particular, query expressions, anonymous types, anonymous functions and iterator blocks are now supported. The largest not-yet-implemented features are the "dynamic" feature from C# 4 and the "await" feature from C# 5. Nullable arithmetic <em>mostly</em> works but the code we generate is non-optimal; I haven't had time to write an optimizer yet. <li>We are giving you this sneak peek in order to get your feedback on the API design and related features such as the interactive window. <strong>Please post any comments you have to the <a href="">Roslyn forum</a>, and not to this blog.</strong> We have a team of awesome program managers who are gathering feedback from the forums and using it to help us tune the APIs to be as useful as possible for you all. We'll certainly take bug reports, but constructive feedback on the APIs is what we are going for here. <li>For a longer overview of this release, see <a href="">Jason's blog post</a>. You can get all the details and download the CTP from <a href="">msdn.com/roslyn</a>. </li></ul></div><div style="clear:both;"></div><img src="" width="1" height="1">Eric Lippert
|
http://blogs.msdn.com/b/ericlippert/atom.aspx
|
CC-MAIN-2015-06
|
refinedweb
| 11,590
| 61.87
|
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
On 15 Dec 2001, Alexandre Oliva wrote: > > But I begin to see light at the end of the tunnel. Since the standard > says what constitutes an access is unspecified, implementations are > free to choose whatever makes the most sense for them, or for their > users :-) Well, you'd _hope_ that it's for "their users". > I suppose we could say that an lvalue constitutes an access only if > its result, as an rvalue, is used. Now, PLEASE don't go down that path. That way lies madness. I'll give you an example: volatile int p; int foo(void) { return p; } int main(void) { foo(); return 0; } Now, compile the above with -O3, and watch "foo" be inlined. Is the rvalue of "p" actually "used" or not? >From a syntactic standpoint, looking at just "foo()", yes. >From a _semantic_ standpoint, depending on how well you analyze the program, equally clearly the answer is "no". The optimizer will get rid of all uses (the _uses_ are certainly not volatile). Basically, "use" is a REALLY BAD thing from a semantic standpoint - the semantics of whether something is used or not often depends on how hard you look at the problem. So if you start making decisions based on "use", then you will always fight behaviour that changes due to subtle optimization issues etc. Now, what about the "syntax-only" use? I claim that it has the same problem: very slight syntactic sugar will change behaviour subtly. For example, is something like ({ p; }) is "syntactic use" or not? Nobody actually _uses_ the value, but the compiler might, depending on internal implementation issues, consider this equivalent to "using" the value of "p" as the "value of the compound statement". Or is just the simple statement p; a "use" of the value? I agree with rth that you can always claim that it is "implementation dependent", but can you claim that it is _consistent_? I don't think you can. If the lvalue-statement "p;" is considered to be a use of the rvalue, then why is not the lvalue-statement "p = 0;" considered to have used _its_ rvalue? Basically, any which way you define "use", you _always_ have problems. You always have to explain you special cases, and special cases are _bad_, even if they are implementation-defined. > I.e., it appears that we're free to choose. We just have to decide > which semantics we want. I'd much prefer to ask what the sane and _consistent_ semantics are that can be clearly documented, and that are _not_ dependent on subtle issues like "optimization" and non-local syntactic sugar. Also, I still claim that the standard CLEARLY SAYS (5.17.1): "..the result of the assignment operation is the VALUE STORED.." (emphasis mine). Nobody has been able to refute that fact, and the best that people like Gabriel have been able to come up with is to _ignore_ that part of the standard. And I will say that if I have volatile int *p; and "p" points to a write-only IO memory area that on read always returns zero, then a compiler that returns zero for the expression x = ... some computed non-zero-value .. return (*p = x); is a _buggy_ compiler. That compiler is clearly _violating_ the sentence of the standard that says that the return value of the assignment expression is the value stored (which is non-zero). Why do you and Gabriel _continue_ to ignore this very real sentence? I've quoted the standard up and down, left and right, and NOBODY has been able to refute the fact that the standard clearly says that the result of an assignment is the value stored. I've shown that that part in _no_ way violates the fact that the assignment is a lvalue. And this is not an issue of "accesses to volatile memory are 'implementation defined'". This is a clear issue of _correctness_, where current gcc behaviour does NOT match the language of the standard. Gcc currently does NOT return the "value stored" like the standard mandates. _Please_ don't just ignore that sentence fragment of the standard because you don't like it or because you profess to not understand it like Gabriel does. At least acknowledge it as a _bug_ in gcc. Linus
|
https://gcc.gnu.org/ml/gcc-patches/2001-12/msg01704.html
|
CC-MAIN-2020-05
|
refinedweb
| 733
| 71.34
|
I've been playing around with the version of the WPµ source that's used on Blogsome's servers, trying to find the exact point where the bug is that escapes apostrophes and quotes.
Basically, the XMLRPC client contacts the server, and sends the data in. According to the console, the content of the post is actually in a field called description.
Searching through the XMLRPC file I find only five references to the word description. Two of these are in functions to do with posting. Both are basically the same, one is for blogger, the other metaweblog type connections:
$post_content = apply_filters('content_save_pre', $content_struct['description']);
Now, a bit of research showed up that apply_filters is a function that allows plugins and their ilk to access the data before it gets saved to the database. Now, I'm fairly sure it's not a plugin doing this.
I also discovered that it's likely that the update to XMLRPC.php that happened was accompanied by a change to another file, that calls stripslashes(), another WP function. The XMLRPC update was, after all, a fix that removed the ability for XMLRPC calls to run unescaped code. So it makes sense that it escapes stuff.
In the short term, I discovered ecto has the ability to automatically run a script as you post: in the New Post window, make sure Options are showing, and choose the Formatting tab. (Incidentally, if you are only using double-quotes, it seems the Smarten Quotes will help, but it may mess with code).
I use a script that is like this to fix everything up:
import sys data = open(sys.argv[1]).read() data = data.replace(“'”,“'”) data = data.replace('“',”“”) open(sys.argv[1],'w').write(data)
This on it's own is not enough - I seemed to have to go into the HTML editing mode before it would work. I think ecto does it's own conversion of certain HTML entities to real characters.
This post is a test post to see how it all goes with
<pre> tags and the like.
|
http://schinckel.net/2005/10/16/
|
crawl-002
|
refinedweb
| 345
| 71.24
|
If you have an interest in Data Science, Web Development, Robotics, or IoT you must learn Python. Python has become the fastest-growing programming language due to its heavy usage and wide range of applications.
For a beginner or a person from a non-tech background, learning Python is a good choice. The syntax is like talking and writing plain English. For example, consider this syntax which shows its resemblance to the English language.
print("Hello folks")
We will use
Python3 in this tutorial as it is widely used. Most of Python's frameworks and libraries support this version.
Note: Any version above 3.5.2 supports most of the libraries and frameworks.
Index:
- Introduction
- Installation
- Python shell
- Comment
- Indentation
- Variables
- Operators
- Conditional Statements
- For Loops
- While loops
- User Input
- Typecasting
- Dictionaries
- Lists
- Tuples
- Sets
- Functions and Arguments
- Args
- keyword Arguments
- Default Arguments
- kwargs
- Scope
- Return Statement
- Lambda Expression
- List comprehension
- OOPS concepts
- Classes
- Methods
- Objects
- Constructor
- Instance attribute
- Class attributes
- Self
- Inheritance
- Super
- Multiple Inheritance
- Polymorphism
- Encapsulation
- Decorators
- Exceptions
- Package Import
- JSON Handling
Note: The beginning of this guide is geared towards beginners. If you have intermediate experience in Python, feel free to skip ahead using the links above.
Introduction:
As per Github's octoverse, Python is the second most used language by developers in 2019.
Before learning any language, it's helpful to know how that language came into existence. Well, Python was developed by Guido van Rossum, a Dutch programmer, and was released in 1991.
Python is an Interpreted language. It uses the CPython Interpreter to compile the Python code to byte code. For a beginner, you don't need to know much about CPython, but you must be aware of how Python works internally.
The philosophy behind Python is that code must be readable. It achieves this with the help of indentation. It supports many programming paradigms like Functional and Object Oriented programming. You will understand more about these as you read through the article.
The basic question that most beginners have in mind is what a language can do. Here are some of the use-cases of Python:
- Server-side development ( Django, Flask )
- Data Science ( Pytorch, Tensor-flow )
- Data analysis / Visualisation ( Matplotlib )
- Scripting ( Beautiful Soup )
- Embedded development
Note: I do not endorse any of the above-mentioned libraries or frameworks in particular. They are popular and broadly used in their respective domains.
Installation
The first step of learning any programming language is installing it. Python comes bundled with most operating systems nowadays. Use the following command in your terminal to check if Python is available:
python3 --version
You'll see the following output:
Python 3.7.0
Note that your version of Python might be different. If you have Python installed and the version is above 3.5.2 then you can skip this section.
For those who don't have Python installed, follow the steps below:
Windows User:
- Go to Python's official website.
- Click on the download button ( Download Python 3.8.2 ) [ Note: The version may differ based on when you are reading this article ]
- Go to the path where the package is downloaded and double-click the installer.
- Check the box indicating to "Add Python 3.x to PATH" and then click on "Install Now".
- Once done you'll get a prompt that "Setup was successful". Check again if python is configured properly using the above command.
- To confirm if Python is installed and configured properly, use the command
python3 --version.
Mac User:
- First install xcode from the app store.
- If you want to install Xcode using the terminal then use the following command:
xcode-select --install
- After that, we will use the brew package manager to install Python. To install and configure brew, use the following command:
/bin/bash -c "$(curl -fsSL)"
- Once brew setup is done, use the following command to update any outdated packages:
brew update
- Use the following command to install Python:
brew install python3
- To confirm if Python is installed and configured properly, use the command
python3 --version.
Linux User:
- To install Python using
apt, use the following command:
sudo apt install python3
- To install the Python using
yum, use the following command:
sudo yum install python3
- To confirm if Python is installed and configured properly, use the command
python3 --version.
Python shell:
The shell is one of the most useful tools you'll come across. The Python shell gives us the power to quickly test any concept before integrating it into our application.
Go to the terminal or command line prompt. Enter
python3 command and you'll get the following output:
➜ python3.7 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
In this tutorial, we will learn some concepts with the help of the python3 shell which you can see above. From now on, whenever I mention go to the Python shell, it means that you have to use the
python3 command.
To learn the remaining concepts we will create a file called "testing" with the extension
.py. To run this file we will use the following command:
python3 testing.py
Let's go to the Python shell. Type
10 + 12 after the
>>> mark. You'll get the output 22:
>>> 10 + 12 22
Commenting:
Comments make it easy to write code as they help us (and others) understand why a particular piece of code was written. Another awesome thing about comments is that they help improve the readability of the code.
# Stay Safe
When you add the above syntax, the Python interpreter understands that it is a comment. Everything after
# is not executed.
You may be wondering why you should use comments. Imagine you are a developer and you have been assigned to a huge project. The project has more than a thousand lines of code. To understand how everything works you'll need to go line by line and read through all the code.
What's a better solution than that? Ah-ha! Comments. Comments help us understand why a particular piece of code was written and what it returns or does. Consider it as documentation for every piece of code.
Print:
Other than debugging tools from the editor, the thing which helps developers solve problems most often is a print statement. The print statement is one of the most underrated pieces of syntax in all of programming.
So how does it help in debugging an issue? Well, consider that you have a module and you want to check the flow of execution to understand or debug it. There are two options. Either you can use a debugger or add a print statement.
It's not always possible to use a debugger. For example, if you are using the Python shell, then a debugger is not available. In such a scenario, print helps us. Another scenario is when your application is running. You can add a print statement that will display in the logs of your application and monitor them in runtime.
Python provides a inbuilt print method with the following syntax:
print("Stay safe...")
Indentation:
Another interesting part of this language is indentation. Why? Well, the answer is simple: It makes the code readable and well-formatted. It is compulsory in Python to follow the rules of indentation. If proper indentation is not followed you'll get the following error:
IndentationError: unexpected indent
See, even the errors in Python are so readable and easy to understand. At the start, you may be annoyed by the compulsion of indentation. But with the time you'll understand that indentation is a developer's friend.
Variables:
As the name implies, a variable is something that can change. A variable is a way of referring to a memory location used by a computer program.
Well in most programming languages you need to assign the type to a variable. But in Python, you don’t need to. For example, to declare an integer in C, the following syntax is used:
int num = 5;. In Python it's
num = 5 .
Go to the Python shell and perform the operation step by step:
Integer: Numerical values that can be positive, negative, or zero without a decimal point.
>>> num = 5 >>> print(num) 5 >>> type(num) <class 'int'>
As you can see here we have declared a
num variable and assigned 5 as a value. Python's inbuilt
type method can be used to check the type of variable. When we check the type of
num we see the output
<class 'int'>. For now, just focus on the
int in that output.
int represents an integer.
Float: Similar an integer but with one slight difference – floats are a numerical value with a decimal place.
>>> num = 5.0 >>> print(num) 5.0 >>> type(num) <class 'float'>
Here we have assigned a number with a single decimal to the
num. When we check the type of
num we can see it is
float.
String: A formation of characters or integers. They can be represented using double or single quotes.
>>>>> print(greet) Hello user >>> type(greet) <class 'str'>
Here we have assigned a string to
greet. The type of greet is a string as you can see from the output.
Boolean: A binary operator with a True or False value.
>>> is_available = True >>> print(is_available) True >>> type(is_available) <class 'bool'>
Here we have assigned a True value to
is_available. The type of this variable is boolean. You can only assign True or False. Remember T and F should be capital or it will give an error as follows:
>>> is_available = true Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined
NoneType: This is used when we don't have the value of the variable.
>>> num = None >>> print(num) None >>> type(num) <class 'NoneType'>
Operators:
Take a look at the image below to see all the arithmetic operators available in Python:
Let's go over the operators one by one.
Arithmetic operators
These include addition, subtraction, deletion, exponentiation, modulus, and floor division. Also the shorthand syntax for some operators.
First, we will declare two variables,
a and
b.
>>> a = 6 # Assignment >>> b = 2
Let's try our basic arithmetic operations:
>>> a + b # Addition 8 >>> a - b # Subtraction 4 >>> a * b # Multiplication 12 >>> a / b # Division 3.0 >>> a ** b # Exponentiation 36
To test for other arithmetic operations let's change the value of
a and
b.
>>> a = 7 >>> b = 3 >>> a % b # Modulus 1 >>> a // b # Floor division 2
Shorthand arithmetic operations are also available in Python. Refer back to the image above to test them out. To print the output of the shorthand operations use the
Comparison operators
These include equal to, greater than, and less than.
>>> a = 5 # Assign >>> b = 2 # Assign >>> a > b # Greater than True >>> a < b # less then False >>> a == b # Equal to False >>> a >= 5 # Greater than or equal to True >>> b <= 1 # Less than or equal to False
Logical operators
These operators include not, and, & or.
>>> a = 10 >>> b = 2 >>> a == 2 and b == 10 # and False >>> a == 10 or b == 10 # or True >>> not(a == 10) # not False >>> not(a == 2) True
Conditional Statements:
As the name suggests, conditional statements are used to evaluate if a condition is true or false.
Many times when you are developing an application you need to check a certain condition and do different things depending on the outcome. In such scenarios conditional statements are useful. If, elif and else are the conditional statements used in Python.
We can compare variables, check if the variable has any value or if it's a boolean, then check if it's true or false. Go to the Python shell and perform the operation step by step:
Condition Number 1: We have an integer and 3 conditions here. The first one is the
if condition. It checks if the number is equal to 10.
The second one is the
elif condition. Here we are checking if the number is less than 10.
The last condition is
else. This condition executes when none of the above conditions match.
>>> number = 5 >>> if number == 10: ... print("Number is 10") ... elif number < 10: ... print("Number is less than 10") ... else: ... print("Number is more than 10") ...
Output:
Number is less than 10
Note: It is not compulsory to check that two conditions are equal in the
if condition. You can do it in the
elif also.
Condition Number 2: We have a boolean and 2 conditions here. Have you noticed how we are checking if the condition is true? If
is_available, then print "Yes it is available", else print "Not available".
>>> is_available = True >>> if is_available: ... print("Yes it is available") ... else: ... print("Not available") ...
Output:
Yes it is available
Condition Number 3: Here we have reversed condition number 2 with the help of the not operator.
>>> is_available = True >>> if not is_available: ... print("Not available") ... else: ... print("Yes it is available") ...
Output:
Yes it is available
Condition Number 4: Here we are declaring the data as None and checking if the data is available or not.
>>> data = None >>> if data: ... print("data is not none") ... else: ... print("data is none") ...
Output:
data is none
Condition Number 5: You can also use an inline if in Python. The syntax to achieve this is the following:
>>> num_a = 10 >>> num_b = 5 >>> if num_a > num_b: print("num_a is greater than num_b") ...
Output:
num_a is greater than num_b
Condition Number 6: You can also use an inline if else in Python. The syntax to achieve this is the following:
expression_if_true if condition else expression_if_false
Example:
>>> num = 5 >>> print("Number is five") if num == 5 else print("Number is not five")
Output:
Number is five
Conditional Number 7: You can also use nested if-else statements. The syntax to achieve this is the following:
>>> num = 25 >>> if num > 10: ... print("Number is greater than 10") ... if num > 20: ... print("Number is greater than 20") ... if num > 30: ... print("Number is greater than 30") ... else: ... print("Number is smaller than 10") ...
Output:
Number is greater than 10 Number is greater than 20
Condition Number 8: You can also use the
and operator in a conditional statement. It states if condition1 and condition2 both are true then execute it.
>>> num = 10 >>> if num > 5 and num < 15: ... print(num) ... else: ... print("Number may be small than 5 or larger than 15") ...
Output:
10
As our number is between 5 and 15 we get the output of 10.
Condition Number 9: You can also use the
or operator in a conditional statement. It states that if either condition1 or condition2 is true then execute it.
>>> num = 10 >>> if num > 5 or num < 7: ... print(num) ...
Output:
10
Are you confused because the value of
num is 10 and our second condition states that
num is less than 7? So why do we get the output as 10? It's because of the
or condition. As one of the conditions matches, it will execute it.
For Loops:
Another useful method in any programming language is an iterator. If you have to implement something multiple times, what will you do?
print("Hello") print("Hello") print("Hello")
Well, that's one way to do it. But imagine you have to do it a hundred or a thousand times. Well, that's a lot of print statements we have to write. There's a better way called iterators or loops. We can either use a
for or
while loop.
Here we are using the range method. It specifies the range until which the loop should be repeated. By default, the starting point is 0.
>>> for i in range(3): ... print("Hello") ...
Output:
Hello Hello Hello
You can also specify the range in this way
range(1,3).
>>> for i in range(1,3): ... print("Hello") ...
Output:
Hello Hello
"Hello" is only printed two times as we have specified the range here. Think of the range as
Number on right - Number on left.
Well, you can also add an else statement in the for loop.
>>> for i in range(3): ... print("Hello") ... else: ... print("Finished")
Output:
Hello Hello Hello Finished
See our loop iterated 3 times ( 3 - 0 ) and once that is done it executed the else statement.
We can also nest a for loop inside another for loop.
>>> for i in range(3): ... for j in range(2): ... print("Inner loop") ... print("Outer loop") ...
Output:
Inner loop Inner loop Outer loop Inner loop Inner loop Outer loop Inner loop Inner loop Outer loop
As you can see the inner loop print statement executed two times. After that outer loop print statement executed. Again the inner loop executed two times. So what is happening here? If you are confused then consider this to solve it:
- Our Interpreter comes and sees that there is a
forloop. It goes down again and checks there is another
forloop.
- So now it will execute the inner
forloop two times and exit. Once it's finished it knows that outer for loop has instructed it to repeat two more times.
- It starts again and sees the inner for loop and repeats.
Well, you can also choose to pass a certain
for loop condition. What does pass mean here? Well whenever that for loop will occur and the Interpreter sees the
pass statement it won't execute it and will move to the next line.
>>> for i in range(3): ... pass ...
You will not get any output on the shell.
While loops:
Another loop or iterator available in Python is the
while loop. We can achieve some of the same results with the help of a
while loop as we achieved with the
for loop.
>>> i = 0 >>> while i < 5: ... print("Number", i) ... i += 1 ...
Output:
Number 0 Number 1 Number 2 Number 3 Number 4
Remember whenever you use a while loop it's important that you add an increment statement or a statement that will end the while loop at some point. If not then the while loop will execute forever.
Another option is to add a
break statement in a
while loop. This will break the loop.
>>> i = 0 >>> while i < 5: ... if i == 4: ... break ... print("Number", i) ... i += 1 ...
Output:
Number 0 Number 1 Number 2 Number 3
Here we are breaking the
while loop if we find the value of
i to be 4.
Another option is to add an
else statement in
while loop. The statement will be executed after the while loop is completed.
>>> i = 0 >>> while i < 5: ... print("Number", i) ... i += 1 ... else: ... print("Number is greater than 4") ...
Output:
Number 0 Number 1 Number 2 Number 3 Number 4 Number is greater than 4
The
continue statement can be used to skip the current execution and to proceed to the next.
>>> i = 0 >>> while i < 6: ... i += 1 ... if i == 2: ... continue ... print("number", i) ...
Output:
number 1 number 3 number 4 number 5 number 6
User Input:
Imagine you are building a command-line application. Now you have to take the user input and act accordingly. To do that you can use Python's inbuilt
input method.
The syntax to achieve this is as follows:
variable = input(".....")
Example:
>>> name = input("Enter your name: ") Enter your name: Sharvin
When you use the
input method and press enter, you'll be prompted with the text that you enter in the
input method. Let's check if our assignment is working or not:
>>> print(name) Sharvin
There it is! It is working perfectly. Here
Sharvin is of the type string.
>>> type(name) <class 'str'>
Let's try one more example where we will assign an integer rather than a string and check the type.
>>> date = input("Today's date: ") Today's date: 12 >>> type(date) <class 'str'>
Are you confused? We entered an integer 12 and it's still giving us its type as a string. It's not a bug. It's how input is intended to work. To convert the string to integer we will use typecasting.
Typecasting:
We saw that the
input method returns a string for the integer also. Now if we want to compare this output with another integer then we need a way to convert it back to an integer.
>>> date_to_int = int(date) >>> type(date_to_int) <class 'int'>
Here we took the date that we have declared above in the User input section and converted it into the integer using the Python's inbuilt
int method. This is called typecasting.
Basically you can do the following conversion with the help of typecasting:
- integer to string:
str()
- string to integer:
int()
- integer to float:
float()
Note: Conversion from float to integer is also possible.
>>> type(date) <class 'str'> # Converting from string to float >>> date_to_float = float(date) >>> type(date_to_float) <class 'float'> # Converting from float to string >>> date_to_string = str(date_to_float) >>> type(date_to_string) <class 'str'> # Converting from float to integer >>> date_to_int = int(date_to_float) >>> type(date_to_int) <class 'int'>
Dictionaries:
Imagine you want to store some user details. So how can you store these details? Yes, we can use variable to store them as follows:
>>>>>>> profession = "Developer"
To access this value we can do the following:
>>> print(fname) Sharvin
But is this an elegant and optimized way to access it? The answer is no. To make it more friendly, let's store the data in a key-value dictionary.
What is a dictionary? A dictionary is a collection that is unordered and mutable ( i.e. it can be updated ).
Following is the format of the dictionary:
data = { "key" : "value" }
Let's understand the dictionary further by an example:
>>> user_details = { ... "fname": "Sharvin", ... "lname": "Shah", ... "profession": "Developer" ... }
How to access a value in a dictionary
We can access the value inside a dictionary in two ways. We will take a look at both and then debug them to find out which is better.
Method 1: To access the value of
fname key from
user_details dictionary we can use the following syntax:
>>> user_details["fname"] 'Sharvin'
Method 2: We can also access the value of
fname key from
user_details dictionary using
get.
>>> user_details.get("fname") 'Sharvin'
I know method 1 looks easier to understand. The problem with it occurs when we try to access the data that is not available in our dictionary.
>>> user_details["age"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'age'
We get a KeyError which indicates that the key is not available. Let's try the same scenario with method 2.
>>> user_details.get("age")
We do not get anything printed in our console. Let's debug it further to know why this happened. Assign a variable age to our
get operation and we will print it in our console.
>>> age = user_details.get("age") >>> print(age) None
So when
get doesn't find the key it sets the value to None. Because of this, we do not get any error. Now you may be wondering which one is right. Most of the time using method 2 makes more sense, but for some strict checking conditions, we need to use method 1.
How to check if a key exists
You may be wondering how to check if the dictionary has a particular key or not in it. Python provides the built-in method
keys() to solve this issue.
>>> if "age" in user_details.keys(): ... print("Yes it is present") ... else: ... print("Not present") ...
We will get the following output:
Not present
What if we want to check if the dictionary is empty or not? To understand this let's declare an empty dictionary as follows:
>>> user_details = {}
When we use if-else on a dictionary directly it either returns true if data is present or false if empty.
>>> if user_details: ... print("Not empty") ... else: ... print("Empty") ...
Output:
Empty
We can also use Python's inbuilt method
bool to check if the dictionary is empty or not. Remember bool returns False if the dictionary is empty and True if it is filled.
>>> bool(user_details) False >>> user_details = { ... "fname" : "Sharvin" ... } >>> bool(user_details) True
How to update the value of an existing key
So now we know how to get a particular key and find if it exists – but how do you update it in the dictionary?
Declare a dictionary as follows:
>>> user_details = { ... "fname":"Sharvin", ... "lname": "Shah", ... "profession": "Developer" ... }
To update the value use the following syntax:
>>> user_details["profession"] = "Software Developer" >>> print(user_details) {'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}
Updating a value of key in dictionary is same as assigning a value to the variable.
How to add a key-value pair
The next question is how to add a new value to the dictionary? Let's add an
age key with a value of 100.
>>> user_details["age"] = "100" >>> print(user_details) {'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer', 'age': '100'}
As you can see a new key-value is added in our dictionary.
How to remove a key-value pair
To remove a key-value from the dictionary, Python provides an inbuilt method called
pop.
>>> user_details.pop("age") '100' >>> print(user_details) {'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}
This removes the
age key-value pair from the
user_details dictionary. We can also use a
del operator to delete the value.
>>> del user_details["age"] >>> print(user_details) {'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}
The
del method can also be used to delete complete dictionary. Use the following syntax to delete complete dictionary
del user_details.
How to copy a dictionary
A dictionary cannot be copied in a traditional way. For example, you cannot copy value of
dictA to
dictB as follows:
dictA = dictB
To copy the values you need to use the
copy method.
>>> dictB = user_details.copy() >>> print(dictB) {'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}
Lists:
Imagine you have a bunch of data that is not labeled. In other words, each piece of data doesn't have a key that defines it. So how will you store it? Lists to the rescue. They are defined as follows:
data = [ 1, 5, "xyz", True ]
A list is a collection of random, ordered, and mutable data (i.e., it can be updated).
How to access list elements
Let's try to access the first element:
>>> data[1] 5
Wait what happened here? We are trying to access the first element but we are getting the second element. Why?
Indexing of the list begins from zero. So what do I mean by this? The indexing of the position of the elements begins from zero. The syntax to access an element is as follows:
list[position_in_list]
To access the first element we need to access it as follows:
>>> data[0] 1
You can also specify a range to access the element between those positions.
>>> data[2:4] ['xyz', True]
Here, the first value represents the start while the last value represents the position until which we want the value.
How to add an item to a list
To add an item in the list we need to use the append method provided by python.
>>> data.append("Hello") >>> data [1, 5, 'abc', True, 'Hello']
How to change the value of an item
To change the value of an item, use the following syntax:
>>> data[2] = "abc" >>> data [1, 5, 'abc', True]
How to remove an item from a list
To remove an item from a list we can use the Python's inbuilt
remove method.
>>> data.remove("Hello") >>> data [1, 5, 'abc', True]
How to loop through a list
We can also loop through the list to find a certain element and operate on it.
>>> for i in data: ... print(i) ...
Output:
1 5 abc True
How to check if an item exists or not
To check if a particular item exists or not in list we can use if loop as follows:
>>> if 'abc' in data: ... print("yess..") ... yess..
How to copy list data
To copy list data from one list to another we need to use
copy method.
>>> List2 = data.copy() >>> List2 [1, 5, 'abc', True]
How to check the length of a list
We can also check the length of list using Python's inbuilt
len method.
>>> len(data) 4
How to join two lists
To join two list we can use the
+ operator.
>>> list1 = [1, 4, 6, "hello"] >>> list2 = [2, 8, "bye"] >>> list1 + list2 [1, 4, 6, 'hello', 2, 8, 'bye']
What happens if we try to access a element position which is not available in the list? We get a
list index out of range error in such a condition.
>>> list1[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
Tuples:
The tuple is a data type which is ordered and immutable (i.e. data cannot be changed).
Let's create a tuple:
>>> data = ( 1, 3 , 5, "bye") >>> data (1, 3, 5, 'bye')
How to access a tuple element
We can access elements in the tuple the same way as we access them in a list:
>>> data[3] 'bye'
We can access the index range as follows:
>>> data[2:4] (5, 'bye')
How to change a tuple's value
If you are thinking wait – how can we change the value of tuple, then you are right my friend. We cannot change the value of tuple as it is immutable. We get the following error if we try to change the value of a tuple:
>>> data[1] = 8 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
There's a workaround available to change the value of a tuple:
>>> data = ( 1, 3 , 5, "bye") >>> data_two = list(data) # Convert data to list >>> data_two[1] = 8 # Update value as list is mutable >>> data = tuple(data_two) # Convert again to tuple >>> data (1, 8, 5, 'bye')
All other methods that we have seen in the list are applicable for the tuple also.
[ Note: Once a tuple is created a new value cannot be added in it. ].
Sets:
Sets are another data type in Python which are unordered and unindexed. Sets are declared as follows:
>>> data = { "hello", "bye", 10, 15 } >>> data {10, 15, 'hello', 'bye'}
How to access a value
As sets are unindexed we cannot directly access the value in a set. Thus to access the value in the set you need to use a for loop.
>>> for i in data: ... print(i) ... 10 15 hello bye
How to change a value
Once the set is created, values cannot be changed.
How to add an item
To add an item to the set python provides an inbuilt method called
add.
>>> data.add("test") >>> data {10, 'bye', 'hello', 15, 'test'}
How to check length
To check the length of the set we use the
len method.
>>> len(data) 5
How to remove an item
To remove an item use the
remove method:
>>> data.remove("test") >>> data {10, 'bye', 'hello', 15}
Functions and Arguments:
Functions are a handy way to declare an operation that we want to perform. With the help of functions, you can separate logic according to the operation.
Functions are a block of code that helps us in the reusability of the repetitive logic. Functions can be both inbuilt and user-defined.
To declare a function we use the
def keyword. Following is the syntax of the functions:
>>> def hello_world(): ... print("Hello world") ...
Here we are declaring a function which, when called, prints a "Hello world" statement. To call a function we use the following syntax:
>>> hello_world()
We will get the following output:
Hello world
Remember that the
() brackets in a function call means to execute it. Remove those round brackets and try the call again.
>>> hello_world
You'll get the following output:
<function hello_world at 0x1083eb510>
When we remove the round brackets from the function call then it gives us a function reference. Here above as you can see the reference of
function hello_world points to this memory address
0x1083eb510.
Consider you have to perform an addition operation. You can do it by declaring
a and
b and then performing the addition.
>>> a = 5 >>> b = 10 >>> a + b 15
This is one way to go. But now consider that the value of
a and
b have changed and you need to do it again.
>>> a = 5 >>> b = 10 >>> a + b 15 >>> a = 2 >>> b = 11 >>> a + b 13
This still looks doable. Now imagine we need to add a set of two numbers a hundred times. The numbers within the set are different for every calculation. That's a lot to do. Don't worry – we have a function at our disposal to solve this issue.
>>> def add(a,b): ... print(a+b) ...
Here we are adding
a and
b as a compulsory argument to the
add function. To call this function we will use the following syntax:
>>> add(10,5)
Output:
15
See how easy it is to define a function and use it? So what happens if we don't pass an argument?
>>> add() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: add() missing 2 required positional arguments: 'a' and 'b'
Python throws a TypeError and informs us that the function requires two arguments.
Can you guess what will happen if we pass a third argument?
>>> add(10,5,1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: add() takes 2 positional arguments but 3 were given
Well, Python will inform us that we have passed 3 arguments but there are only 2 positional arguments.
So what can we do when we don't know how many arguments a function can take? To solve this issue we use args and kwargs.
Args:
When you don't know how many arguments will be passed to the function, use args and kwargs (kwargs are discussed below).
To pass n number of arguments to a function we use args. We add a
* in front of the argument.
Remember when you attach a
*in front, you will be receiving a tuple of arguments.
>>> def add(*num): ... print(num) ...
Here
*num is an instance of args. Now when we call the function
add we can pass in n number of arguments and it won't throw a
TypeError.
>>> add(1,2,3) (1, 2, 3) >>> add(1,2,3,4) (1, 2, 3, 4)
Now to perform the addition operation we will use the Python's builtin function
sum
>>> def add(*num): ... print(sum(num)) ...
Now when we call the add function we will get the following output:
>>> add(1,2,3) # Function call 6 >>> add(1,2,3,4) # Function call 10
Keyword Arguments:
There are times when we don't know the order of the arguments that will be passed to our function when it's called. In such a scenario we use keyword arguments because you can pass them in any order in your call and our function will know the value. Take a look at this example:
>>> def user_details(username, age): ... print("Username is", username) ... print("Age is", age) ...
Let's call this function as follows:
>>> user_details("Sharvin", 100)
We will get the following output:
Username is Sharvin Age is 100
Well this looks correct, but imagine if we called our function in this way:
>>> user_details(100, "Sharvin")
We will get the following output:
Username is 100 Age is Sharvin
This does not look right. What happened is
username took the value of 100 while
age took the value of "Sharvin". In scenarios like this where we don't know the order of arguments we can use keyword arguments when calling the function:
>>> user_details(age=100, username="Sharvin")
Output:
Username is Sharvin Age is 100
Default Argument:
Suppose there is a condition where we are not sure if a particular argument will get a value or not when the function is called. In such a scenario we can use Default arguments as follows:
>>> def user_details(username, age = None): ... print("Username is", username) ... print("Age is", age) ...
Here we are assigning a
None to our age argument. If we don't pass a second argument while calling the function it will take None as a default value.
Let's call the function:
>>> user_details("Sharvin")
Output:
Username is Sharvin Age is None
If we pass in the second argument it will override None and use it as the value.
>>> user_details("Sharvin", 200) Username is Sharvin Age is 200
But what will happen if we assign the first argument in our function as default and the second as a compulsory argument? Go to the Python shell and try this out:
>>> def user_details(username=None, age): ... print("Username is", username) ... print("Age is", age) ...
You'll get the following error:
File "<stdin>", line 1 SyntaxError: non-default argument follows default argument
Remember: All compulsory arguments must be declared first and then the default argument must be declared.
kwargs:
There can be a situation where you don't know how many keyword arguments will be passed into the function. In such a scenario we can use Kwargs.
To use kwargs we put
** in front of the argument.
Remember: When you attach a
**in front, you will be receiving a dictionary of arguments.
Let's understand this by example. We will declare a function which accepts username as it's argument with
** in front of it.
>>> def user(**username): ... print(username) ...
When we call the
user function as follows we will receive a dictionary.
>>> user(username1="xyz",username2="abc")
Output:
{'username1': 'xyz', 'username2': 'abc'}
So what's happening here? It looks the same as args, right?
No, it's not. In args, you cannot access a particular value by its name as it is in the form of a tuple. Here we get the data in the form of a dictionary so we can easily access the value.
Consider this example:
>>> def user(**user_details): ... print(user_details['username']) ...
Let's call our function:
>>> user(username="Sharvin",age="1000")
And you'll get the following output:
Sharvin
Scope:
A scope defines where a variable or function is available. There are two types of scope in Python: Global and Local.
Global Scope
A variable or function created in the main body of Python code is called a global variable or function and is part of the global scope. For example:
>>>>> def testing(): ... print(greet) ... >>> testing() Hello world
Here the variable
greet is available globally because it is declared in the body of the program.
Local Scope
A variable or function created inside a function is called a local variable or function and is part of the local scope:
>>> def testing(): ... greet = "Hello world" ... print(greet) ... >>> testing() Hello world
Here
greet is created inside the testing function and is only available there. Let's try to access it in our main body and see what happens:
>>> print(greet) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'greet' is not defined
Remember: Restart the Python console by pressing ctrl + d and starting the shell again by using the
python3 command before testing the code above. The first example has you declare the
greet variable in the global scope meaning it will still be available in memory when you run the second example.
As
greet is not available globally we get the error that it is not defined.
Return Statement:
Until now our functions are pretty simple. They are receiving data, processing it, and printing them. But in the real world, you need a function to return output so that it can be used in different operations.
To achieve this, return statements are used. Remember, return statements are only part of functions and methods. The syntax for the return statement is quite easy.
>>> def add(a, b): ... return a + b ... >>> add(1,3) 4
Instead of printing our addition, we are returning the output. The value of the returned output can also be stored in a variable.
>>> sum = add(5,10) >>> print(sum) 15
Lambda Expression:
Consider a situation where you don't want to perform much computation in a function. In such a situation writing a full-fledged function doesn't make sense. To solve this we use a lambda expression or lambda function.
So what is a lambda expression? It is an anonymous function and they are restricted to a single expression. The lambda expression can take n number of arguments.
The syntax for lambda expression is:
variable = lambda arguments: operation
Let's understand it more by example:
>>> sum = lambda a: a + 10
Here we have declared a variable
sum which we are using to call the lambda function.
a represents the argument that is passed to that function.
Let's call our function:
>>> x(5) 15
List comprehension:
Consider a situation where you want a list of squares. Normally you'll declare a
squares list and then in a for loop you'll square out the numbers.
>>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Well this is doable, but we can achieve this in a single line with the help of list comprehension.
There are two ways to achieve this. Let's understand both of them.
>>> squares = list(map(lambda x: x**2, range(10))) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Here we are using
list constructor to build a list and inside that lambda function which squares out the number. Another way to achieve the same result is as follows:
>>> squares = list(x**2 for x in range(10)) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
I prefer this way because it is easier to more concise and easier to understand.
What about when we have a condition where we want a set of two numbers that are the same? Well, we need to write two for loops and one if loop.
Let's see how that will look:
>>> num_list = [] >>> for i in range(10): ... for j in range(10): ... if i == j: ... num_list.append((i,j)) ... >>> num_list [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
That's a lot of work. And in terms of readability it's hard to understand.
Let's use list comprehension to achieve the same result.
>>> num_list = list((i,j) for i in range(10) for j in range(10) if i == j) >>> num_list [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
See how easy it is to get the same output in a single expression? Well, that's the power of list comprehension.
OOP concepts:
Python is a multi-paradigm programming language. It means Python can use different approaches to solve a problem. One of the paradigms is procedural or functional programming. It structures the code like a recipe – a set of steps in the form of functions and code blocks.
Another approach to solving the problem is by creating classes and objects. This is known as object-oriented oriented programming. An object is a collection of data (variables) and methods that act on those data. And classes are a blueprint for each object.
The important thing to understand in object-oriented programming is that objects are at the center of the paradigm – they not only represent the data but also the structure of the program.
You can choose the paradigm that best suits the problem at hand, mix different paradigms in one program, and/or switch from one paradigm to another as your program evolves.
Advantages of object oriented programming
- Inheritance: This is one of the most useful concepts in OOP. It specifies that the child object will have all the properties and behavior of the parent object. Thus Inheritance allows us to define a class that inherits all the methods and properties from another class.
- Polymorphism: To understand polymorphism let’s divide the word into two parts. The first part "poly" means many and "morph" means to form or shape. Thus polymorphism means one task can be performed in many different ways.
For example, you have a class
animal, and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.
Polymorphism means the same function name or method name being used for different types.
- Encapsulation: In object-oriented programming you can restrict access to methods and variables – we can make the methods and variables private. This can prevent the data from being modified by accident and is known as encapsulation.
First, we will understand classes, objects, and constructors. Then after that, we will look into the above properties again. If you already know about classes, objects, and constructors, feel free to skip ahead.
Classes:
There are primitive data structures available in Python, for example, numbers, strings, and lists. These can all be used for simple representations like name, place, cost, and so on.
But what if we have more complex data? If there is a pattern in the repetition of the properties of that data, what can we do?
Suppose we have 100 different animals. Every animal has a name, age, legs, etc. What if we want to add other properties to each animal, or one more animal gets added to that list? To manage such a complex scenario we need classes.
According to the official Python documentation:.
Syntax of class:
class ClassName: <expression-1> . . . <expression-N>
We use
class keyword to define a class. We will define a
class Car.
class Car: pass
Methods:
Methods look the same as functions. The only difference is that methods are dependent on an object. A function can be invoked by name while methods need to be invoked by using their class reference. They are defined inside the class.
In our example, let's create two methods. One is an engine and another is a wheel. These two methods define the parts available in our car.
The below program will give us a better idea of classes:
>>> class Car: ... def engine(self): ... print("Engine") ... >>> Car().engine() Engine
Here we are calling the
engine method by using the
Car() reference.
To summarize, the class provides a blueprint of what should be defined but it does not provide any real content. The
Car class above defines the engine but it will not state what a specific car’s engine is. It is specified by the object.
Objects:
The object is an instance of the class. Let’s consider the above example of a car. Here Car is our
class and
toyota is the
object of the car. We can create multiple copies of the object. Every object must be defined using the class.
The syntax for creating an object is:
toyota = Car()
Let’s consider our
Car example to understand objects a bit better:
class Car: def engine(self): print("Engine") def wheel(self): print("Wheel") toyota = Car()
The above
toyota = Car() is a class object. Class objects support two kinds of operations: attribute references and instantiation.
Class instantiation uses function notation. The instantiation operation (“calling” a class object) creates an empty object.
Now we can call different methods from our class
Car using the object
toyota that we have created. let’s call the method
engine and
wheel.
Open your editor and create a file named
mycar.py. In that file copy the code below:
class Car: def engine(self): print("Engine") def wheel(self): print("Wheel") if __name__ == "__main__": toyota = Car() toyota.engine() toyota.wheel()
Save the above code. Now let's take a closer look at our program.
Here we are creating a
toyota object with the help of
Car class. The
toyota.engine() is a method object. What exactly happens when a method object is called?
In the call
toyota.engine() doesn't take any argument but if you see the method declaration we can see that it takes a
self argument.
You may be confused about why it is not throwing an error. Well whenever we use a method object, the call
toyota.engine() is converted to
Car.engine(toyota). We will understand more about the self in the upcoming section.
Run the program using the following command.
python mycar.py
You'll get the following output:
Engine Wheel
Constructor:
The
__init__ method is the constructor method in Python. The constructor method is used to initialize the data.
Go to the Python shell and enter this example:
>>> class Car(): ... def __init__(self): ... print("Hello I am the constructor method.") ...
When we will call our class we will get the following output:
>>> toyota = Car() Hello I am the constructor method.
Note: You will never have to call the init() method – it gets called automatically when you create a class instance.
Instance attributes:
All the classes have objects and all the objects have attributes. Attributes are the properties. We use
__init__() method to specify an object’s initial attribute.
Let’s consider our car example:
class Car(): def __init__(self, model): self.model = model #instance attribute
In our example, each
Car() has a specific model. Thus instance attributes are unique data to each instance.
Class attributes:
We saw that instance attributes are specific to each object but class attributes are the same for all the instances. Let us look at the example of the car with the help of class attributes.
class Car(): no_of_wheels = 4 #class attribute
So each car can have different models but all the cars will have only 4 wheels.
Self:
Now let’s understand what
self means and how we use it in object-oriented programming.
self represents the instance of a class. By using the
self keyword we can access the data initialized in the constructor and methods of a class.
Let's look at an example of how
self can be used. Let’s create a method named
brand under our class
Car.
Inside that
__init__ method, we will pass a model by passing our car’s model name when we are instantiating our object. This name can be accessed anywhere in the class, for example
self.model in our case.
Go to the file named
mycar.py and replace old code with this code:
class Car(): def __init__(self, model): self.model = model def brand(self): print("The brand is", self.model) if __name__ == "__main__": car = Car("Bmw") car.brand()
Now when we run our above program using the following command:
python mycar.py
We will get the following output:
The brand is Bmw
Note:
self is a convention and not a real Python keyword.
self is an argument in a method and we can use another name in place of it. But it is recommended to use
self because it increases the readability of your code.
Inheritance:
Inheritance refers to when a class inherits the property of another class.
The class from which properties are inherited is called the base class. The class which inherits the property of another class is called the derived class.
Inheritance can be defined as a parent and child relationship. The child inherits the properties of the parent. Thus making the child a derived class while parent is a base class. Here the term property refers to attributes and methods.
The syntax for a derived class definition looks like this:
class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>
It’s important to note that child classes override or extend the attributes and behaviors of parent class methods. This is to say that child classes inherit all of the the attributes and behaviors of their parents – but they're also able to specify different behavior to follow.
The most basic type of class is an object, which generally all other classes inherit as their parent. Let’s modify our previous example to understand how inheritance works.
We will create a base class named
vehicle:
class Vehicle: def __init__(self, name): self.name = name def getName(self): return self.name
We have created a class
Vehicle and instantiated a constructor with
self.name which we are using in
getName method. Whenever this method will be called, it will return the
name that has been passed when an object is instantiated for that class.
Now let’s create a child class
Car:
class Vehicle: def __init__(self, name): self.name = name def getName(self): return self.name class Car(Vehicle): pass
Car is a child class of
Vehicle. It inherits all the method and attributes of parent class.
Now let’s use methods and attribute from the
Vehicle class in our child class
Car.
class Vehicle: def __init__(self, name, color='silver'): self.name = name self.color = color def get_name(self): return self.name def get_color(self): return self.color class Car(Vehicle): pass audi = Car("Audi r8") print("The name of our car is", audi.get_name(), "and color is", audi.get_color())
Let's understand what we have done here.
We have declared a class named
Vehicle with a constructor that takes name as an argument while color has a default argument.
We have two methods inside it.
get_name returns name while
get_color returns the color. We have instantiated an object and passed the car name.
One thing you'll notice here that we are using base class methods in our child class declaration.
Run the above program using the following command:
python mycar.py
Output:
The name of our car is Audi r8 and color is silver
We can also override a parent method or attribute. In the above example, we have defined our vehicle color has silver. But what if the color of our car is black?
Now for every child class, we can’t make changes in the parent class. There comes the overriding functionality.
class Vehicle: def __init__(self, name, color='silver'): self.name = name self.color = color def get_name(self): return self.name def get_color(self): return self.color class Car(Vehicle): def get_color(self): self.color = 'black' return self.color audi = Car("Audi r8") print("The name of our car is", audi.get_name(), "and color is", audi.get_color()
As you can see in the above program, I have not instantiated a constructor. The reason behind this is that our child class
Car is only using attributes from the
Vehicle class and it is already inheriting them. So in such a scenario, there is no need to re-instantiate these attributes.
Now when we run the above program we will get the following output:
The name of our car is Audi r8 and color is black
Super:
super() returns a temporary object of the superclass that then allows us to call that superclass’s methods.
Calling the previously built methods with
super() saves us from needing to rewrite those methods in our subclass, and allows us to swap out superclasses with minimal code changes. Thus
super extends the functionality of the inherited method.
Let’s extend our car example using
super(). We will instantiate a constructor with
brand_name and
color in the parent class,
Vehicle. Now we will call this constructor from our child class (
Car) using
super. We will create a
get_description method which is returning
self.model from
Car class and
self.brand_name,
self.color from the
Vehicle class.
class Vehicle: def __init__(self, brand_name, color): self.brand_name = brand_name self.color = color def get_brand_name(self): return self.brand_name class Car(Vehicle): def __init__(self, brand_name, model, color): super().__init__(brand_name, color) self.model = model def get_description(self): return "Car Name: " + self.get_brand_name() + self.model + " Color:" + self.color c = Car("Audi ", "r8", " Red") print("Car description:", c.get_description()) print("Brand name:", c.get_brand_name())
When we run the above program we get following output:
Car description: Car Name: Audi r8 Color: Red Brand name: Audi
Multiple Inheritance:
When a class inherits the method and attributes from multiple parent class then it is called multiple inheritance. This allows us to use the property from multiple base classes or parent classes in a derived or child class.
The general syntax of multiple Inheritance is as follows:
class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>
Let’s extend our vehicle example using the multiple inheritance property. Here in this example, we will create 3 classes i.e.
Vehicle,
Cost and
Car
The classes
Vehicle and
Cost will be the Parent class. A
Vehicle class represents the general property while the
Cost class represents its pricing.
As
Car has a general property and cost will have two parent classes. Thus we will inherit multiple parent classes.
class Vehicle: def __init__(self, brand_name): self.brand_name = brand_name def get_brand_name(self): return self.brand_name class Cost: def __init__(self, cost): self.cost = cost def get_cost(self): return self.cost class Car(Vehicle, Cost): def __init__(self, brand_name, model, cost): self.model = model Vehicle.__init__(self, brand_name) Cost.__init__(self, cost) def get_description(self): return self.get_brand_name() + self.model + " is the car " + "and it's cost is " + self.get_cost() c = Car("Audi ", "r8", "2 cr") print("Car description:", c.get_description())
Here you will find one thing in the above program that is different from all the other programs in this tutorial. I have used
Vehicle.__init__(self, brand_name) in the constructor of
Car class. This is one way of calling attributes from the parent class. Another was is
super which I have explained above.
When we run the above program we will get the following output:
Car description: Audi r8 is the car and it's cost is 2 cr
Though it can be used effectively, multiple inheritance should be done with care so that our programs do not become ambiguous and difficult for other programmers to understand.
Polymorphism:
The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.
Let’s extend our car program using polymorphism. We will create two classes,
Car and
Bike. Both the classes have common method or function, but they are printing different data. The program is pretty self-explanatory:
class Car: def company(self): print("Car belongs to Audi company.") def model(self): print("The Model is R8.") def color(self): print("The color is silver.") class Bike: def company(self): print("Bike belongs to pulsar company.") def model(self): print("The Model is dominar.") def color(self): print("The color is black.") def func(obj): obj.company() obj.model() obj.color() car = Car() bike = Bike() func(car) func(bike)
When we run the above code we will get the following output:
Car belongs to Audi company. The Model is R8. The color is silver. Bike belongs to pulsar company. The Model is dominar. The color is black.
Encapsulation:
In most object-oriented programming, we can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.
Let’s use encapsulation in our car example. Now imagine we have a super-secret engine. In the first example, we will hide our engine using a private variable. In the second example, we will hide our engine using a private method.
Example 1:
class Car: def __init__(self): self.brand_name = 'Audi ' self.model = 'r8' self.__engine = '5.2 L V10' def get_description(self): return self.brand_name + self.model + " is the car" c = Car() print(c.get_description) print(c.__engine)
In this example
self.__engine is a private attribute. When we run this program we will get the following output.
Audi r8 is the car AttributeError: 'Car' object has no attribute '__engine'
We get an error that
Car object doesn't have _engine because it is a private object.
Example 2:
We can also define a private method by adding
__ in front of the method name. Following is the example of how we can define a private method.
class Car: def __init__(self): self.brand_name = 'Audi ' self.model = 'r8' def __engine(self): return '5.2 L V10' def get_description(self): return self.brand_name + self.model + " is the car" c = Car() print(c.get_description()) print(c.__engine())
In this example
def __engine(self) is a private method. When we run this program we will get the following output.
Audi r8 is the car AttributeError: 'Car' object has no attribute '__engine'
Now suppose we want to access the private attribute or method we can do it in the following way:
class Car: def __init__(self): self.brand_name = 'Audi ' self.model = 'r8' self.__engine_name = '5.2 L V10' def __engine(self): return '5.2 L V10' def get_description(self): return self.brand_name + self.model + " is the car" c = Car() print(c.get_description()) print("Accessing Private Method: ", c._Car__engine()) print("Accessing Private variable: ", c._Car__engine_name)
The output of the following program is:
Audi r8 is the car Accessing Private Method: 5.2 L V10 Accessing Private variable: 5.2 L V10
Encapsulation gives you more control over the degree of coupling in your code. It allows a class to change its implementation without affecting other parts of the code.
Decorator:
Imagine you have to extend the functionality of multiple functions. How will you do that?
Well, one way is you can make functional calls and in that function, you can handle it. Making changes in 30 to 40 function calls and remembering where to place the call is a messy task. But the more elegant way provided by Python is with decorators.
What is a decorator? A decorator is a function that takes a function and extends its functionality without modifying it explicitly. Well, I understand if you are still confused about what decorators are. Don't worry – we have a tool named example to explain it.
Let's try an example to understand the decorator. There are two ways to write a decorator.
Method 1
We declare a decorator function and in the arguments of the function we expect the function to be passed as an argument. Inside that, we write a wrapper function where operations are carried out and it is returned.
>>> def my_decorator(func): ... def wrapper(): ... print("Line Number 1") ... func() ... print("Line Number 3") ... return wrapper ... >>> def say_hello(): ... print("Hello I am line Number 2") ...
To call the function we assign the decorator with
say_hello as an argument.
>>> say_hello = my_decorator(say_hello)
We can also check the reference using
say_hello. We will get the output that tells us it has been wrapped by the
my_decorator function.
<function my_decorator.<locals>.wrapper at 0x10dc84598>
Let's call our
say_hello function:
>>> say_hello() Line Number 1 Hello I am line Number 2 Line Number 3
See the magic the line "Hello I am line Number 2" gets printed in between Line Number 1 and 3 because the function call gets executed there.
Method 1 is clunky, and because of that many people prefer a different approach.
Method 2
Here our decorator declaration remains same but we change how the call is assigned to that decorator. Whichever function requires that decorator wraps itself with
@decorator_name.
>>> def my_decorator(func): ... def wrapper(): ... print("Line Number 1") ... func() ... print("Line Number 3") ... return wrapper ... >>> @my_decorator ... def say_hello(): ... print("Hello I am line Number 2") ... >>> say_hello()
Output is the same:
Line Number 1 Hello I am line Number 2 Line Number 3
A decorator is a powerful tool and it is used in the following development scenarios of an application:
- Setup logger
- Setup configuration
- Setup Error catching
- Extending common functionality for all function and classes
Exceptions:
When we were learning various syntax we came across various errors. Those errors occurred because of the syntax. But in a real-world application, errors (or commonly known as bugs) not only occur due to syntax issues but also because of network errors or some other cause.
To handle these issues we use Try - Except. In
try block, we write the expression that we want to be executed, while in
except block we catch the error. The Try-Except block looks as follows:
try: expression except: catch error
Let's understand this by an example:
>>> try: ... print(value) ... except: ... print("Something went wrong") ...
Here we are trying to print the value variable but it is not defined. So we get the following output:
Something went wrong
You may be thinking that the line "something went wrong" is not that helpful. So how can we know what went wrong here?
We can print the exception and use it to find out what went wrong. Let's test this in our example:
>>> try: ... print(value) ... except Exception as e: ... print(e) ...
And the result is:
name 'value' is not defined
Whoa! That's magic. It is notifying me that 'value' is not defined.
Python also provides a tool named
raise. Suppose you don't want a certain condition to occur and if it occurs you want to raise it. In such condition you can use
raise. Consider the example below:
>>> i = 5 >>> if i < 6: ... raise Exception("Number below 6 are not allowed") ...
The output we get is as follows:
Traceback (most recent call last): File "<stdin>", line 2, in <module> Exception: Number below 6 are not allowed
There are many sub-types of Exceptions, so I recommend that you go through the Python Documentation to understand them.
Package Import:
You have learned the basics of Python and now you are all ready to build awesome applications. But hold on – we are still missing some important topics.
Without package import, you will be forced to write everything in one single file. Imagine what a mess it will be.
Create two files named
main.py and
hello.py. Remember both file needs to be in the same directory.
Under
hello.py copy paste the following code:
def say_hello(): print("Hello world")
Under
main.py copy paste the following code:
import hello if __name__ == "__main__": hello.say_hello()
In
hello.py we have declared a
say_hello() function which prints "Hello world". In
main.py you'll see an import statement. We are importing the hello module and calling the
say_hello() function from that module.
Run our program using the following command:
➜ python main.py
Output:
Hello world
Now let's understand how to import a module which is in another directory.
Let's create a directory named "data" and move our
hello.py inside that directory.
Go to the
main.py and change the previous import statement.
from data import hello if __name__ == "__main__": hello.say_hello()
There are two ways to import from a directory.
- Method 1:
from data import hello
- Method 2:
import data.hello
I prefer method 1 because of its readability. You can choose whichever method looks better to you.
Let's run our application using the following command:
➜ python main.py
And an error occurs. Wait why did this happen? We did everything right. Let's go through the error:
Traceback (most recent call last): File "main.py", line 1, in <module> from data import hello ImportError: No module named data
Well Python is telling us that it doesn't recognize a module named data. To solve this issue create a
__init__.py inside data directory. Leave the file blank and run the program again and you'll get the following output:
Hello world
Well python by default does not treat a directory as a module. To inform Python to treat a directory as a module,
__init__.py is required.
JSON Handling:
If you have worked previously with web development or app development you may be aware that all the API calls take place in JSON format. While JSON looks similar to a dictionary in Python, remember that it's very different.
To handle JSON, Python provides an inbuilt
json package. To use this package we need to import it as follows:
import json
This library provides two methods which help us in handling the JSON. Let's understand them one by one.
JSON loads:
If you have a JSON string and want to convert it back to a dictionary you need to use the
loads method. Go to the Python shell and copy-paste the following code:
>>> import json >>> >>> data = json.loads(json_string) >>> type(data) <class 'dict'> >>> data {'user_name': 'Sharvin', 'age': 1000}
JSON dumps:
Now let's convert our data back to the JSON string format using the
dumps method.
>>> jsonString = json.dumps(data) >>> type(jsonString) <class 'str'> >>> jsonString '{"user_name": "Sharvin", "age": 1000}'
To learn more about JSON Manipulation, go through the Python Documentation.
That's it!
And we're done! I hope you now understand the basics of Python. Congratulations! That's a huge achievement.
Feedback is welcomed. Also if you want to learn about any other topic you can tweet the topic name on Twitter and include my Twitter handle. [ @sharvinshah26 ]
Feel free to connect with me on Twitter and Github.
|
https://www.freecodecamp.org/news/the-ultimate-guide-to-python-from-beginner-to-intermediate-to-pro/
|
CC-MAIN-2021-21
|
refinedweb
| 11,472
| 66.03
|
Fast Native Eclipse with GTK+ Looks 300
Mark Wielaard writes "The gcj team created a natively compiled build of the Eclipse IDE. The resulting binary starts up faster then with any traditional JVM since there is no virtual machine to initialize or slow byte code interpreter or just in time compiler involved. This means that gcj got a lot better since the last Slashdot story in December about gcj and Eclipse. Red Hat provides RPMs for easy installation. Footnotes has screenshots by Havoc Pennington of the Eclipse IDE with GTK+ widgets."
Startup sure, but how fast does it run? (Score:4, Interesting)
Re:Startup sure, but how fast does it run? (Score:2, Flamebait)
The class library is certainly complete enough to write nice, crisp, fast and beautiful native GUIs with SWT.
The true question is: What can you do with GCJ?
The answer is: everything you can't do with the JDK, because the JDK starts up too slowly, because Swing suffers from obesity, and because both memory and disk footprints of the JRE are a disaster.
Re:Startup sure, but how fast does it run? (Score:5, Insightful)
Swing suffers from obesity - what does that mean?
I've been developing Java applications for years (including a stint as project lead on a weather satellite imagery analysis program) and I know firsthand how much Java has improved. Spend some time writing applications in Java, using Swing (I use Netbeans for my IDE)...you'll see how sporty applications can be. Also check out Sun's Java Games [java.net] community for some links to games that really exhibit excellent performance.
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:4, Insightful)
two responses to that.
I write 95% of my work in Java. It's just as performant as anything else doing the same job. Most of my stuff (web applications) typically service small requests - very much like ls, albeit in a different environment. But the trick is, you don't start a new JVM for each invocation; you have a JVM running all the time and service the requests you receive within it. In this sense, the webapp is analogous ot a shell.
I'm not saying Java doesn't have problems - it does have a significant problem which is Sun's attitude to 'intellectual property' and their continued restrictive licensing. But speed and efficiency are no longer problems Java has.
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:2, Insightful)
Re:Startup sure, but how fast does it run? (Score:3, Insightful)
Re:Startup sure, but how fast does it run? (Score:2)
Furthermore, Python is more syntactically similar to Java than any other language (maybe perl). And the reason python takes less time is because it is an interpreter and not a virtual machive, unless you are using Jython, which is python inside the java vm. I do not think higher level means what you think it means. I suspect you are try
Re:Startup sure, but how fast does it run? (Score:3, Informative)
class bar(object):
def foo(self, obj):
obj.register(self)
bar::foo() is completely generic. It can register itself with any object, as long as that object supports the register() method. In Java, you'd have to define an interface and have all possible objects you're interested in registering with implement that interface.
Object oriented languages have similar capabilities, but they do *not* all offer the same ab
Re:Startup sure, but how fast does it run? (Score:3, Insightful)
Not necessarily; reflection could do this with any old Object. Admittedly, the interface solution is normally neater, but it's also a better solution for maintenance purposes - too much dynamism makes code easier to write, but can make it much harder to maintain and introduce subtle bugs unless you're very disciplined (and, more importantly, so are every one of your predecessors and colleagues...)
Re:Startup sure, but how fast does it run? (Score:2)
Isn't this a good thing? Don't you want to think about everything that wants to use register()? What about the posibility of name-space clashing, i.e. that register() registers itself with an object that supports the register() but in a totally unexpected way, and was never intended to be used in this way?
I wouldn't say it's another level of abstraction, but rather a
Re:Startup sure, but how fast does it run? (Score:2)
>>>>>>
Okay, thought about it. Decided that all the objects that could get passed to that function support an appropriate register() method. In Python, I'm done. The solution works. In Java, in addition to thinking about it, I have to now go and modify all those classes to add an interface to it. Now the there is talk about adding optional type declarations to Python, to both allow better code ge
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:2)
Well, Sun's Java tools, for one, are written all in java (javac, jar, etc.).
Umm... no (Score:3, Interesting)
Re:Startup sure, but how fast does it run? (Score:5, Informative)
Of course, I don't see myself as a "Java programmer" or a "carpenter" or a "brick layer". I wouldn't take any pride in that. I have a degree in computer science...
To further extend your knowledge in computer science, look into the Internet tool called "Google". Using it can save you from ridiculing yourself by publicly posting uneducated statements:
Embedded Java [google.ca]
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:2)
Complete and utter BS. I know for a fact that there are quite a few auto manufacturers currently working on Java in-car computing systems. I should know - I work with the team at IBM that is developing the technologies for them (and close to the team that originally wrote Eclipse).
Also, have you heard of Java running on cellphones? It's been all over the news lately.
Re:Startup sure, but how fast does it run? (Score:5, Interesting)
What utter garbage. I'd describe myself primarily as a Java programmer, and I've got a college degree, a masters degree and a bucketful of professional qualifications.
I don't know. Who are you that you can say the same? There are plenty of cases where Java can be used in shell scripts, or where the same functionality can be achieved using a tool such as Ant (which is very widely used these days). Startup time isn't always the be all and end all of what people need from their programs. If it is, then obviously there are better tools than Java. I'd have hoped that at some point they'd have taught you in your college degree that there are plenty of tools out there and that there's such a thing as picking the right tool for a given job. That tool may be Java, it may be perl, it may be lovingly hand-crafted assembly code.
The fact that you seem to ignore that means that you also ignore the things that you can do with the JDK that you can't do with gcj, and ignore the requirements people may have that your preferred way of working doesn't address. And also, it seems, the fact that some people [sun.com] don't agree with your blanket generalisations.
Re:Startup sure, but how fast does it run? (Score:3, Interesting)
Gee whiz, you're a raving spastic.
I have a degree in computer science. The day you will get a college degree, or at least some formal qualification, you won't need to go around saying: I am a "Java programmer".
Right, and the day you get around to pulling your head out of your own ass - or at least do something to stop you talking so much shit all the time - you won't need to go around pompously saying, "I have a degree in computer science."
Who are you that you can say what can be important in someone
Couple of hits, couple of misses. (Score:3, Interesting)
Well...no. I believe that embedded environments are a rather stripped down form of Java, but Java isn't all that uncommon in embedded systems. Take a look at Javacard -- you'd use it in environments where you typically have less than 64KB of memory.
That being said, I *still* think Java is a terrible language for most people to be using. There's something to the argument that there's "not much better out there".
Problem: C sucks f
Re:Startup sure, but how fast does it run? (Score:3, Interesting)
So do perhaps 90% of the people reading Slashdot. IMO it's not much to be proud of.
You're a pompous ass. He probably has better qualifications than you do.
Re:Startup sure, but how fast does it run? (Score:2)
Re:Startup sure, but how fast does it run? (Score:2, Informative)
Fast. Was:Startup sure, but how fast does it run? (Score:3, Informative)
increases the credibility of GCJ (Score:4, Insightful)
GCJ slower than IBM JDK (Score:2)
Five years from now, when gcj has sped up and can take advantage of the Java 1.5 typed container classes and disable bounds checking, Java may actually become usable, if still slower than C/C++ programs.
Re:GCJ slower than IBM JDK (Score:3, Insightful)
load times (Score:3, Interesting)
I leave stuff like mozilla, eclipse, and xemacs running for weeks on end.
Re:load times (Score:3, Funny)
Re:load times (Score:3, Informative)
Of course, java tends toward handling this differently, where java programs invoke each other inside the same runtime, but it makes mixing java and non-java tools annoying.
Re:load times (Score:4, Informative)
I wrote a simple JVMPI method tracer. It's mind-blowing what all happens before your code is actually run. Here's a method trace I just ran with 1.4.2 for a simple program. [visi.com]
-Kevin
load times *do* matter in the real world (tm) (Score:5, Insightful)
For those who start up their IDE in the morning and close it down in the evening (or at the end of the week, whatever), then long startup times are just a minor cost of doing business.
For someone like me, however, who is ambivalent about this IDE or that IDE, and whose fingers are too hard-wired for one particular editor [vim.org] to use the brain-damaged editors foisted by most IDEs, startup time IS a big issue. When you are going in and out of tools all day long, it becomes a major annoyance to have to wait for the darned thing to start up.
Re:load times *do* matter in the real world (tm) (Score:2)
Yup, And there's also stuff like daemons started from inetd, tools launched from cron jobs and shell scripts and data manipulation programs - the general UNIX philosophy favors launching these kinds of things as short-lived processes.
I know java advocates who would probably recommend that all the other code that interfaces with these things just be written in java and run as
Re:load times *do* matter in the real world (tm) (Score:4, Informative)
Re:load times (Score:2)
Modified GCJ Required (for now) (Score:4, Interesting)
"A team of hackers from Red Hat has released RPMS for a version of Eclipse, a free software IDE written in Java, that has been compiled with a modified gcj. You can find more information here. We'll be integrating the required gcj patches into cvs in the near future."
ps
Slashdot preview is buggy today...can't do HTML format preview and links one or more spaces get embedded in URLs (like the one below).
---
My most underrated Slashdot post is
What is yours?
Another FOSS IDE. (Score:4, Interesting)
There is another FOSS IDE called gps [act-europe.fr]. They call the unsupported version the "academic edition", but you can download the source, and a peak at a few files shows that it's GPL'd. (Their economic model is to give it away for free and sell support for those who need it.)
It's a cross-platform IDE, with binaries available for Linux, Solaris, and various versions of Windows, and in principle you should be able to build it on any *n*x system where you can get GTK2 to run.
The bad news is that language support is still limited. It has full support for Ada and partial support for C and C++, which are lower priorities for the authors. It comes with instructions for setting up support for your language, but that looks like a non-trivial task.
I've just started playing with it so I can't give a good review, but so far it has been very helpful. The features listed at their Web site are:
Screenshots are available at the link above.
Please Read Parent!!! (Score:4, Funny)
Let's take a look:
Automatic generation of body files
Hot *damn*! It writes my code for me!
Source code reformatting
Then it reformats it to fit whatever standard I need!
Automatic code fixing
Then it *debugs* the code!
Application builder
Finally, it *builds* the program I'm working on!
All this, from a piece of software that the ignorant layman might consider no more than a wrapper for an editor and a compiler.
Truly, a groundbreaking achievement.
Plugins? (Score:4, Interesting)
Re:Plugins? (Score:4, Informative)
That was the case last time I looked at GCJ about a year ago. I ended up being unable to use it because of lack of windowing toolkit support. Anyone know the status on all that?
Re:Plugins? (Score:5, Interesting)
Eclipse uses its own SWT toolkit, which works well under GCJ. SWT is a combination of native code and Java, and is said to both be fast and integrate well with other window systems, as it uses native widgets when available.
The implementation of AWT (including applets) is coming along very quickly, but it isn't complete yet.
Total GCJ performance (Score:5, Insightful)
I don't know how much of this potential is actually realized in JITs (it's insanely hard to do) and how much of a difference it makes in the end. How substantial would the difference between a specialized AMD vs Intel optimziation be, for example (which would presumably depend on the task)?
I suppose the best possible world would be to have the optimization run exactly once, the first time you install a program. (Yeah, you could conceptually move the same installation to a different CPU, or add more RAM, or some such, but let's not make an already messy issue even messier.)
I doubt such things are easy to benchmark, and the best test may well be something like this (gcj'd Eclipse), where the end result to the user is "which one feels faster?" and "which one actually runs faster?"
Isn't that how .NET languages like C# work? (Score:3, Informative)
I don't know how well it works but I can see the potential.
Re:Isn't that how .NET languages like C# work? (Score:2)
My understanding (I may be wrong) is that the way that Microsoft's "managed code" works is that the installer creates a native compile of your application on your computer right when it installs.
I think
.NET is just in time compiled, similar to Java.
If what you said is true, we wouldn't be able to copy an executeable from one computer to another. It would have to be installed.
Optimizing JITs are very common (Score:2, Insightful)
> can be optimized for your exact configuration (AMD vs
> Intel, particular kinds of RAM, etc.) It can even
> (conceptually) optimize the same program differently at
> different times depending on usage. At, of course, a
> startup penalty and runtime compilation overhead.
True, the optimization for hardware platforms are less significant than the overall optimizations.
> I don't know how much of this potential is actually
> rea
Re:Total GCJ performance (Score:2, Interesting)
That's not nearly as interesting as using runtime feedback to further optimize code. Static optimizing compilers need to make guesses about things, like how often loops are expected to r
Re:Total GCJ performance (Score:2, Insightful)
That's what makes GCJ so interesting: it's a Java compiler that, unlike most other Java compilers, compiles directly to native code without the VM in between. Thus, you potentially lose some of the advantages that the VM can provide you
Re:Total GCJ performance (Score:2)
The main advantages of Java and the VM have never been thought to be performance by anyone. It's definately an issue, especially for real-time interactive applications. A common way to solve all sorts of problems in software engineering, especially when part of the problem is completely out of your control, is to create an abstraction - a layer of indirection. For example, you might have to develop a 3D gra
Re:Total GCJ performance (Score:3, Interesting)
Oh, but there are a few fallacies associated with that.
The first and bigggest one, a pet peeve of mine, is that people claim that they can reoptimize the application repeatedly on the fly
Re:Total GCJ performance (Score:2)
Re:Total GCJ performance (Score:2)
Branch prediction and OO languages (Score:4, Insightful)
There's an interesting claim I have seen made: Apparently the late binding feature of object-oriented languages -- virtual methods in C++, any non-static method in Java -- works against branch prediction, effectively resetting the prediction state whenever such a call is made, because the target jump address must be resolved -- read from a memory location -- only at the time of the jump. If this claim is accurate, this means typical OO code is inherently slower to execute than non-OO code on modern processors. Of course, the problem will equally apply to any language that supports function pointers, and in particular to C programs "emulating" OO with structs and function-pointer tables.
Re:Branch prediction and OO languages (Score:2)
I don't think GCs move code around very often, and code addresses are all that matters for branch prediction.
UltraSPARC III has a "prepare to branch" instruction that can allow the processor to correctly prefetch past an unpredictable unconditional branch like those found in virtual method calls.
Re:Total GCJ performance (Score:3, Informative)
You get all the advantages of Native compilation, and system specific JIT compilation combined - at the expense of more complexity and lots more disk space.
As other
Re:Total GCJ performance (Score:3, Insightful)
Probably the biggest downside is that OS/400 simply isn't particularly user friendly. Leaving aside for a moment the existence of Client Access, OS/400 is completely command line and/or menu driven. Everything is "green screens" and dumb terminals (or terminal emulators running on a PC ). There really isn't any GUI, except the "psuedo-GUI" you get by running Client Access on a PC.
I spent about 4 years working primarily with AS/400's, and I can
Re:Total GCJ performance (Score:2)
You do now get websphere on it, so you can run java stuff on it, and apache and various other bits and pieces have been ported, but 99% of software out there will simply not work on OS400 without major rewrites.
Ewa
Re:Total GCJ performance (Score:2)
Disclaimer - I've never actually played with an AS/400 due to the price
:-) I just read about it and like
GCJ performance is a myth. Benchmarks inside. (Score:5, Informative)
Often the JVM will out-perform GCJ with a factor of 3. Check out the numbers on this page [shudo.net].
I fail to see why people want to run a GCJ compiled evrsion of a development tool and run at at one third of the speed of the JVM, just in order to save a few seconds of startup time.
Re:GCJ performance is a myth. Benchmarks inside. (Score:3, Informative)
They don't have figures for memory usage, installation profile, etc., and I bet in those areas GCJ beats Hotspot for end-users. And you can't beat an install with no library dependencies.
Re:GCJ performance is a myth. Benchmarks inside. (Score:3, Insightful)
Let's assume for a second that you are correct, and Java limits the platforms you can distribute to. Tell me again exactly how GCJ improves on that?
The JRE is 13 MB last I looked. And you only have to download it once and it works for all your Java apps. Most Java applications are offered in a package both with an
Good for QNX (Score:3, Informative)
obligatory pun (Score:5, Funny)
View-based programming (Score:2)
Once of the advantages of this aspect-oriented approach is that menu items and UI elements change as your view changes. You keep the same oouter wrapper at all times, but your available choices very. I found it very confusing in the beginning, but once you get used to it it makes life a lot easier and keeps things cleaner.
Why JVM? (Score:3, Interesting)
What's the purpose of the JVM?
Dynamicity? No. Java is a aggressively static language. Meanwhile, highly dynamic languages like Lisp, Dylan, and Scheme (among others) can be efficiently compiled to native code.
Speed? While in theory a JIT can be faster, its not the case in practice. In the "Great Computer Language Shootout" (which isn't bad, as far as these things go) Java has an average CPU rank of 14, behind other static languages like C, C++, Ocaml, and SML, and behind dynamic languages like Scheme and CL as well! In reality, Java can only get within 90% of the speed of C for inner-loop numeric-type stuff (which lends itself to JIT optimization).
Flexibility? Java is highly inflexible. Its almost as as inflexible as C. It requires you to manually specify pretty much everything. You even have to do manual boxing/unboxing! Java is so highly structured, it should be compilable to native code that hits 90% the speed of C, without a very smart optimizer at all.
Safety? Given Java's lack of pointer types, it shouldn't need a JVM monitoring it to be safe. Again, there are lots of safe languages (Haskell, Clean, and the aforementioned dynamic languages) that don't require a runtime monitor.
Actually, I don't see much of a point in Java at all. Its got statically typed, but can't use that advantage to be as fast as C++. It runs in a VM, but can't use that advantage to be as dynamic as Python. Its syntax isn't any easier to use than something like Dylan (kinda like Lisp with a Pascal syntax) or Python. It doesn't have the development environment advantages of Smalltalk. Heck, its not even a very good compromise language ---- Dylan is as easy, often faster, and more powerful, Python is much easier (and thanks to Psyco) often as fast, C++ is much more powerful, as well as much faster, etc.
Re:Why JVM? (Score:2)
- Dynamicity? No.
I don't think 'Dynamicity' is a word. But hey, enlighten me?
- Flexibility? Java is highly inflexible. Its almost as as inflexible as C.
Nup, not even. See 'instanceof' - which, although considered hackish among OOP elites, gives volumes compared to using void pointers in C. Then there's the whole polymorphism thing, but hey - C is procedural.
- Safety? Given Java's lack of pointer types, it shouldn't need a JVM monitoring it to be safe.
Someone correct me if I'm wrong, but AFAIK
Re:Why JVM? (Score(, size: 100);
for(i from 0 below 100)
do-foo(vec[i]
Re:Why JVM? (Score:3, Informative)
I don't think 'Dynamicity' is a word. But hey, enlighten(
Re:Why JVM? (Score:5, Informative)
Static types perhaps, but very dynamic when it comes to linking. Java has a lot of support for things like dynamic class loaders that lead to a very nice plug-in architecture, and extreme flexibility when it comes to deployment of code updates to a running application. Not to mention fun with diddling bytecodes on the fly.
Re:Why JVM? (Score:3, Interesting)
If I understand the myth/history correctly, it was made to run arbitrary code from an arbitrary source in an arbitrary environment, in a safe manner.
Sun needed something to load up additional code within a program which the original programmer didn't know anything about, get it from somewhere in the network at runtime, then run it in anything from a toaster to a cable-box to a PC to a cell-phon
Re:Why JVM? (Score:2)
>>>>>>
Not looking for the strengths, but why it requires a VM.
Flexibility? Once more, it's not about the type-system. It's about loading arbitrary code into your application server without shutting it down, or worrying too much that the code will crash your system.
>>>>>
But why does it require a VM? C/C++ can do the dynamic code loading via dlopen() and kin, and L
Re: Why JVM? (Score:2)
The big deal is that unless you have the source, you're restricted to those platforms that the maker happens to support. Which is usually a depressingly small number, and if you're not running Windows XYZ, can be a pretty frustrating experience.
Permissions is usually the domain of the OS kernel, not the language runtime. How is putting the thing in a VM any more secure than putting t
Memory Usage vs Eclipse Running in JVM (Score:2)
Re:Memory Usage vs Eclipse Running in JVM (Score:5, Informative)
Eclipse 2.1.1 with JVM
- Second start: 13 seconds
- Memory Eclipse: 80 MB
- Memory JVM: 65 MB
Eclipse 2.0.1 without JVM
- Second start: 9 seconds
- Memory: 96 MB
The download page seems to indicate you're downloading an Eclipse 2.1.0 version, but the about dialog says 2.0.1. Which one is it?
Cheers,
Thimo (back to coding in Eclipse 2.1.1
BitTorrent url (Score:2, Informative)
jit is not a slowdown... (Score:3, Informative)
Just so you all know. A good jit/hotspot compiler can make things quite a bit faster than any static build compiler. This is because at runtime certain optimizations are possible that simply cannot be done at build. These optimizations are typically very aggressive, to that extent that later on in execution it may turn out so that those snippets have to be thrown away and recompiled. And thus they usually target only the hotspots, i.e. portions of code that are being executed inside tight loops, which is usually where compile time savings occur anyway. The speed of the rest of the code is pretty much governed by the programmer anyway along with his choice of algorithms and data structures.
A good example of such snippets would be the inlining of a virtual method, turning a virtual method recursion into a loop along with some unrolling, inlining function pointer call (which is basically the same as virtual method call).
Mind you, ofcourse a hotspot compiler could also be implemented to a C/C++ runtime environments, but I haven't heard of anyone actually taking that path.
(for the record, I'm a C programmer and rarerly write much with java)
Re:Looks great! (Score:2, Interesting)
Re:Looks great! (Score:2)
On the flip side, most of my Java coding counterparts claim that Eclipse crushes VS.NET. I've tried Eclipse, and although it was good (and free) I wasn't extremely impressed (no offense to OSS, but my experience has always been that a commercial IDE is far better than it's OSS counterpart). I'll have to try out Intel
Re:Looks great! (Score:3, Interesting)
Unfortunately one of the reasons IntelliJ has got more expensive is because of its success. Its about 100$ more expensive now than when I purchased it. If you a
Microsoft's IDEs? You have GOT to be kidding (Score:2, Offtopic)
Have you used Metrowerks Codewarrior [metrowerks.com]? Now there's an IDE. It's a joy to use. Runs on Mac and Windows. I think there is a Linux version that uses gcc, but I haven't tried it.
(I admit I haven't tried Eclipse yet, but I would be very surprised if it were better than CodeWarrior.)
Everything Just Works in CodeWarrior. I've even got my wife, a web designer who prefers to hand-code her HTML, to use it to write her
Re:Microsoft's IDEs? You have GOT to be kidding (Score:2)
I now can't stand working without xemacs, and haven't really seen the point of an IDE for years (though I use one at work, just because that's what everyone else is using).
CodeWarrior for the Mac has been a wonderful IDE, if you like IDEs, for years upon years. However, you claimed that it worked on Windows. From what I've seen, the Windows version of CodeWarrior (keep in mind that my experi
Re:Microsoft's IDEs? You have GOT to be kidding (Score:3, Informative)
While IDEs can be quite a personal preference thing, you don't quite mention anything specifically about what is so good about the Metrowerks IDE other than it being cross platform and easy to author web pages in(!). I mean come on neither of those are core IDE functionality. I would have given you more credit if you had any pointed thing
Re:Microsoft's IDEs? You have GOT to be kidding (Score:2)
You will be surprised.
Maybe not for C/C++ development: The Eclipse support (which is implemented, just the Java stuff, exclusively with plug-ins) currently consists of just the basics: syntax-aware editor, code outline, debugger, makefile support. There are no source code tools, no code completion, no cross-referencing tools (Doxygen/JavaDoc lookup, etc.).
The Java personality, however, is extremely
Re:Looks great! (Score:2, Funny)
1) Lead developer has a cool name, like "Anders Heljborg".
2) Lead developer earns a cool salary, like $1,000,000+ a year.
3) Lead developer has legion of microsoft's code monkeys implementing and testing features out the yang, and they still can't burn up all the money they extort from, err, i mean charge, their customers.
4) Anders Heljsborg rewite and maintainence has been going on for four or five years. Give eclipse a chance to ketchup.
Re:Looks great! (Score:2)
Re:Looks great! (Score:2)
Dammit, Anders, aren't you supposed to be coding instead of posting to Slashdot?
Re:You sir are a troll.... (Score:2, Insightful)
Re:You sir are a troll.... (Score:2)
Emperor has no clothes (Score:3, Insightful)
Just getting a program to
Re:Emperor has no clothes (Score:2)
Re:Troll...Troll...Troll... (Score:5, Informative)
Java is still some 40 times faster than Python. As hardware speed continues to obey Moore's law, performance per clock cycle becomes less important. (For many areas of computing anyway.)
Re:Troll...Troll...Troll... (Score:2)
Re:Troll...Troll...Troll... (Score:2)
And this is horse shit.
What you meant to say was "for some tasks, java is faster than python, but python is clearly much faster for the vast majority of tasks that the programmer must solve. more importantly, however, python saves programmer time, which is far more expensive and valuable than CPU time."
or something like that.
if i wasn't so lazy today, i'd dig up the link to put you in your place. but you wouldn't believe it, so why bother?
Re:Troll...Troll...Troll... (Score:2)
Re:Troll...Troll...Troll... (Score:2)
But then again, once it goes to hardware, it's not about the language, it's about the skill of the hardware designer.
Sun abandoned java-in-hardware, but with all the server-side java code, why not have a java bytecode machine?
Re:Troll...Troll...Troll... (Score:2)
Re:Annoyed with the post (Score:5, Insightful)
Probably not. Nor would it have kill him to explain that a compiler turns source code into a binary executable for a particular architecture, or that IDE stands for Integrated Development Environment, or that a JVM is a Java Virtual Machine, or that RPM stands for Redhat Package Manager, or that GTK+ stands for GIMP ToolKit, or that now it is now used for far more than just GIMP, or that GIMP stands for GNU Image Manipulation Program, or that the included acronym stands for Gnu's Not Unix, or that GNU is a project to write free implementations of operating system components derived around the POSIX model, or that POSIX is a collection of operating system standards based around tradional Unix interfaces.
Doing all of these at once, however, would probably piss everyone off. Explaining just the particular missing piece of information that a specific reader is going to need would be better, but would require Slashdot readers to be more homogenous and Slashdot posters to be more psychic than they are.
The compromise, wherein the word "gcj" is linked to a web page entitled "The GNU compiler for Java", seems to be hard to improve upon.
Re:Annoyed with the post (Score:2)
Simon
|
http://developers.slashdot.org/story/03/08/03/1555206/fast-native-eclipse-with-gtk-looks
|
CC-MAIN-2015-35
|
refinedweb
| 5,665
| 62.88
|
If you're brand new to using unittests, ...READ MORE
connect mysql database with python
import MySQLdb
db = ...READ MORE
It appears that a write() immediately following a read() on a ...READ MORE
Not sure what your desired output is, ...READ MORE
suppose you have a string with a ...READ MORE
if you google it you can find. ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
This actually gives you the property names ...READ MORE
from django.tests import TestCase
class MyTests(TestCase):
...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/31590/how-to-run-django-unit-tests-on-production-database-in-python
|
CC-MAIN-2020-05
|
refinedweb
| 105
| 88.94
|
IP6(4) BSD Programmer's Manual IP6(4)
ip6 - Internet Protocol version 6 (IPv6)
#include <sys/socket.h> #include <netinet/in.h> int socket(AF_INET6, SOCK_RAW, proto); 2553), and the advanced API (defined in RFC 2292). The basic API looks very similar to the API presented in ip(4). Advanced API uses ancillary data and can handle more complex cases. To specify some socket options, a certain level of privilege (i.e. root privilege) is required.
IPV6_UNICAST_HOPS may be used to set the hoplimit field in the IPv6 header. As the symbol name suggests, the option controls the hoplimit field on unicast packets. If -1 is specified, the kernel will use a de- fault it- self elim-limit; unsigned. Members ob- jects. equal to IPPROTO_IPV6, and cmsg_type equal to IPV6_PKTINFO. If IPV6_HOPLIMIT is enabled, the hoplimit value on the packet will be made available to the userland program. The ancillary data stream will contain an integer data item with cmsg_level equal to IPPROTO_IPV6, and cmsg_type equal to IPV6_HOPLIMIT. inet6_option_space(3) and friends help parse ancillary data items for IPV6_HOPOPTS and IPV6_DSTOPTS. Similarly, inet6_rthdr_space(3) and friends help parse ancillary data items for IPV6_RTHDR. IPV6_HOPOPTS and IPV6_DSTOPTS may appear multiple times on an ancillary data stream (note that the behavior is slightly different than the specification). Other ancillary data items can appear no more than once. For outgoing direction, ancillary data items with normal payload data can be passed using sendmsg(2). Ancillary data items will be parsed by the kernel, and used to construct the IPv6 header and extension headers. For the 5 cmsg_level values listed above, the ancillary data format is the same as the inbound case. Additionally, the IPV6_NEXTHOP data object can also be specified. struc- ture. If the socket address structure contains an IPv6 address (i.e., the sin6_family member is AF_INET6 ), then the node identified by that ad- dress must be a neighbor of the sending host. If that address equals the destination IPv6 address of the datagram, then this is equivalent to the existing SO_DONTROUTE socket option. For applications that do not, or are unable to use sendmsg(2) or recvmsg(2), ob- jects. op- tional receive information that the application has previously specified ap- plication processes this buffer exactly as if the buffer were returned by recvmsg(2) as control information.
When using getsockopt(2) with the IPV6_PKTOPTIONS option and a TCP sock- et,.
In some cases, there are multiple APIs defined for manipulating a IPv6 header field. A good example is the outgoing interface for multicast da- tagrams: it can be manipulated by IPV6_MULTICAST_IF in basic API, IPV6_PKTINFO in advanced API, and the sin6_scope_id field of the socket address passed to sendto(2). When conflicting options are given to the kernel, the kernel will get the value in the following order of preference: (1) options specified by us- ing ancillary data, (2) options specified by a sticky option of the ad- vanced API, (3) options specified by using the basic API, and lastly (4) options specified by a socket address. Note that the conflict resolution is undefined in the API specification and implementation dependent.
Raw IPv6go- ing packets and to filter incoming packets. Outgoing packets automatically have an IPv6 header prepended to them (based on the destination address and the protocol number the socket is created with). Incoming packets are received without an IPv6 header or extension headers. All data sent via raw sockets MUST be in network byte order and all data received via raw sockets will be in network byte order. This differs from the IPv4 raw sockets, which did not specify a byte ordering and typically application normal- ly pseudo-header checksum for output, and (2) verify the received pseudo- header checksum on input, discarding the packet if the checksum is in er- ror. This option prevents applications from having to perform source ad- dress)); By default, this socket option is disabled. Setting the offset to -1 also disables the option. By disabled we mean (1) the kernel will not calcu- late in- correct op- tion name was unknown.
getsockopt(2), recv(2), send(2), setsockopt(2), inet6_option_space(3), inet6_rthdr_space(3), icmp6(4), inet6.
Most of the socket options are defined in RFC 2292 and/or RFC 2553. IPV6_PORTRANGE and conflict resolution rule is not defined in the RFCs and should be considered implementation dependent.
The implementation is based on KAME stack (which is a descendant of WIDE hydrangea IPv6 stack kit). Part of the document was shamelessly copied from RFC 2553 and RFC 2292.
The IPV6_NEXTHOP object/option is not fully implemented as of writing this. MirOS BSD #10-current December 17, 1999.
|
https://www.mirbsd.org/htman/i386/man4/ip6.htm
|
CC-MAIN-2015-48
|
refinedweb
| 774
| 55.44
|
On Fri, Apr 06, 2001 at 11:35:55AM -0400, Tom Diehl wrote: > Hi all, > On another list I am on (Big Brother if anyone cares) it has been reported > that the <time.h> header is no longer included in glibc. Was this changed No, <time.h> is obviously included in glibc, it is required by many standards. What has changed is that <sys/time.h> no longer includes the whole <time.h>. This was needed to leave the namespace clean as standards require. For what belongs in each header, see e.g.: If some program needs declarations from both headers, but errorneously includes just <sys/time.h>, it worked on glibc until recently but the programs should be fixed. We've done this for all programs in the distribution. sys/time.h was including time.h to get e.g. time_t definition, now is sys/time.h including time.h as well, but after defining macros which only take time_t definition from the header. > for a reason or is bugzilla bate? People are getting compile failures on > stuff that compiles fine on 7.0 because of this. So far the fix seems to > be to use <sys/time.h> instead. Jakub
|
https://listman.redhat.com/archives/wolverine-list/2001-April/msg00264.html
|
CC-MAIN-2017-34
|
refinedweb
| 202
| 79.16
|
After spending about an hour trying to figure out what was the problem that my threaded version of a program took more time than the single-core one, I think I rediscovered the wheel. Simply put, I can not use the clock () function to determine the "real" time I spent working in parallel. What do I mean? Example:
A program creates some threads and each one of them will make argv[1] calls to the rand () function (just to do something so that time goes by
). Then in the end I compute the time recorded by clock () differences and differences with time(). Obviously the ratio below is almost two because my machine is dual core. But ...). Then in the end I compute the time recorded by clock () differences and differences with time(). Obviously the ratio below is almost two because my machine is dual core. But ...
Question: How can I measure the exact time elapsed and not the approximation in seconds with time()?
And the programAnd the programCode:$ g++ try_to_time.cpp -pthread -o try $ ./try 50000000 Just started counting! All threads joined! Duration 1: 11.8488 secs. Duration 2: * started : 1206834449 seconds after 1/1/1970. * finished: 1206834455 seconds after 1/1/1970. Duration 3: 6 secs. $
Code:$ cat try_to_time.cpp #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> #include <pthread.h> using namespace std; #define NUM_THREADS 10 #define DIGITS 4 void * thread_function (void *); int main (int argc, char * argv []) { time_t start1, start2, start3; time_t end1, end2, end3; int iterations, i, rc; void * status; double duration; if (argc != 2) { cout << "Usage error. I am expecting one positive integer." << endl; exit (1); } iterations = atoi ( argv [1] ); // create opaque objects. pthread_t * threads = new pthread_t [NUM_THREADS]; // Make threads Joinable for sure. pthread_attr_t attr; pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); start1 = clock (); start2 = time (NULL); time (&start3); cout << "Just started counting!" << std::endl; for (i = 0; i < NUM_THREADS; i++) { rc = pthread_create(&(threads[i]), &attr, thread_function, (void *) &iterations); if (rc) { cerr << "ERROR; return code from pthread_create() is " << rc << std::endl; exit (2); } } for (i = 0; i < NUM_THREADS; i++) pthread_join ( threads [i], &status ); cout << "All threads joined!" << std::endl; end1 = clock (); end2 = time (NULL); time (&end3); duration = static_cast<double> (end1 - start1); if (duration < static_cast<double> (CLOCKS_PER_SEC)) { cout << "Few iterations. Try again with a bigger number." << endl; exit (3); } cout << "Duration 1: " << fixed << setprecision (DIGITS) << static_cast<double> (duration / CLOCKS_PER_SEC) << " secs." << endl; cout << "Duration 2: " << endl; cout << "* started : " << start2 << " seconds after 1/1/1970." << endl; cout << "* finished: " << end2 << " seconds after 1/1/1970." << endl; cout << "Duration 3: " << static_cast<int> (difftime ( end3, start3 ) ) << " secs." << endl; return 0; } void * thread_function (void * input) { int loops = *((int *) input); int i; for (i = 0; i < loops; i++) rand () % RAND_MAX; // Just a dummy operation. pthread_exit (NULL); }
|
http://cboard.cprogramming.com/cplusplus-programming/101085-how-measure-time-multi-core-machines-pthreads.html
|
CC-MAIN-2014-52
|
refinedweb
| 451
| 66.74
|
A Swipe View Android Example for Screen Paging
This introductory tutorial shows how to code a simple page swiping app with the
ViewPager class. It is the basis for more complex view flipping examples, such as an image swiping gallery (to replace the Android Gallery widget that was deprecated in API 16). The ViewPager controls the swiping (flicking the screen left and right) between multiple screens or pages of data.
(This Android ViewPager swipe.)
Simple Flip View Tutorial Using ViewPager for the Android Screen Swipe Effect
The ViewPager is fed with the multiple screens by a
PagerAdapter (or the sub-classes
FragmentPagerAdapter and
FragmentStatePagerAdapter).
The implementation of the PagerAdapter will create (and destroy) the pages to be shown in the ViewPager. It will load the pages with the data (such as text or images) that must be displayed on the individual pages. This tutorial's PagerAdapter allows swiping through a series of strings (text). The following steps are performed to complete the screen swiping demo:
- Start a new Android app in Android Studio.
- Add the ViewPager widget to the app's screen.
- Define the data (text) to be displayed on each swiped page.
- Define the layout for the swiped pages.
- Implement PagerAdapter which will create each page and load it with data.
- Test the app.
Start a New Android App
Start this tutorial by generating a new project in Android Studio, here it is called it Swipe Demo. (Alternatively add the page swiping effect to an existing App.) Use an Empty Activity with other settings left at default values. Update: The minimum Android API required for the ViewPager Support Library is now API level 9 (Gingerbread), or API level 14 (Ice Cream Sandwhich) if developing apps using Google AdMob for advertising.
The Support Library
The ViewPager is part of the Support Library. If not installed use the SDK Manager to download it (scroll to the bottom of the list of items in SDK Manager to find the Android Support Repository). See also Support Library Setup on the Android Developers website.
Adding the ViewPager Widget to the App's Layout
The ViewPager is referenced using it's package name of android.support.v4.view.ViewPager. (The v4 stands for the first API version that the original Support Library could be used on, but now it requires API level 9 or later.)
Here's the layout from this demo referencing the ViewPager. It is a
RelativeLayout with a ViewPager below a
TextView. Replace the activity_main.xml with code similar to this:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: <android.support.v4.view.ViewPager android: </RelativeLayout>
Defining the Data to Show on Each ViewPager Page
In this example some text is shown on each swiped page. Here the strings are stored in an array. The array could be defined in code but here they are in a resource file. Open the strings.xml file and add a string array. We are using the code names for Android version releases, all named after desserts. Here is the strings.xml for the Swipe Demo:
<resources> <string name="app_name">Swipe Demo</string> <string name="instructions">Please Swipe</string> <string-array <item>Cupcake</item> <item>Donut</item> <item>Eclair</item> <item>Froyo</item> <item>Gingerbread</item> <item>Honeycomb</item> <item>Ice Cream Sandwich</item> <item>Jelly Bean</item> <item>Kit Kat</item> <item>Lollipop</item> <item>Marshmallow</item> <item>Nougat</item> </string-array> </resources>
In the main class file, here called MainActivity.java, a string array is declared at the class level, String pageData[], and loaded from the resource in the onCreate method using pageData=getResources().getStringArray(R.array.desserts).
Create a Layout Used for the Swiped Pages
The swiped screen will display large text that has been centered. Using the Project explorer select the layout folder. Using the context menu (usually right-click) or the File menu select New. Then select Layout resource file. Enter the File name of page.xml. Enter RelativeLayout for the Root element, this will hold the centered text data. Click OK then add a TextView with the textAppearance attribute set to AppCompat.Large, give it an id of textMessage. The final layout XML for a page will be similar to this:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: </RelativeLayout>
Implement PagerAdapter in the Java Class
The PagerAdapter will create and destroy the pages being swiped. In the MainActivity.java class, before the closing brace, create a new class, e.g. MyPagesAdapter, it needs to extend PagerAdapter and will require android.support.v4.view.PagerAdapter to be added to the imports. The new class implements four methods:
- getcount() – Returns the total number of pages and here it is simply the number of strings in the array so returns pageData.length.
- instantiateItem() – This is passed a reference to the ViewPager so the new page can be added to it, and the page number so that the correct data for the page can be loaded. In our implementation we use a class level LayoutInflater to create an instance of page.xml, and set the TextView to a string in the pageData array.
- isViewFromObject() – A method required by the ViewPager to check that a page matches the object from which it was created.
- destroyItem() – This is called when the ViewPager no longer requires the page (it is now several swipes away so can be cleared).
Here is the full MainActivity Java class with the PagerAdapter implemented:
package com.example.swipedemo; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { String pageData[]; //Stores the text to swipe. LayoutInflater inflater; //Used to create individual pages ViewPager vp; //Reference to class to swipe views @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Get the data to be swiped through pageData=getResources().getStringArray(R.array.desserts); //get an inflater to be used to create single pages inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Reference ViewPager defined in activity vp=(ViewPager)findViewById(R.id.viewPager); //set the adapter that will create the individual pages vp.setAdapter(new MyPagesAdapter()); } //Implement PagerAdapter Class to handle individual page creation class MyPagesAdapter extends PagerAdapter { @Override public int getCount() { //Return total pages, here one for each data item return pageData.length; } //Create the given page (indicated by position) @Override public Object instantiateItem(ViewGroup container, int position) { View page = inflater.inflate(R.layout.page, null); ((TextView)page.findViewById(R.id.textMessage)).setText(pageData[position]); //Add the page to the front of the queue ((ViewPager) container).addView(page, 0); return page; } @Override public boolean isViewFromObject(View arg0, Object arg1) { //See if object from instantiateItem is related to the given view //required by API return arg0==(View)arg1; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((View) object); object=null; } } }
The source code is also available in the text_swiper.zip file ready to import into Android Studio (also available from the Android Example Projects page).
Test the Swiping by Running the App
This simple swiping App can be extended to support different types of data.
See Also
- See some more Android Example Projects.
Archived Comments
Ahmad on September 4, 2014 at 3:04 am said: Very useful and detailed. Thank you very much!
Dewan on July 14, 2015 at 6:23 am said: It’s so perfect! Thank you. This is helping me a lot.
Aelafseged on August 11, 2015 at 11:25 am said: So neat and to the point. I salute you for your Javaness!!!
Raul on November 9, 2015 at 8:47 pm said: Thank you very much! This is the first example that is simple and actually works!
Muhammad Mubeen on February 14, 2016 at 9:45 am said: How to create multiple swipe view? Can anyone help me please?
Christopher Geel in January 2018 said: Thanks buddy! This worked 100%
Author:Daniel S. Fowler Published: Updated:
|
https://tekeye.uk/android/examples/ui/a-swipe-view-android-example
|
CC-MAIN-2018-26
|
refinedweb
| 1,347
| 58.69
|
hana 0.1dev# Bloom
## Python modules
* pyyaml
* jinaj2
* markdown
* typogrify
## Configs
### site.yaml
* generator (optional; default Bloom.plugins.generators
full class and module name of a generator. If not specified, default publisher gets used
* publisher (optional)
full class name including module to used for publishing
* mode (optional)
freeform, generally development, production, etc
* content_root (optional; default content)
* base_url (optional; default /)
* media_root (optional; default media)
path is relative from content folder???
* media_url (optional; default /media)
url where media files are served from
* output_dir (optional; default output)
* authors
needs to have at least one author defined. Each author item needs at least name specified. Other optional parameters can be specified as desired
authors:
- author: mayo
- name: Mayo Jordanov
* meta file (optional, default meta.yaml)
* meta extension (optional, default meta.yaml)
my-article-stub.meta.yaml
### meta.yaml
* title (optional; first line of data file used as default)
* author (required)
keyed from site.yaml authors list
* created (optional; file created date used if not specified)
created timestamp. custom datatype with !!timestamp, can also be !!lookup, where the lookup value can be `fs` (filesystem lookup), or custom values from pluguns (mercurial, etc)
* modified (optional; file modified date used if not specified)
modified timestamp. see notes on `created`.
* any other yaml formatted data. lower level values over overlaid on top (ie. /content/meta.yaml[foo: test1, bar: test2], /content/dir/meta.yaml [bar: weee]. In /content, foo and bar meta values evaluate to test1 and test2 respectively. In /content/dir. foo evaluates to test1, bar evaluates to weee)
%%%%%%
- need to be able to override file extensions (article.md, .rst, etc)
%%%%%%
=========================
===========
Towel Stuff
===========
Towel Stuff provides such and such and so and so. You might find
it most useful for tasks involving <x> and also <y>. Typical usage
often looks like this::
#!/usr/bin/env python
from towelstuff import location
from towelstuff import utils
if utils.has_towel():
print "Your towel is located:", location.where_is_my_towel()
(Note the double-colon and 4-space indent formatting above.)
Paragraphs are separated by blank lines. *Italics*, **bold**,
and ``monospace`` look like this.
A Section
=========
Lists look like this:
* First
* Second. Can be multiple lines
but must be indented properly.
A Sub-Section
-------------
Numbered lists look like you'd expect:
1. hi there
2. must be going
Urls are and links can be
written `like this <http:"" foo="" bar="">`_.
- Author: Mayo Jordanov
- License: LICENSE.txt
- Package Index Owner: mayo
- DOAP record: hana-0.1dev.xml
|
https://pypi.python.org/pypi/hana/0.1dev
|
CC-MAIN-2016-36
|
refinedweb
| 403
| 52.26
|
MFi Game Controller Support
I bought a SteelSeries Stratus XL game controller for my new Apple TV today. I thought it would be fun to connect to it with Pythonista, but I ran into problems very quickly.
The whole thing seemed pretty straight forward. The objc_util package is fantastic, it is the first time I read the documentation. The GCController class should very easy to work with, especially since it should work well with only polling (I want to stay away from callbacks, handlers and blocks, at least at first):
So here we go!
from objc_util import * GCController = ObjCClass('GCController') controllers = GCController.controllers() print controllers
I expected to see an empty list when the controller was turned off, and a list with one element when the controller was on. Instead I got an error:
ValueError: no Objective-C class named 'GCController' found
I checked what classes are available. (This takes some time if anyone plans to run this code.)
from objc_util import * classes = ObjCClass.get_names() print classes
There are no classes starting with GC in the list. It would have been between 'FontSizeSliderCell' and 'GEOABExperimentAssignment'. I assume that is due to the fact that the "Game Controller Framework" is not linked into the Pythonista binary.
What a pity! I was kind of looking forward to building something to play with proper buttons. That would have been great fun.
So I assume we cannot use a controller unless @omz decides to add the "Game Controller Framework" to Pythonista. Or am I missing something?
Thanks @shaun-h! How did you figure that out?
I did a quick test, and it did load the framework. But then I just got an empty list when calling GCControllers.controllers() unfortunately. My wife stole the controller before I could try more things. I will check this out again soon though.
Thanks again!
I seem to be stuck again. I only get an empty list from GCController.controllers(), even though a controller is paired and connected.
It'll be some time, but next I'll try to do this in XCode and see what I get from the call. Unless someone else can figure out what's going on before that of course.
@Oscar I can't take credit, It was posted in the past by someone else and I kept the snippet stashed away.
I can't help you with the rest of it as I have never dealt with GCController before and don't have a controller to play with.
I would be very interested in how you go with it though.
Cheers
Are you able to test that the controller works in other iOS applications?
Also try reading through the apple documentation
You need to call
startWirelessControllerDiscoveryWithCompletionHandler_
And then stop the search after you have your controller.
@Cethric, I am pretty certain that you do not have to handle controller discovery in the app unless you want to.
"Although support for pairing is normally provided by the operating system (typically in the Preferences or Settings, you can use the Game Controller framework to pair devices inside your game. "
"Normally, discovery occurs outside your game—that is, a player usually pairs the controller before launching your game. However, you can let a player discover new controllers from within your game."
Still I tried using startWirelessControllerDiscoveryWithCompletionHandler, but that didn't make a difference. I might have made a mistake though, because the completion handler block was never called, not even after a call to stopWirelessControllerDiscovery.
I do not have a controller to test this with. How ever the controller should be showing up in system preferences (if it is a wireless controller, don't know about wired (lightening) controllers, but I would assume they should as well)
Have you tryed testing the controller in another application/game?
Also isn't there a tag that needs to go in the Application's plist file to say that it is allowed to connect to MFI Controllers? (I can't check this at the moment cause I am not at my computer)
@Cethric Yes, I made sure that the Controller was listed as connected in Settings, and that I could use it in another app.
I've looked around to find out if Game Controller support needs to be declared in the app plist. It seems to be true for tvOS apps, but I can't find anything about that for iOS. It would explain the behavior though.
I've run into the very same problem, unfortunately.
Now I can be sure that it's not my fault that it doesnt work :P
I have a suspicion that MFi controllers require that the app is actually linked against the GameController framework – could be an optimization to turn off controller communication while an app is running that doesn't support them or something like that... I don't have a controller to test this unfortunately, though controller support is something that I find potentially interesting as an addition to the scene module. I might buy one for testing at some point.
|
https://forum.omz-software.com/topic/2508/mfi-game-controller-support/11
|
CC-MAIN-2019-09
|
refinedweb
| 841
| 71.85
|
Investors in Raytheon Co. (Symbol: RTN) saw new options become available today, for the August 2nd expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the RTN options chain for the new August 2nd contracts and identified one put and one call contract of particular interest.
The put contract at the $172.50 strike price has a current bid of $4.25. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $172.50, but will also collect the premium, putting the cost basis of the shares at $168.25 (before broker commissions). To an investor already interested in purchasing shares of RTN, that could represent an attractive alternative to paying $173.69/share today.
Because the $172.99% annualized — at Stock Options Channel we call this the YieldBoost.
Below is a chart showing the trailing twelve month trading history for Raytheon Co., and highlighting in green where the $172.50 strike is located relative to that history:
Turning to the calls side of the option chain, the call contract at the $175.00 strike price has a current bid of $3.65. If an investor was to purchase shares of RTN stock at the current price level of $173.69/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $175.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 2.86% if the stock gets called away at the August 2 $175.00 strike highlighted in red:
Considering the fact that the $175.10% boost of extra return to the investor, or 15.34% annualized, which we refer to as the YieldBoost.
The implied volatility in the put contract example is 31%, while the implied volatility in the call contract example is 27%.
Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 251 trading day closing values as well as today's price of $173.69).
|
https://www.nasdaq.com/articles/interesting-rtn-put-and-call-options-august-2nd-2019-06-13
|
CC-MAIN-2020-45
|
refinedweb
| 347
| 66.23
|
from pymol import cmd from pymol.cgo import * # This example shows one way to create a plane behind the current # molecule. # # Note that because PyMOL's ray-tracer doesn't currently support # perspective, the plane will not look right if the edges are # showing. Thus, it is best to zoom the image so that the edges can't # be seen and that the plane appears infinite # # To use this script, setup your molecule and then "run cgo_plane.py". # This will create a plane in space about 80% of the way to the far # clipping plane. You can then rotate the camera around to get the # desired shadowing. # # If the plane is too close to the molecule, move the rear clipping # plane back and then re-run cgo_plane.py. # # NOTE that once the plane is created, there is no easy way to move it # (other than recreating it). However, you can move you molecule # relative to the plane using PyMOL's molecular editing features. # # (Remember, you can't click on cartoons, but you can click on ribbons). # # Good luck, # Warren view = cmd.get_view() # locate plane most of the way to the rear clipping plane plane_z = - (view[11] + (view[15]+5*view[16])/6.0) # choose the size of the plane plane_size = abs(view[11])/3.0 obj = [] # now create a plane in camera space plane = [ [ -plane_size, plane_size, plane_z ], [ plane_size, plane_size, plane_z ], [ -plane_size, -plane_size, plane_z ], [ plane_size, -plane_size, plane_z ]] normal = [ 0.0, 0.0, 1.0 ] # then transform plane coordinates into model space plane = map( lambda p,v=view: [ v[0] * p[0] + v[1] * p[1] + v[2]* p[2], v[3] * p[0] + v[4] * p[1] + v[5]* p[2], v[6] * p[0] + v[7] * p[1] + v[8]* p[2] ], plane ) normal = apply( lambda p,v=view:[ v[0] * p[0] + v[1] * p[1] + v[2]* p[2], v[3] * p[0] + v[4] * p[1] + v[5]* p[2], v[6] * p[0] + v[7] * p[1] + v[8]* p[2] ], (normal,) ) # and position relative to the camera plane = map( lambda p,v=view: [ p[0] + v[9 ] + v[12], p[1] + v[10] + v[13], p[2] + + v[14], ], plane ) # set color obj.extend( [ COLOR, 0.8, 0.8, 0.8 ] ) # greyish # begin triangle strip obj.extend( [ BEGIN, TRIANGLE_STRIP ] ) # set normal obj.append( NORMAL ) obj.extend( normal ) # draw the plane for a in plane: obj.append( VERTEX) obj.extend(a) obj.append( END ) # delete existing object (if any) cmd.delete("cgo_plane") # now load the new object without zooming auto_zoom = cmd.get('auto_zoom') cmd.set('auto_zoom', 0, quiet=1) cmd.load_cgo(obj,'cgo_plane') cmd.set('auto_zoom', auto_zoom, quiet=1)
|
http://pymol.sourcearchive.com/documentation/1.2r1-1/cgo__plane_8py-source.html
|
CC-MAIN-2018-17
|
refinedweb
| 443
| 65.93
|
21 March 2010
By clicking Submit, you accept the Adobe Terms of Use.
All
MXML files are ordinary XML files, so you have a wide choice of development environments. You can write MXML code in a simple text editor, a dedicated XML editor, or an integrated development environment (IDE) that supports text editing. Flex supplies a dedicated IDE, Adobe Flash Builder 4, that you can use to develop your applications.
The first line of the MXML file is the XML declaration. This line has to be the first line in each MXML file.
The next line is
<s:Application> tag, which defines the Application container that is always the root tag of a Flex application. The
<s:Application> tag specifies namespaces to use to resolve ActionScript classes. It also specifies additional layout information.
The
<s:Panel> tag defines a Panel container that includes a title bar, a title, a status message, a border, and a content area for its children. Its
title property is set to
"My Application". The Panel container also specifies a layout pattern and additional layout information.
The
<s:Label> tag represents a Label control, a very simple user interface component that displays text. Its
text property is set to
"Hello, World!".
The
fontWeight and
fontSize properties of the
<s:Label> tag change the style of the font used. There are many ways to apply styles to components in Flex 4. For more information, see About styles in the Adobe Flex 4 documentation.
Note: You can compile your Flex application by using the command-line compiler mxmlc, or by using Flex Builder 4. For instructions on compiling your application with mxmlc, see the Coding with MXML and ActionScript.
<?xml version="1.0" encoding="utf-8"?> <!-- HelloWorld.mxml --> <s:Application xmlns: <s:Panel <s:layout> <s:VerticalLayout </s:layout> <s:Label </s:Panel> </s:Application>
|
http://www.adobe.com/devnet/flex/quickstarts/your_first_app.html
|
CC-MAIN-2016-36
|
refinedweb
| 307
| 56.86
|
I am having a hard time with this.
Although am new here.
I am using Codeigniter, This is the query code.
<?php $is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'"); $check = $is_member->result_array(); if (in_array($id, $check)) { echo "Match found"; } else { echo "Match not found"; } ?>
Which outputs Match not found
but
print_r($check) gives
Array ( [0] => Array ( [user] => 1 ) [1] => Array ( [user] => 2 )
So how am I going to check if a specific integer is in the array which is multidimensional I think.
Note: $id = 1, which is clearly in the array, but it still saying not found.
Any answers? feel free to correct me if am doing something wrong
If you already know the ID you’re looking for and the room ID where you want to check, you might benefit from doing this:
(I’m assuming here that the room number is contained in
$row->id and the user ID you’re looking for is
$id)
$this->db->select('user'); $this->db->from('chatroom_members'); $this->db->where('room', $row->id); $this->db->where('user', $id); $query = $this->db->get(); return ($query->num_rows() == 0) ? false : true;
You’ll save yourself from looping through a huge result array (which may or may not be an issue depending on how large the resultset from the table is) and you’ll get a simple yes/no answer.
I used a
return and a ternary operator but you can easily change that to an if/else and do something else than return true or false depending on what you need.
Answer:
I think the best way to do it is having a foreach loop, in_array wouldn’t work on the root array.
<?php $is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'"); $arrays = $is_member->result_array(); $found = false; foreach ($arrays as $array) { if(in_array($id,$array)) { $found = true; break; } } echo $found === true ? "Match found" : "Match not found"; ?>
Tags: codeigniter, phpphp
|
https://exceptionshub.com/php-how-can-i-check-if-a-value-is-in-codeigniter-result_array.html
|
CC-MAIN-2021-10
|
refinedweb
| 323
| 58.01
|
Offline Files considers \\server.domain.com\share and \\server\share 2 independent namespaces. Win2K launches the Offline Files Wizard to walk you through the process. Even when multiple LAN connections are available to you, the Items to Synchronize dialog box doesn't specify which LAN connection you're using. Print reprints Favorite EMAIL Tweet Discuss this Article 10 PAVLA (not verified) on Dec 30, 2002 I wish the feature was profile - specific. get redirected here
Conflicts occur when you connect to multiple LANs. Troubleshooting Synchronization If only one user accesses particular files through the Offline Files feature, that user probably won't encounter a problem with synchronization. Right-click or Ctrl-click the clip in the Timeline, and select Link Media from the context menu. Working Offline and Synchronizing Changes As a user, when you log off the network or shut down your computer, you see a Synchronization reminder (assuming that you didn't configure Offline Files
The Offline tab allows you to view all your offline files together, or you can view them by account type. Handles reboots so you can install all hotfixes and have one reboot. Dropbox Business users If you have your personal and business accounts connected, you will be able to access all of the files you mark for offline access from the same tab. To ensure you have the latest versions, Dropbox will update them automatically if you're on a Wi-Fi network.
When another user modifies the network copy of a file while you (as a user) are working on the same file offline, a situation called file conflict occurs, and Win2K prompts When you work on the same network folder and you are about to disconnect from the network or you just disconnected, click on the Work offline button. When viewing the Control Panel by category, the Sync Center shortcut is not displayed in any of the available categories. Reset Offline Files Windows 10 In this article we will share what the Tablet Mode is, how to use it, how to...
IT recommends that you Log Off or Shut Down laptops when taking them from the office . Windows 7 Offline Files Sync Problems The Offline Files Folder also displays the path to each file's source folder—important information because the local system stores all offline files in one folder, even when they come from multiple Press Export. The sync will fail anyway.
when the computer has been idle for 15 minutes . Windows 7 Offline Files Not Syncing When you are connected again to the network, it will sync the files you have modified. What if you'd like your File Explorer to start in your OneDrive folder, your Dropbox folder, one of your... Specifically, making a file available offline: Adds the file to the app's Offline tab for easy access (like a bookmark) Saves the file to your iPhone or iPod Touch for offline
Files and folders usually are available for offline access to multiple users, in which case synchronization becomes more complicated. The problems are too numerous to mention! Offline Files Access Is Denied It will push to the server and pull from it. Clear Offline Files Cache Windows 7 With the computer connected to the network and Online I can see the two 0 KB files listed but anytime you try and access them (both PDFs) an error message shows as
After Working Offline, you may be asked to resolve file conflicts. Get More Info Then, Configure Offline Files Don’t be afraid to configure how Offline Files works on your computer. This is OK. All Rights Reserved.Home Redirected Folders + Offline Files + Access Denied = Bad Headache by JGatz on Mar 27, 2014 at 2:02 UTC | Windows Server Essentials & SBS Sync Failed With Offline Files Windows 7
None of the above solutions resolved the issue for me. Oddly this error only shows for those 6 files, all other files are syncing normally and without any problem. The permissions setup Desktop computers can have just the Synchronize all offline files before logging off check box selected. I used Total Commander; other similar applications should work well, too. Note: Other redirected folders that can be redirected "officially" did not negatively impact synchronization, e.g.
Tip: If you are having difficulty with staying "online" while in the office, verify that the computer has the correct AG Domain DNS & WINS Network Settings. Clear Offline Files Cache Windows 10 Windows IT Pro Guest Blogs Veeam All Sponsored Blogs Advertisement Join the Conversation Get answers to questions, share tips, and engage with the IT professional community at myITforum. But this manual sync will not do the full scan of files and folders for pinned and unpinned items.
By creating an account, you're agreeing to our Terms of Use, Privacy Policy and to receive emails from Spiceworks. Tried using the "Unlocker" program mentioned in some other forums to check if the file has any open handles. None were found, and yet the program can't delete the file. I Offline clips are represented by the 'Offline Item' icon in the project panel, and “Media Offline” appears in the timeline sequence, Program Monitor, and elsewhere as follows: Offline Clips displayed in Delete Offline Files Windows 10 A full sync can only happen at Log On or Log Off .
However, several users reported that when they looked at the files actually available offline (by starting Manage offline files and clicking View your offline files), they had files not only from To look directly at the file server a path must be used that is not configured to be available offline. Although the Scheduled Synchronization Wizard has an option to connect to the network automatically if you aren't already connected at the scheduled time, this option works only when you connect through this page Locating and linking offline files When you open a project with missing media files, the Link Media dialog box gives you visibility into files that have broken links and helps you
All this is scary, yes. Change regionUnited States (Change) Choose your region Selecting a region changes the language and/or content on Adobe.com. Unless you have an extremely large number of offline files or your offline files are very large, the synchronization process takes only a few seconds. Join Now After many days and many hours of frustration I have still yet to find an exact solution to my issue.
I have written and published 7 books, most of them about Microsoft products and technologies. Solution The free tool Run As System can start arbitrary processes as local system. Go to the On Idle tab to enable synchronization during computer idle times, then click Advanced to open the Idle Settings dialog box, which Figure 3 shows. If your computer has a Wireless card, disable it before you Log Off or Shut Down.
Manually locate and relink offline media You can manually find and reconnect the media that Premiere Pro is unable to automatically relink. Resolve File Conflicts You might never see one of these dialog boxes. Therefore, click on Manage offline files. Any thoughts or something I may be missing?
|
http://dlldesigner.com/offline-files/offline-files-computer-is-offline-error.php
|
CC-MAIN-2017-51
|
refinedweb
| 1,192
| 57.61
|
This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
look ! What's wrong with java in memory ?
Posted by harold bondz on August 17, 2001 at 2:12 PM
try the following program, it will throwa out of memory exception when it get about no more than 10M memory. ( it require 32 M )what's wrong with java!!!
class MType { int dummy;}public class MemTest { public static void main(String[] args) { int maxmsg = 8000000; MType[] msg = new MType[maxmsg]; for(int i= 0; i< maxmsg; i++) { if( i % 1000 == 0) System.out.println(i); msg[i] = new MType(); } }}
|
https://www.artima.com/legacy/answers/Aug2001/messages/100.html
|
CC-MAIN-2018-13
|
refinedweb
| 119
| 72.76
|
Class
In Microsoft .NET framework all the namespaces derived from
Object. The
System.Diagnostics namespace provides the information about the process state, start the new process, etc. In this namespace allows to starts the new process, kill process, etc..
ProcessStartInfo contains the following properties.
The arguments property use to set the argument in file name like
ShellExecute function.
The
FileName Property is used to set the application name . We can set this property before starting the process class.
If we set this is
True we can perform the file operations (like, printing the contents in that file). If we set
False we just execute the application.
We set and get the
WindowStyle in process starting time.
WaitForExit property is to wait for the process fora specified time.
For Example :-
Notepad->waitForExit(1000) // waits 1000 seconds.
Kill property is to kill the currently running process.
Ex :-
notePad->Kill();
The following code is to start the notepad. It waits 1000 secounds and kills it automatically using kill property in
Process class.
// Create Process Process *notePad = new Process(); // set the filename notePad->StartInfo->FileName = "notepad.exe"; // Arguments notePad->StartInfo->Arguments = "textfile.txt"; //Start the process notePad->Start(); // Wait for 1000 secounds notepad->waitForExit(1000); //Kill the process notepad->Kill();
The Process Thread contains information about the currently running process. We control the threads within the process. We set or get the thread proprieties like low, high. The Process Thread class contains the following properties.
The
BasePrority is used to get the priority.
The
CurrentPriority Class is to get the current priority
The
PriorityLevel is to Get or set the priority level
The
ThreadState is to get the current state
ProcessModuleclass.
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/mcpp/SelProcessInfo.aspx
|
crawl-002
|
refinedweb
| 284
| 60.51
|
I have two dataframes (df) A and B. df A has a column called 'Symbol' with non-unique stock-ticker-symbols as values in random order and the corresponding amount of buy or sell quantities in another column called 'Shares'; it is indexed by non-negative integers. df B, indexed by dates in the same date-order as df A and same number of rows as df A, has the same ticker symbols as df A as unique column names. I need to populate all df B rows with the amount of stock purchase or sell amounts from corresponding
A.Shares.values
join
import pandas as pd
bCN = B.dtypes.index # list of column names in df B to be used for populating its stock quantity based on matching values from df A
A = pd.DataFrame({'Date': ['2011-01-14', '2011-01-19', '2011-01-19'],
'Symbol': ['AAPL', 'AAPL', 'IBM'], 'Order':['BUY','SELL','BUY'],'Shares':[1500, 1500, 4000]}) #example of A
B = pd.DataFrame({'AAPL':[0,0,0],'IBM': [0,0,0], index = pd.date_range(start, end)}) #example of B
for index, row in A.iterrows():
for symbol in bCN:
if A['Symbol'][row] == symbol:
B[symbol][row] = A['Shares'][row]
first of all, I highly suggest you to read how-to-make-good-reproducible-pandas-examples
I think you could use pivot such has:
B = A.pivot('Date','Symbol','Shares')
Since image of dataframe are hard to copy paste I can't show you the exact result you could get using this method
|
https://codedump.io/share/TG2ZUUzfnirL/1/adding-values-from-a-dataframe-a-acolumn1-by-matching-values-in-acolumn2-to-the-bcolumn1-name-of-another-dataframe-b
|
CC-MAIN-2018-43
|
refinedweb
| 254
| 69.62
|
Details
- Type:
Improvement
- Status: Open
- Priority:
Minor
- Resolution: Unresolved
- Affects Version/s: Scala 2.10.0
- Fix Version/s: Scala 2.11.0-RC2
- Component/s: Specification
- Labels:None
- Environment:
Welcome to Scala version 2.10.0-20120501-234146-b27abca41a (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Description
This is edge-use-case, but:
scala> def m(a:Int,bs: =>Int*) = 7 <console>:1: error: ')' expected but identifier found. def m(a:Int,bs: =>Int*) = 7 ^ scala> def n(is: (=>Int)*) = 7 <console>:1: error: no by-name parameter type allowed here def n(is: (=>Int)*) = 7 ^ scala> def q(is: =>(Int *)) = 5 // not my intention <console>:1: error: no * parameter type allowed here def q(is: =>(Int *)) = 5
Am I the only one who experiences a cognitive hiccup every time I have to disambiguate "named parameter" and "by-name parameter?" Internally (to myself), I've started calling (denoting) params that have call-by-name semantics "eval params" because of the loose notion that they are evaluated on reference. ("Deferred params" conveys the idea that evaluation is deferred, but people get confused about deferred to when, especially under partial application, and deferred doesn't suggest multiple evaluation. I hope Paul reads this and has a better word for it – besides "evil params", of course.)
I haven't thought closely about this, except my terminology hangup, but the Seq[=>T] view might be a reason to ignore the use case.
Activity
spec clarification needed
more notes from the meeting: would be useful to have, but let's clarify it's disallowed for now. Can always implement once we've come up for air after 2.10.0
This might fall under the same rubric: var varargs. Given (var is: Int*), you can assign one Int, is=1, but not is=List(1,2,3). Also, someone wanted an implicit convert(Seq) to apply to a vararg, which is expected if vararg is type Seq inside the method. With respect to overloading (how to explain how it works), it was suggested the spec should talk about A* with the same reverence applied to =>A. (That is, a useful fiction.)
Note that the spec is unambiguous wrt this.
ParamType ::= Type
So it's clear they cannot be combined.
Unassigning and rescheduling to M7 as previous deadline was missed.
Apologies to those holding their breath. I will start working on spec cleanup as soon as RC1 is out the door. Promise.
Whew. It was my mistake to misread the spec when I was learning the language (specese, as it's been called). I thought this would make an interesting (at the time) contribution, but paulp's use case is obviated by other features (macros). By coincidence, I was just touching this production in my last PR, wondering if Int`*` is a good param type, with star as a regular identifier instead of some intermediate category.
Yes, the terminology we have to describe evaluation semantics is unreasonably impoverished. I have no better word, but if ambiguity is a concern I call by-name parameters thunks (whether that's an accurate use of that word or not, people at least tend to know what I mean.)
I have asked martin for by-name + varargs before, the use case I often encounter being logging - I'd really like to be able to write
def log(fmt: String, args: =>Any*) = if (logging) println(fmt.format(args: _*))
log("%s: %s %s", foo, bar, baz)
A single instance could serve to hold all three (or N) methods, something like
There was some objection which I no longer remember.
|
https://issues.scala-lang.org/browse/SI-5787
|
CC-MAIN-2014-10
|
refinedweb
| 603
| 61.06
|
I still cant get the code to work. Here is what I have
I dont know if this helps but the HAT I am trying to attatch is the MCC-118 from Measurement Computing Corporation. When I try to run the code I get these error messages:
Code: Select all
from sense_hat import SenseHat from datetime import datetime sense = SenseHat() def get_sense_data(): sense_data = [] return sense_data datetime.now() while True: print(get_sense_data()) dtoverlay=rpi-sense
Traceback (most recent call last):
File "/home/pi/Desktop/DAQ HAT.py", line 3, in <module>
sense = SenseHat()
File "/usr/lib/python3/dist-packages/sense_hat/sense_hat.py", line 39, in __init__
raise OSError('Cannot detect %s device' % self.SENSE_HAT_FB_NAME)
OSError: Cannot detect RPi-Sense FB device.
I read through a forum that I was directed to but since I dont have much coding experience, it was hard for me to get anything from it. The forum is here: ... p?t=173113
Any help is appreciated. Thanks!
|
https://www.raspberrypi.org/forums/viewtopic.php?f=31&t=248135&p=1514983
|
CC-MAIN-2020-50
|
refinedweb
| 160
| 65.83
|
If you enter any number into a calculator and repeatedly press the cosine key, you’ll eventually get 0.73908513, assuming your calculator is in radian mode [1]. And once you get this value, taking the cosine more times won’t change the number. This is the first example of a fixed point of an iteration that many people see.
Sam Walter posted a variation on the cosine fixed point problem on Twitter recently. If you add up the distance from each iteration value to the fixed point, the sum converges. Furthermore, if you consider this sum as a function of the starting point x, it defines a differentiable function of x.
I was curious what this function looks like, so I wrote the following Python code. First we find the fixed point.
from math import cos epsilon = 1e-16 x, cx = 1, cos(1) while abs(x - cx) > epsilon: x, cx = cx, cos(cx) alpha = x # fixed point
Now let’s evaluate the function described above.
def f(x): s = 0 cx = cos(x) delta = alpha - cx while abs(delta) > epsilon: s += delta x, cx = cx, cos(cx) delta = alpha - cx return s
Here’s what the plot of our function looks like.
As we’d expect, it crosses the x-axis at the fixed point.
If we sum the absolute distance to the fixed point at each iteration, we get the following function with a minimum at the fixed point.
Python’s new walrus operator
Incidentally, we can make the code slightly more compact if we take advantage of a new feature in Python 3.8, affectionately known as the “walrus operator.” The
:= operator lets you do assignments inside a loop test, among other places, much like is commonly done in C.
def f(x): s, cx = 0, cos(x) while abs(delta := alpha - cx) > 1e-16: s += delta x, cx = cx, cos(cx) return s
Now we don’t need to compute
delta before the loop, and we can update delta and check its absolute value in the same place.
I’m not sure how I feel about the walrus operator. It could make code easier to read or harder to read, depending on context.
One advantage of Python’s walrus over its C analog is that it prevents bugs due to typing
= when you mean to type
==. If you really want to do an assignment inside a Boolean test, you’ll need an extra character, the colon in front of the equal sign; using an ordinary equal sign alone is a syntax error.
More fixed point posts
- Kepler and the contraction mapping theorem
- Fixed points of the Cliff random number generator
- Logistic fixed points and bifurcations
[1] If your calculator is in degree mode, you’ll still get a fixed point, but the fixed point will be 0.99984774 degrees. Note that this is not simply the fixed point for cosine of an angle in radians, converted to degrees. Cosine of x degrees is a different function than cosine of x radians and it has a different fixed point.
|
https://www.johndcook.com/blog/2020/01/18/variation-on-cosine-fixed-point/
|
CC-MAIN-2022-40
|
refinedweb
| 513
| 67.89
|
Files changed (1)
- +69 -52src/main.cpp
src/main.cpp
- if (wmemcmp(arguments[0] + (name_len-9), L"-utf8.exe", 9) == 0 || wmemcmp(arguments[0] + (name_len-9), L"-UTF8.exe", 9) == 0) {
- //for native Win32 & full unicode support (well, cli arguments anyway), take whatever 16bit unicode windows gives (utf16le), and convert EVERYTHING
- //that is sends to utf8; use those utf8 strings (mercifully subject to familiar standby's like strlen) to pass around the program like getopt_long
- //to get cli options; convert from utf8 filenames as required for unicode filename support on Windows using wide file functions. Here, EVERYTHING = 350.
- UTF16LEToUTF8((unsigned char*) argv[z], 8*wchar_length, (unsigned char*) arguments[z], wchar_length*2);
} else if (argc == 2 && ((strncmp(argv[1],"-v",2) == 0) || (strncmp(argv[1],"-version",2) == 0)) ) {
- //a uuid in AP is a version 5 uuid created by getting a sha1 hash of a string (the atom name) in a namespace ('AP.sf.net'). This is guaranteed to be
- //reproducible, so later it can be verified that this uuid (which could come from anywhere), is in fact made by AtomicParsley. This is achieved by
- //storing the atom name string right after the uuid, and is read back later and a new uuid is created to see if it matches the discovered uuid. If
- //they match, it will print out or extract to a file; if not, only its name will be displayed in the tree.
- // --meta-uuid "�foo" 1 '' --meta-uuid "pdf1" file /some/path/pic.pdf description="My Booty, Your Booty, Djbouti"
if ( memcmp(argv[optind], "text", 5) == 0 || memcmp(argv[optind], "1", 2) == 0 ) uuid_dataType = AtomFlags_Data_Text;
- //The file was opened orignally as read-only; when it came time to writeback into the original file, that FILE was closed, and a new one opened with write abilities, so to close a FILE that no longer exists would.... be retarded.
+ UTF16LEToUTF8((unsigned char*) argv[z], 8*wchar_length, (unsigned char*) arguments[z], wchar_length*2);
|
https://bitbucket.org/wez/atomicparsley/commits/bb43f0b13e5c9014db56a643878c1d53b3f05cae?at=0.9.4
|
CC-MAIN-2014-15
|
refinedweb
| 323
| 64.95
|
Patent application title: EFFICIENT ELLIPTIC-CURVE CRYPTOGRAPHY BASED ON PRIMALITY OF THE ORDER OF THE ECC-GROUP
Inventors:
Erdinc Ozturk (Worcester, MA, US)
Vinodh Gopal (Westboro, MA, US)
Gilbert Wolrich (Framingham, MA, US)
Wajdi K. Feghali (Boston, MA, US)
IPC8 Class: AH04L930FI
USPC Class:
380 30
Class name: Cryptography particular algorithmic function encoding public key
Publication date: 2009-01-01
Patent application number: 20090003596
Abstract:
Time to perform scalar point multiplication used for ECC is reduced by
minimizing the number of shifting operations. These operations are
minimized by applying modulus scaling by performing selective comparisons
of points at intermediate computations based on primality of the order of
an ECC group.
Claims:
1. A method comprising:performing operations on points in an Elliptic
Curve Group (ECC) group having a k-bit National Institute of Standards
and Technology (NIST) generated modulus using an N-bit scaled modulus;
andupon detecting that the order of the ECC group is prime, skipping an
operation to reduce a point based on the scaled modulus to the NIST
generated modulus prior to performing a test to determine if the point is
at a point of infinity (O).
2. The method of claim 1, wherein the test checks point equality.
3. The method of claim 1, wherein the test checks point inverse.
4. The method of claim 1, wherein the operations on points uses a k-bit scalar d represented in non-adjacent form with each digit assigned a value -1, 0, or +1.
5. The method of claim 4, wherein the k-bit scalar d is converted to non-adjacent form using a pair of k-bit scalars (3d/2, d/2).
6. The method of claim 1, wherein N is 512.
7. The method of claim 1, wherein the N-bit scaled modulus is 64-bit aligned.
8. An apparatus).
9. The apparatus of claim 8, wherein the test checks point equality.
10. The apparatus of claim 8, wherein the test checks point inverse.
11. The apparatus of claim 8, wherein the operations on points uses a k-bit scalar d represented in non-adjacent form with each digit selected from the redundant set consisting of -1, 0 and +1.
12. The apparatus of claim 11, wherein the k-bit scalar d is converted to non-adjacent form using a pair of k-bit scalars (3d/2, d/2).
13. The apparatus of claim 8, wherein N is 512.
14. The apparatus of claim 8, wherein the N-bit scaled modulus is 64-bit aligned.
15. A system comprising:a dynamic random access memory to store data and instructions; anda processor coupled to said memory to execute the instructions, the processor).
16. The system of claim 15, wherein the test checks point equality.
17. The system of claim 15, wherein the test checks point inverse.
18. The system of claim 15, wherein the operations on points uses a k-bit scalar d represented in non-adjacent form with each digit selected from the redundant set consisting of -1, 0 and +1.
19. The system of claim 18, wherein the k-bit scalar d is converted to non-adjacent form using a pair of k-bit scalars (3d/2, d/2).
20. The system of claim 15, wherein N is 512.
Description:
FIELD
[0001]This disclosure relates to public key cryptography and in particular to elliptic curve cryptography.
BACKGROUND
[0002).
[0003.
[0004.
[0005).
[0006-1) times. Note that 1<=k<ord(P), where "ord" is defined as the order of the element of the group. Given P and [k]P, it is computationally infeasible to recover k.
BRIEF DESCRIPTION OF THE DRAWINGS
[0007]Features of embodiments of the claimed subject matter will become apparent as the following detailed description proceeds, and upon reference to the drawings, in which like numerals depict like parts, and in which:
[0008]FIG. 1 is a block diagram of a system that includes an embodiment of a Public Key Encryption (PKE) unit to perform computations for ECC;
[0009]FIG. 2 is a block diagram of an embodiment of a system that includes a public key encryption (PKE) unit;
[0010]FIG. 3 is a block diagram of an embodiment of the PKE unit shown in FIG. 2;
[0011]FIG. 4 is a block diagram illustrating the scaled modulus (M) and operands (A, B) according to the principles of the present invention;
[0012]FIG. 5 is a flow-chart illustrating a method for performing ECC operations according to an embodiment of the present invention.
[0013]FIG. 6 is a flow chart illustrating an embodiment of a method for reducing a result of a modular arithmetic operation performed with a scaled modulus M to a result based on an original modulus m; and
[0014]FIG. 7 is a flow diagram illustrating the computations performed for reducing the N-bit result modulo a k-bit modulus m.
[0015.
DETAILED DESCRIPTION
[0016.
[0017]Modular arithmetic such as modular multiplication (that is, r=x.y mod m) is typically used to perform computations for ECC. Many of the standard NIST ECC field sizes are not a multiple of 8-bits, for example, the NIST P-521 ECC curve. Thus, the operands used for performing point-addition and point-multiplication may be unaligned with an 8-bit aligned data path or multiplier. In a system having a data path that is a multiple of 8-bits, multiple shift operations are required to align operands (x, y) and the result of modular multiplication (r) to the data path.
[0018]Also, there are differences in the manner in which elliptic curves are defined over prime and binary fields. For example, for prime fields the ECC curve is defined by the equation:
Y2=X3+a.X+b
[0019]where a, b, X, Y are elements of the prime field (numbers modulo p).
[0020]For binary fields, the ECC curve is defined by the equation:
Y2+XY=X3+a.X2+b
[0021]where a, b, X, Y are elements of the binary Galois-field GF2m.
[0022]These differences make it challenging to support both prime and binary fields.
[0023]The basic building blocks of any cryptosystem are computations of the form Q=[k]P, that may be referred to as scalar point multiplication and can be defined as P added to itself (k-1) times. P is defined as a point (x, y) on the ECC curve having an order n and k is an integer that is an element of {1, n-1}. The problem of computing Q=[k]P is similar to group exponentiation. Q is computed in minimal steps when k is a large number using scalar point multiplication. Scalar point multiplication is performed through the use of point addition and point doubling. Point addition and point doubling requires a large number of shifting and multiply operations.
[0024]In an embodiment of the present invention, the number of shifting and multiply operations is optimized based on the primality of the order of the ECC group. When the order (n) of the ECC group is prime or when the order (n) of a point on the curve is known, performance of the scalar point multiplication operation is optimized. In other cases, partial checking is enabled as needed to optimize performance. Optimizing based on primality of the order of the ECC group, results in a significant performance increase and reduction in complexity. Performance may be optimized for prime (integer) fields in addition to binary fields and for other co-ordinate systems.
[0025]FIG. 1 is a block diagram of a system 100 that includes an embodiment of a Public Key Encryption (PKE) unit 108 to perform computations for ECC. The system 100 includes a processor 101, a Memory Controller Hub (MCH) 102 and an Input/Output (I/O) Controller Hub (ICH) 104. The MCH 102 includes a memory controller 106 that controls communication between the processor 101 and memory 110. The processor 101 and MCH 102 communicate over a system bus 116.
[0026.
[0027]The memory 110 may be Dynamic Random Access Memory (DRAM), Static Random Access Memory (SRAM), Synchronized Dynamic Random Access Memory (SDRAM), Double Data Rate 2 (DDR2) RAM or Rambus Dynamic Random Access Memory (RDRAM) or any other type of memory.
[0028]The ICH 104 may be coupled to the MCH 102 using a high speed chip-to-chip interconnect 114 such as Direct Media Interface (DMI). DMI supports 2 Gigabit/second concurrent transfer rates via two unidirectional lanes.
[0029).
[0030]FIG. 2 is a block diagram of an embodiment of a system 200 that includes a public key encryption (PKE) unit 108.
[0031]The system 200 includes a memory 202 for storing work requests 210 and a state machine (micro engine) 204 which processes the work requests 210. The state machine 204 issues instructions to the PKE unit 108 through a shared memory 206.
[0032.
[0033.
[0034.
[0035]The PKE unit 108 includes one or more modular math processors (MMP) 218 and a multiplier 216. The PKE unit 208 may perform modular arithmetic on large numbers. An example of modular arithmetic is a modular exponential operation such as, ge mod m where g is the base, e is the exponent and m is the modulus.
[0036]FIG. 3 is a block diagram of an embodiment of the PKE unit 108 shown in FIG. 2..
[0037]The PKE unit 108 performs computationally expensive mathematical computations such as modular exponentiation, division and greatest common divisor (gcd). The PKE unit 108 also includes a multiplier 216, which is shared by the MMPs 218a, 218b. In the embodiment shown, the multiplier 216 is a 512×512 multiplier.
[0038]Each MMP 218a, 218b includes a respective input First In First Out (FIFO) 322 and an output FIFO 324. The communication path through each MMP 218a, 218b is through the FIFOs 322, 324 by enqueuing data to the input FIFO 322 and dequeuing data from the output FIFO 324. The states of the MMPs 218a, 218b are independent from each other and each MMP 218a, 218b may be concurrently transferring data to/from shared memory 206 (FIG. 2) through the push-pull interface 306.
[0039]The multiplier 216 may be accessed via an internal PKE bus by the MMPs 218a, 218b and an arbitration mechanism that includes multiplexers 310, 312, 314 and 316 and associated multiplexer control logic (not shown). As the multiplier 216 is shared by the MMPs 218a, 218b, the arbitration mechanism controls which MMP 218a, 218b is currently using the multiplier 216.
[0040]The operand size for each MMP 218a, 218b is configurable through control logic/program store/state machine 330. In one embodiment the operand size may be configured to be 256 or 512 bits. The type of multiply operation is also configurable. In one embodiment, the type of multiply operation performed by the multiplier 216 for a particular MMP 218a, 218b may be unsigned integer or Galois Field (carry-less). Based on the configured operand size and multiply operation for a particular MMP 218a, 218b, the MMP 218a, 218b operates on the required length result vectors without explicit command encodings.
[0041]One of the MMPs 218a, 218b may perform scalar point multiplication that works efficiently for all prime ECC sizes<521 bits. The single shared multiplier 216 may work in one mode with MMP 218a and another mode with MMP 218b in an interleaved fashion. For example, MMP 218a may perform a binary ECC operation on 233 bit fields, thus requiring the multiplier to be set in 256 bits, Galois Field ({256b, GF*}) mode. MMP 218b may be operating on 384-bit prime ECC field, requiring the multiplier to be set in 512 bit, integer ({512b, int*}) mode; these operations are supported concurrently. Furthermore, each MMP may be configured to perform one of a plurality of reduction methods, such as, Barrett Reduction or Montgomery Reduction.
[0042]An ECC computation involves arithmetic operations on an elliptic curve over a finite field. A finite field consists of a finite set of elements. Addition and multiplication operations may be performed on pairs of field elements. There is one finite field containing q elements if and only if q is a power of a prime number. The order of a finite field is the number of elements in the field. A prime finite field is a field with q=p, where p is an odd prime, that is, the order of the finite field is prime because q is prime.
[0043]An ECC group has an order (that is, number of elements in the group) and every point in the ECC group also has an order (that is, the number of elements of the group that the point generates). If the order of the ECC group is prime, the order of the group is the same as the order of the point. For example, if the order of the group is 11 (a prime value), the group defined by addition modulo p=11 has 11 elements (0, . . . 10). Taking one of the points in the group, for example, 2 and performing addition by 2 mod p (with p=11), the point generates the points {4, 6, 8, 10, 1, 3, 5, 7, 9, 0, 2 . . . }, that is, 11 elements, where 1 is 12 mod 11 and 3 is 14 mod 11. However, if the order of the group is not prime, the order of the group and the order of a point in the group may not be the same. For example, if the order of the group is four in the group defined as addition modulo 4, and the point is 2, the point only generates 2 elements 0 and 2, so the order of the point is 2.
[0044]A positive integer having n+1 base b digits may be represented as a sum of multiples of base b, for example, if b is 2, n is 8 and a=1111011, then 1111011 may be represented as 1.26+1.25+1.24+1.23+0.22+1.21+1.20. Addition may be performed on two integers having the same number of base b digits. The product resulting from the multiplication of two integers x, y each having n base b digits has at the most 2n base b digits. Modular arithmetic includes modular addition and modular multiplication that is performed on integers modulo m, where m is a multiple-precision positive integer. The classical technique for performing modular multiplication is to compute x.y and then compute the remainder on division by m.
[0045]The elements of a prime finite field may be represented by the set of integers {0, 1, . . . , p-1} with addition defined as a+b=r mod p and multiplication defined as a.b=s mod p. The "mod p" refers to modulo p where r is the remainder when the integer result of a+b is divided by p. Barrett Reduction may be used to compute r mod p. However, when performing Barrett reduction with non-aligned field sizes in an 8-bit aligned datapath, alignment of various subvectors require a significant amount of shifting to align the operands and the result.
[0046]In an embodiment of the present invention, for an 8-bit aligned datapath and an N-bit multiplier, where N is 8-bit aligned, the modulus m is scaled to N bits. The k-bit operands are treated as N-bits. During intermediate stages of computation, intermediate results are partially reduced with respect to a scaled modulus M. At the end of the scalar point multiplication operation, the N-bit result is reduced to k-bits.
[0047]FIG. 4 is a block diagram illustrating a modulus (m) and operands (a, b) for use in a modular arithmetic operation. The modulus (m) and operands (a, b) each have k-bits. Modulus scaling is provided by scaling the value of modulus m to N-bits where N is greater than k and is selected dependent on the multiplier size which is a multiple of the 8-bit aligned data path size. For example, N is selected to be 512 for a 512-bit multiplier. The operands are not scaled, but are treated as N-bit operands instead of k-bit operands.
[0048]Modulus scaling is performed instead of operand scaling because as ECC computations involve many operands, operand scaling would have to scale many numbers, whereas modulus scaling is applied to only one number, that is, the modulus. This results in reducing the number of shifting operations during the main computations by performing one slower final transformation to the non-scaled original modulus.
[0049]The bit length of operand values a, b and modulus m is k-bits, k may be one of the NIST-recommended prime field sizes, for example, 192-bits, 224-bits, 256-bits, 384-bits or 521-bits. In one embodiment having a data path size of 64-bits and a 512-bit multiplier, N may be 512 or 256.
[0050]Instead of scaling the operands (a, b), the k-bit operands (a, b) are treated as N-bit operands by adding 0s to the Most Significant bits (MSB) that are greater than the (k+1)th bit of the N-bit operands (a, b). The modulus (m) is scaled to N-bits by shifting the modulus (m) to the left by N-k bits and setting the N-k Least Significant bits (LSB) of the N-bit scaled modulus M to `0`. In an embodiment in which N is 512-bits, the modulus m is scaled to 512-bits. In another embodiment in which N is 256-bits, the modulus is scaled to 256-bits.
[0051]The scalar point multiplication is performed with a modulus M to reduce the number of shift operations and the final result is scaled back to modulus m. During intermediate stages of computation, the numbers are partially reduced with respect to the scaled modulus. At the very end of the computation, the N-bit result is converted back to k-bits.
[0052]For example, the result of point multiplication (C) of operand A by operand B may be written as follows:
C=A.B mod m
[0053]Where the result C is the remainder upon dividing the product of A.B by m
[0054]After expanding the operands and result to mod M, the result (R) may be written as follows:
R=A.B mod M, [0055]where M>m and M=m2P; where P is the number of zeros added to shift (multiply by 2)
[0056]The result R is the remainder upon dividing the product of A.B by m.
[0057]Having computed R, the result C may be derived from the Result (R) that was computed using mod M as follows:
C=R mod m
[0058]The result C is the remainder upon dividing the result R by m.
[0059]Elliptic curve (ECC) point scalar multiplication is typically performed by performing point addition and point doubling operations. ECC point scalar multiplication may be performed to compute the result of Q=dP where d is an integer that is an element of {1, n-1} and P is a point (x1, y1) having an order n on the elliptic curve and Q is another point (x2, y2) on the elliptic curve. The order n of P is defined as the smallest integer which satisfies the equation: n*P=a point at infinity. If n is a prime number, the order of Q is equal to the order of P.
[0060]Point addition and point doubling operations over an ECC curve (group) have the properties shown in Table 1 below. The properties are described using a point P1 on the curve defined by co-ordinates x1, y1, a point P2 on the curve defined by co-ordinates x2, y2 and a point at infinity that is expressed as O.
TABLE-US-00001 TABLE 1 For point addition: x1 = x2 , y1 = y2 P1 = P2 , call point doubling. x1 = x2 , y1 = -y2 P1 = -P2 , P1 + P2 = O For point doubling: P1 = (x1, y1) y1 = 0 2*P1 = O
[0061]As shown above in Table 1, both point addition and point doubling require comparisons of respective (x, y) co-ordinates of two points P1, P2 on the ECC curve. For example, point doubling requires checking if y1=0 and point addition requires checking if point P1 is equal to point P2. These comparisons need to be performed using the non-scaled modulus m and thus require converting from the scaled modulus M to modulus m which requires bit shift operations with each bit shift operation consuming at least one processor clock cycle.
[0062]However, conversion of intermediate variables from the scaled modulus M to modulus m is not required when the order n of the ECC curve (group) is prime and the scalar d is in the range of [1 . . . n-1]. The order n of an ECC curve is the number of distinct points on the ECC curve, that is, n is the smallest integer that satisfies nG=point at infinity. When a scalar (integer) d is in the range of [1 . . . n-1], the point at infinity O is not reached after a single scalar point multiplication.
[0063]When n is prime, the order of Q is equal to the order of G, where Q=dG. Thus, when the order n of the ECC curve is known to be prime, a check to determine if the points to be added are equal is not required resulting in a further reduction in computation time. If the order n of the ECC curve is not a prime number, the modulus M is converted back to a residue modulo--the real modulus m for minimal intermediate variables.
[0064]FIG. 5 is a flow-chart illustrating a method for performing an ECC operation to compute d*G according to an embodiment of the present invention.
[0065]At block 500, the order n of G is checked to determine if it is a prime number. If so, processing continues with block 502.
[0066]At block 502, as n is a prime number, some checks for detecting if the point at infinity may be avoided. First the scalar d is expanded to modulus N, by expanding the scalar d to N-bits by adding 0s to the Least Significant Bits (LSB) as discussed in conjunction with FIG. 4. Processing continues with block 504.
[0067]At block 504, a check is performed to determine if the scalar d is equal to n-1. If d=n-1, then a subtraction operation may result in d hitting the point of infinity O. Thus, any method for performing scalar point multiplication that involves subtraction operations cannot be used. If scalar d is equal to n-1, processing continues with block 506. If not, processing continues with block 508.
[0068]At block 506, as the scalar d is equal to the order(n)-1, the result of d*G is -G and thus -G is returned based on the point addition rules discussed in conjunction with Table 1. Processing is complete.
[0069]At block 508, a scalar point multiplication operation is to be performed to compute d*G. As the order (n) of G is prime, a flag is set so that checks for point infinity are skipped when performing the scalar point multiplication operation. Processing continues with block 510.
[0070]At block 510, point multiplication to compute the result of scalar d multiplied by a point G having co-ordinates (x, y) is performed using point addition and point doubling operations as shown in Tables 2 and 3 below.
TABLE-US-00002 TABLE 2 Point addition: 1. d = (x1 - x2) 2. if (d <0) d = -d 3. if (d != 0) d' = d mod m 4. else d' = d 5. if (d' =0) a. d = (y1-y2) b. if (d<0) d = -d c. if (d != 0) d' = d mod m d. else d' =d e. if (d' =0) { P1 = P2 , call point doubling; return} f. d = (y1+y2) g. if (d<0) d = -d h. if (d != 0) d' = d mod m i. else d' =d j. if (d' =0) { P1 = -P2 , P1 + P2 = O, return O} 6. else return (P1 + P2)
TABLE-US-00003 TABLE 3 Point doubling: 1. if (y1 != 0) d' = y1 mod m 2. else d' = y1 3. if (d' =0) { 2*P1 = O; return O} 4. else return 2* P1
[0071]For point addition, if the order is a prime number, the checks in steps labeled the checks at 2, 3 and 5 are skipped. If the order is not prime, all of the checks are performed. Reduction modulo m may be performed in three places in the worst-case, however the conditional statement in at 5 (that is, if (d'=0)) is almost always false giving an average very close to 1, that is, the reduction at 3. The reduction modulo m at 3, 5c and/or 5h may be performed using a scale-invariant Barretts technique that does not require any shifting operations and is thus very fast. An embodiment of a scale-invariant Barrett Reduction will be described later in conjunction with FIG. 6.
[0072]Thus, for point addition, a check for point equality at 5e, that is to check if P1=P2 in order to determine if point doubling is to be performed and a check for point inverse at 5j, that is, to check if P1=-P2 in order to determine if P1+P2 is at the point of infinity (O) are only performed if the order of the ECC group is not known to be a prime number.
[0073]For point doubling, if the order of the ECC group is a prime number, the conditional statements at 1 and 3 are skipped. If the order of the ECC is not a prime number, the reduction modulo m needs to be performed in exactly one place for doubling if the y1 co-ordinate of point P1 is not equal to 0. If y1 is equal to 0, point doubling is performed that is, 2*P1. If y1 is equal to 0, the reduction modulo m is performed to check if the result of the reduction modulo m is 0.
[0074]Thus, by checking the primality of the order of the ECC group, that is, whether the order (n) is a prime number, a number of checks when performing point addition and point doubling in a scalar point multiplication operation on a scaled modulus M may be skipped.
[0075]Checks on the scaled co-ordinates are only performed if a user bit in the MMP is enabled to indicate that the point has an order that is not guaranteed to be prime. This allows use of the same operations shown in Tables 2 and 3 above for all cases. When an ECC curve (group) having an order that is a prime number is encountered the checking steps are skipped.
Processing continues with block 512.
[0076]At block 512, the result of the point multiplication is returned, processing is complete.
[0077]At block 514, the order n of G is not a prime number, a flag is set to indicate that checks are to be performed in the point addition and point doubling algorithms used to perform point multiplication. These checks result in a slower processing time due to the need to perform a reduction of the scalar d from the scaled modulus M to modulo m prior to performing checks to determine if the computed point is at point infinity.
[0078]In an embodiment of the present invention, computation time for performing a scalar point multiplication operation may be further reduced by decreasing the number of point addition and point doubling operations.
[0079]Scalar point multiplication may be performed using a bit-serial approach that is, starting from the Most Significant Bit (MSB) of the integer d. However, the number of point doublings and point additions for the scalar point multiplication may be reduced by using a signed digit representation, that is, d may be represented in signed digit representation with signed digits selected from the group of digits {-1, 0, 1}. One known signed digit representation is non-adjacent form (NAF).
[0080]In an embodiment of the invention, NAF is used to provide a signed digit representation of the integer d that is used for a scalar point multiplication operation to compute Q=dP. If a scalar d has n bits, NAF utilizes n point doublings and n/3 point additions. The number of point doublings is the same as a scalar point multiplication using a bit serial approach that starts from the most significant bit of scalar d. However, the number of point additions is reduced from an average of n/2 to n/3.
[0081]The scalar d is multiplied by 3 by performing a single left bit shift to provide 2d followed by an addition of d to 2d to provide 3d. Each bit of scalar d is compared with the respective bit of scalar 3d from bit position k+1 to 1 to determine the corresponding signed digit value as shown below in Table 4.
TABLE-US-00004 TABLE 4 (3d, d) Signed digit (0, 0) 0 (0, 1) -1 (1, 0) +1 (1, 1) 0
[0082]For example, if the values of the respective bits are equal, for example, (00) or (11), the signed digit representation is 0. However, if the values of the respective bits are not equal, the signed digit representation is -1 or +1 dependent on whether the value of the respective bit of 3d is 0 or 1.
[0083]Thus, Q=dP is computed by scanning bits in 3d/2 and d/2 from left to right, and determining whether to apply point doubling, point addition or point subtraction based on result of a comparison of the value of a respective bit in 3d/2 and d/2. If the value of each respective bit is equal, the P is doubled, if not equal, the point is doubled and then a subtraction or addition is performed on the doubled value dependent on whether the respective bit in 3d/2 is 1 or 0 as shown in Table 2.
[0084]By scanning the pair of scalars (3d, d) from bit position k+1 down to bit position 1, that is, ignoring the least significant bit (bit 0), scalars (3d/2,d/2) are scanned by scanning bit pairs from bit position k down to bit position 0. Using this optimization 3d/2 remains in the range of k-bits and an additional word is not required in order to store 3d/2, that is, the k-bit scalar d is converted to non-adjacent form using a pair of k-bit scalars (3d/2, d/2), that is, each scalar in the pair of scalars has k-bits each. These computations may be performed on-the-fly in the MMP 218a, 218b (FIG. 2).
[0085]Table 3 below illustrates an example of point multiplication for an 8-bit scalar d having a value `1011 01 10`. 2d is the result of shifting d to the left by one digit, that is, `101101100`. 3d is the result of adding d and 2d, that is, `1000100010`.
TABLE-US-00005 TABLE 5 1 0 1 1 0 1 1 0 (d) 1 0 1 1 0 1 1 0 (2d) 1 0 0 1 0 0 0 1 0 (3d)
[0086]A scalar point multiplication operation is performed on 3d/2 and d/2 by performing scalar point doubling and scalar point addition on the operands, that is, 3d/2 and d/2 starting with the respective Most Significant Bit (MSB) of each operand. 3d/2 and d/2 are computed by shifting the values of 3d and d to the right by one digit as shown in Table 6 below:
TABLE-US-00006 TABLE 6 1 0 0 0 1 0 0 0 1 (3d/2) 0 0 1 0 1 1 0 1 1 (d/2)
[0087]For example, starting with the MSB of 3d/2 and d/2, the MSB of 3d/2 is 1 and the MSB of d/2 is 0. Referring to Table 1, with (3d/2, d/2) equal to (1, 0) the result of the comparison corresponds to signed digit +1. Thus, for the MSB-1, both bits are 0, and point doubling is performed. Thus to compute Q=dP, with d="1011 0110", the scalar point multiplication is performed using the sequence of point doubling, point addition/subtraction operations shown in Table 7 below.
TABLE-US-00007 TABLE 7 1 0 0 0 1 0 0 0 1 (3d/2) 0 0 1 0 1 1 0 1 1 (d/2) +1 0 -1 0 0 -1 0 -1 0 1 2 3 6 12 23 46 91 182
[0088]As shown in Table 7, there are 5 point doublings (when respective bits are equal) and 4 point addition/subtraction (when respective bits are not equal) operations to perform the scalar point multiplication of Q=dP. The result of the scalar multiplication with d="1011 0110" is 182P. Thus, computation time for performing a scalar point multiplication operation Q=dP is reduced by reducing the number of point additions from an average of n/2 to n/3 where n is the number of digits in the scalar d.
[0089]FIG. 6 is a flow chart illustrating an embodiment of a method for reducing a result of a modular arithmetic operation performed with a scaled modulus M to a result based on an original modulus m.
[0090]After a result of a modular arithmetic operation has been computed with respect to the scaled modulus M, a final transformation is performed to reduce the result of the scalar multiplication with respect to the original modulus m.
[0091]Barrett reduction is a known method for reducing a first number (having 2k bits) modulo a second number (having k bits). Knowing that the k least significant digits of the 2k-bit first number are not necessary to compute a result, only a partial multiple-precision multiplication is necessary using a pre-computed constant g=floor(b2k/m), where b is the radix. If b is 2, then k is the number of bits in the first number and the second number.
[0092]Barrett Reduction computes a result r=X mod m as shown below in Table 8 where X, m and g are positive integers, X has 2k bits, m has k bits and μ=floor (22k/m).
TABLE-US-00008 TABLE 8 q1 = floor (X/bk-1) q2 = q1 * μ q3 = floor (q2/bk+1) r1 = X mod bk-1 r2 = q3 * mod bk+1 r = r1 - r2 if r < 0 then r = r + bk+1 while r >= m { r = r - m}
[0093]Barrett reduction shown in Table 8 may be applied to the result of a modular arithmetic operation such as scalar point multiplication with respect to an N-bit scaled modulus M. However, as the number of bits in original modulus m may not be N/2, Barrett reduction requires a large number of bit-shifting operations to extract and align various sub vectors.
[0094]Furthermore, Barrett Reduction as shown in Table 8 cannot be applied in the case in which a number of bits in an operand are less than half the number of bits of the modulus. For example, Barrett reduction as shown in Table 8 cannot be applied to a P-192 ECC curve defined by NIST with a scaled modulus M of 512 bits because 192 is less than half of the number of bits in the scaled modulus M, that is, 512/2 (256).
[0095]In an embodiment of the invention, the result of the scalar multiplication with respect to the scaled modulus M having N-bits is reduced to k-bits with respect to the modulus m where k is less than N through a scale invariant Barrett Reduction in order to avoid costly bit-level shifting operations.
[0096]Instead of computing μ=floor(b2k/m) as required by Barrett Reduction, a scaled reduction parameter μ is pre-computed using Equation 1 below:
μ=floor(2N/m) Equation 1
[0097]The scaled reduction parameter μ is used to compute the result (R) and may be computed using regular division which takes a fixed amount of time. The floor function is a mathematical function that returns the largest integer value less than or equal to (2N/m).
[0098]FIG. 7 is a flow diagram illustrating the computations performed for reducing the N-bit result modulo a k-bit modulus m. FIG. 7 will be described in conjunction with FIG. 6.
[0099]Referring to FIG. 6, at block 600, Q is computed using the pre-computed scaled reduction parameter μ and X which is an N-bit result to be reduced modulo a k-bit modulus m according to Equation 2 below.
Q=floor[(μ*X)/2N] Equation 2
[0100]The multiplication operation, that is, μ*X has N-bit operands and results in a 2N-bit product that needs to be reduced to a k-bit result. This enables the number of shift operations in the main computations in the ECC point operation (or a modular exponentiation) to be reduced. This is particularly useful in the context of ECC where field sizes (prime/binary) are not expected to be multiples of 64 (or even 32 in some cases) bits.
[0101]Referring to FIG. 6, X is stored at 700 and μ is stored at 702. In the embodiment shown N is 512. The number of bits in μ is dependent on the number of bits in modulo m. For example, if m is 384-bits, N is 512-bits and μ is 128 bits. The result of μ*X (512+128 bits) is stored at 704.
[0102]The least significant N-bits of the 2N-bit Q are not needed to compute the result, thus the most significant N-bits of the 2N-bit product of μ*X are selected at 606. In one embodiment, the most significant bits may be selected by using a pointer/scale adjustment in the MMP 218a, 218b to avoid shift operations. For example, the result of the multiply operation is 512*512=1024 bits which is represented as 16 quad-words (64-bits) in memory. Thus, the variable (full result) that points to the result is a quad-word pointer data structure with a reference count of 16. Ignoring the scale adjustment for simplicity, in order to extract the most-significant bits of the full result by skipping over the N least significant bits, a variable top_result is computed by adding 8 (that is, 256 bits (8×64 bits)) to the full result variable. This may be computed using a simple one-cycle instruction with no shifting/aligning required
[0103]Returning to FIG. 6, at block 602, after Q has been computed at 706 (FIG. 7), the result modulo m is computed iteratively through the use of subtraction operations to provide the remainder (R) mod m. On average the number of iterations is about one in contrast to the use of the standard Barrett Reduction which typically requires 2 or 3 iterations. The initial remainder (R) is computed using equation 3 below:
R=X-m*Q Equation 3
[0104]The multiplication operation, that is m*Q is performed with 512 bit operands shown at 706 (FIG. 7) and 708 (FIG. 7). X (at 600) is subtracted from result of the multiplication operation (at 710).
[0105]At block 604, the result R is compared with modulus m. The final remainder mod m is computed by subtracting m from the remainder (R) until the remainder is less than m as shown in the code snippet in Table 9 below:
TABLE-US-00009 TABLE 9 While (R > m) {R = R - m;}
[0106]If result R is greater than modulus m, processing continues with block 606 to subtract modulus m from the result R. If result R is not greater than modulus m, the final result R has been computed, processing is complete.
[0107]At block 608, the result R is returned. The computation of the result mod m may be used for integer fields or binary fields. In one embodiment, X is a 512 bit positive integer to be reduced modulo a k-bit modulus m where k is less than 512. In other embodiments M may be 2k with k selected such that the number of bits in M is greater than the number of bits in m.
[0108]For example, in an embodiment for a NIST curve having a 384-bit prime field and a 512-bit multiplier, M has 512 bits and m has 384 bits. Thus, substituting 2384 for m in Equation 1 above, μ is a 128-bit (512-384) value that is stored in a 512-bit field. The modulo 384-bit result is computed from the modulo 512-bit result using the operations shown in Equations 1-4 and Table 8 as discussed in conjunction with FIGS. 6 and 7.
[0109]Having pre-computed the 128-bit scaled reduction parameter value μ, the 128-bit μ is multiplied by 512-bit value X in the 512×512 multiplier to provide a 620-bit product. According to Equation 2, the Most Significant 512-bits of the 620-bit product are right shifted by 512-bits such that the Most Significant 128-bits of the 620-bit product are stored in the least significant 512-bits as Q. According to Equation 3, the 128-bit Q is multiplied by the 384-bit modulus m to provide a 512-bit product which is reduced to a 384-bit result by subtracting the 384-bit modulus m until the result is less than the 512-bit value X. This is achieved through the use of a single pointer addition operation, that is, no bit shifts are necessary. For example, first, m*Q is subtracted from X, and then m is iteratively subtracted as needed until the resulting remainder is less than m. The remainder after the subtraction operations is the 384-bit result.
[0110.
[0111.
Patent applications by Erdinc Ozturk, Worcester, MA US
Patent applications by Gilbert Wolrich, Framingham, MA US
Patent applications by Vinodh Gopal, Westboro, MA US
Patent applications by Wajdi K. Feghali, Boston, MA US
Patent applications in class Public key
Patent applications in all subclasses Public key
User Contributions:
Comment about this patent or add new information about this topic:
|
http://www.faqs.org/patents/app/20090003596
|
CC-MAIN-2014-23
|
refinedweb
| 7,127
| 57.2
|
#include <CGAL/Nef_polyhedron_S2.h>
An object
s of type
Sphere_segment is a segment in the surface of a unit sphere that is part of a great circle trough the origin.
Sphere segments are represented by two sphere points \( p\) and \( q\) plus an oriented plane \( h\) that contains \( p\) and \( q\). The plane determines the sphere segment as follows. Let \( c\) be the circle in the intersection of \( h\) and \( S_2\). Then \( s\) is that part of \( c\) that is swept, when we rotate \( p\) into \( q\) in counterclockwise rotation around the normal vector of \( h\) as seen from the positive halfspace.
creates a spherical segment spanning the shorter arc from
p1 to
p2 if
shorter_arc == true.
Otherwise the longer arc is created.
p1 != p2and
p1 != p2.opposite().
creates a spherical segment spanning the arc from
p1 to
p2 as part of the oriented circle
c (
p1 == p2 or
p1 == p2.opposite() are possible.)
p1and
p2are contained in
c.
creates the spherical segment as part of
c1 that is part of the halfsphere left of the oriented circle
c2.
c1 != c2as unoriented circles.
|
https://doc.cgal.org/4.7/Nef_S2/classCGAL_1_1Nef__polyhedron__S2_1_1Sphere__segment.html
|
CC-MAIN-2019-30
|
refinedweb
| 183
| 73.27
|
by Jeffrey Kantor (jeff at nd.edu). The latest version of this notebook is available at.
Demonstrate the use of a Bode plot for controller tuning. The notebook uses the Python Control Systems Library.
The process output $y$ is modeled as the output of a linear system described by the transfer function
$$y = G_p(s)G_v(s) u + G_d(s) d$$
where $G_p(s)$ is the process response to a manipulated variable, $G_v(s)$ is the transfer function of the actuator dynamics, and $G_d(s)$ is process response to a disturbance. The measured process output is given by
$$y_m = G_m(s) y$$
where $G_m(s)$ is the sensor transfer function. We assume the sensor has unit gain, i.e., $G_m(0) = 1$
The controller generates a command $u$ in response to the reference input $r$ and measured process output $y_m$. This is modeled as
$$u = G_r(s)r - G_y(s)y_m$$
where $G_r(s)$ and $G_y(s)$ are the controller transfer functions. Textbook simulations often set $G_r(s) = G_y(s)$ for PID control. In practice, however, it is generally desireable to avoid excessive action in response to setpoint changes, so generally $G_r \neq G_y$.
Below we employ a parallel implementation of PID control for output feedback where
$$G_y(s) = K_p\left[ 1 + \frac{1}{\tau_Is} + \frac{\tau_D s}{\alpha\tau_Ds + 1}\right]$$
where parameter $\alpha$ limits excessive derivative action. Typical values of $\alpha$ are in the range 0.2 to 0.1.
For the reference signal, $G_r(s)$ has the same general form but with additional parameters $\beta$ and $\gamma$
$$G_r(s) = K_p\left[ \beta + \frac{1}{\tau_Is} + \gamma\frac{\tau_D s}{\alpha\tau_Ds + 1}\right]$$
Commonly $\gamma = 0$ to avoid derivative action on the reference signal. Parameter $\beta$ is typically set to a value $0\leq\beta\leq 1$ that balances prompt response to a setpoint against undue 'kicks' caused by sudden changes in setpoint.
The overall response of the closed-loop system is characterized by a set of four transfer functions relating the reference and disturbance inputs to the process output $y$ and the control command $u$.
$$\begin{align*} y & = H_{yr}(s)r + H_{yd}(s)d \\ u & = H_{ur}(s)r + H_{ud}(s)d \end{align*} $$
The closed-loop transfer functions are given explicitly as
$$H_{yr} = \frac{G_pG_vG_r}{1 + G_pG_vG_yG_m}$$
$$H_{yd} = \frac{G_d}{1 + G_pG_vG_yG_m}$$
$$H_{ur} = \frac{G_r}{1 + G_yG_mG_pG_v}$$
$$H_{ud} = -\frac{G_yG_mG_d}{1 + G_yG_mG_pG_v}$$
where the argument $s$ has been suppressed for brevity.
We'll assume a process transfer function with time delay
$$G_p(s) = \frac{0.2}{s^2 + 1.5 s + 1}$$
and a disturbance response
$$G_d(s) = \frac{1}{s + 1}$$
and a measurement transfer function
$$G_m(s) = e^{-s}$$
We'll assume the dynamics of the actuator are negligible such that $G_v(s) = 1$.
The Python Control Systems Library does not provide a specific representation for time delay. It does, however, provide a function
pade for creating Pade approximations to time delay systems.
%matplotlib inline import numpy as np import matplotlib.pyplot as plt from control.matlab import * Gp = tf([0.2],[1, 1.5, 1]) print("Gp = ", Gp) Gd = tf([1],[1,1]) print("Gd = ", Gd) Gv = tf([1],[1]) print("Gv = ", Gv) (num,den) = pade(1.0,3) Gm = tf(num,den) print("Gm = ", Gm)
Gp = 0.2 --------------- s^2 + 1.5 s + 1 Gd = 1 ----- s + 1 Gv = 1 - 1 Gm = -s^3 + 12 s^2 - 60 s + 120 -------------------------- s^3 + 12 s^2 + 60 s + 120
w = np.logspace(-1,1) mag,phase,omega = bode(Gp*Gm*Gv,w) plt.tight_layout() # find the cross-over frequency and gain at cross-over) plt.plot([omega[0],omega[-1]],([omega[0],omega[-1]],[-180,-180],'r--') [pmin,pmax] = plt.ylim() plt.plot([wc,wc],[pmin,pmax],'r--') plt.title("Crossover Frequency = {0:.3g}".format(wc))
<matplotlib.text.Text at 0x1115d4518>
The conventional tuning rules for process control are written in terms of an ultimate gain $K_{cu}$ and ultimate period $P_u$. These are the values obtained by an experiment or calculation where the gain of a proportional only controller is increased until a steady closed-loop oscillation is first observed. The corresponding proportional gain is $K_{cu}$, and the period of oscillation is $P_u$.
These values may be computed from a Bode plot. The ultimate period corresponds to
$$P_u = \frac{2\pi}{\omega_c}$$
where $\omega_c$ is the cross-over frequency. The ultimate gain is then
$$K_{cu} = \frac{1}{G_p(\omega_c)}$$
where $G_p(\omega_c)$ is the open-loop process gain at the cross-over frequency.
Kcu = 1.0/gc Pu = 2.0*np.pi/wc
Kp = 0.6*Kcu tauI = Pu/2.0 tauD = Pu/8.0 print("Ziegler-Nichols PID Tuning") print("Kp = {0:0.3g}".format(Kp)) print("tauI = {0:0.3g}".format(tauI)) print("tauD = {0:0.3g}".format(tauD))
Ziegler-Nichols PID Tuning Kp = 5.97 tauI = 2.48 tauD = 0.621
from ipywidgets import interact, interactive, fixed import ipywidgets as widgets def f(alpha=0.1,beta=0.5,gamma=0.0,Kp=0.6*Kcu,tauI=Pu/2.0,tauD=Pu/8.0): # parallel implementation of PID control P = Kp * tf([1.0],[1.0]) I = (Kp/tauI) * tf([1.0],[1.0,0.0]) D = Kp*tauD * tf([1.0,0.0],[alpha*tauD,1.0]) # controller transfer functions Gr = beta*P + I + gamma*D Gy = P + I + D t = np.linspace(0,20,200) plt.figure(figsize=(12,6)) yr,t = step(Gp*Gv*Gr/(1+Gp*Gv*Gy*Gm),t) plt.subplot(2,2,1) plt.plot(t,yr) plt.plot(plt.xlim(),[1.0,1.0],'r--') plt.title('Setpoint Response') plt.ylabel('Output y') yd,t = step(Gd/(1+Gp*Gv*Gy*Gm),t) plt.subplot(2,2,2) plt.plot(t,yd) plt.plot(plt.xlim(),[0.0,0.0],'r--') plt.title('Disturbance Response') plt.ylabel('Output y') ur,t = step(Gr/(1+Gy*Gm*Gp*Gv),t) plt.subplot(2,2,3) plt.plot(t,ur) plt.plot(plt.xlim(),[0.0,0.0],'r--') plt.ylabel('Control u') ud,t = step(-Gy*Gd/(1+Gy*Gm*Gp*Gv),t) plt.subplot(2,2,4) plt.plot(t,ud) plt.plot(plt.xlim(),[0.0,0.0],'r--') plt.ylabel('Control u') plt.tight_layout() interact(f, alpha=fixed(0.1), Kp = (0.01*Kcu,Kcu), tauI = (Pu/20.0,Pu), tauD = (0.0,Pu), continuous_update=False)
<function __main__.f>
def h(a,b): print(a,b) def g(Controller): interact(h,a=12.2,b=3.) return interact(g, Controller=['P','PI','PID']);
12.2 3.0
|
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/Controller%20Tuning%20Rules%20in%20Frequency%20Domain.ipynb
|
CC-MAIN-2018-05
|
refinedweb
| 1,107
| 52.26
|
|
| HCG | Member-Confidential!
Registration is closed.
The W3C Hypertext Coordination Group will hold a meeting in Amsterdam, The Netherlands, on 20/21 November 2006, on the architecture of the proposed W3C Backplane.
Many W3C specifications use similar architectural features, such as the use of events, the idea of serializing and submitting values and dealing with replies, and so on.
In the context of multiple-namespace documents, or of user agents that deal with several markup languages, it is preferable if all markup languages used these facilities in the same way, so that for instance it is not necessary to have different serialization routines.
These ideas have been captured in a draft Hypertext Coordination Group Note, to which you should refer for more details.
This meeting is intended to further develop these ideas, identify other candidate architectural features for inclusion, and to develop a plan of action to achieve a W3C Backplane.
This work should be of interest to many working groups, and we especially encourage working groups within the Hypertext Coordination Group to arrange for at least one attendee, but the meeting is open to anyone from a W3C member company wishing to participate.
To participate you should send a statement of interest to the meeting committee at w3c-html-cg@w3.org. If you wish to present, please also send a position paper (may be as little as a single side) summarizing what you wish to say. Please register by 6 November 2006.
The meeting will be hosted by CWI and the Benelux Local Office of the W3C. There is no participation fee.
Kevin Kelly Charles Wiecha, IBM
Steven Pemberton, CWI/W3C
Address: Kruislaan 413, 1098 SJ Amsterdam. How to get there.
Time: 9:00-17:00 each day
Meals: Lunch wil be provided. Breakfast will not be available.
Connectivity: There will be a Wi-Fi network available.
Local host: Steven Pemberton, tel: +31 624 671 668
Best practice is to stay at a hotel in the centre of Amsterdam, and take tram 9 to the CWI (20 minutes tram, 10 minutes walk). There is a closer hotel to the CWI, but it is an uninteresting hotel in an uninteresting location, and still takes 20 minutes to get to the CWI.
See the results of the registration questionnaire to see the list of attendees.
There is the possibility of attending by phone. Zakim: +1.617.761.6200 code 2225 ("BACK")
IRC channel: irc.w3.org:6665#backplane
Backplane whitepaper
Evening: meal at De Waag (Amsterdam Centre)
Public proceedings of the meeting have been requested.
Brief summary
Monday
Tuesday
The Internet Guide to Amsterdam gives information about how to use transport, where to eat and drink, and where to go.
Last updated: $Date: 2007/01/19 14:04:47 $ by $Author: jigsaw $
|
http://www.w3.org/2006/11/backplane/
|
CC-MAIN-2015-32
|
refinedweb
| 462
| 53.61
|
Little Language
One spin-off of the
UnixDesignPhilosophy
was the realization that it is easier to implement a task-specific language optimized for that task than it is to implement a general-purpose language optimized for all possible uses. The
Little Language
title was given by
JonBentley
in the Communications of the ACM [Jon Bentley, "Little languages",
Communications of the ACM
, 29(8):711-21, August 1986.].
What Bell Labs did was to make separate languages for the tasks they found, and optimized them for those tasks. These tasks include:
Pattern matching (and thus
RegularExpression
s were born)
text line editing (ed/sed)
language grammar (lex/yacc)
Regex record data manipulation (AWK [
AwkLanguage
])
shell services (sh)
text formatting (troff/nroff); spawned multiple interacting little languages:
picture drawing (pic, IDEAL)
graph drawing (grap, dot,
GnuPlot
)
typesetting mathematics (eqn)
typesetting tables (tbl)
CHEM (chemical structures)
bib, refer (bibliographic notations)
dformat -- data structure/record format drawings
ptx (create permuted KWIC (keyword in context) index)
macro packages like mm, me, ms
incremental rebuilds (make)
preprocessing (cpp, m4)
arithmetic (dc [
DeeCee
], bc)
find (non-power users may not have noticed that it supports full boolean expressions over file attributes)
After UNIX left Bell Labs, more other little languages got added to it, including:
shell services (csh, ash, ksh, zsh, bash, tcsh, etc.)
file editing (vi) (vim and several other clones are now big)
sendmail CF configuration language (
TuringComplete
, I think, but obfuscated)
I know there are more. Could someone fill these in? Thanks.
Little Languages
have these characteristics:
may or may not be
TuringComplete
(see table below)
very efficient to execute (for example, sed scripts don't need to be tokenized; they already are.) both in terms of speed and memory (most cases) in their intended scope.
reasonably simple to express (
RegularExpression
s are simple enough to be concisely described on a single sheet 8 1/2"x11" paper, single spaced, 10 point font.)
very powerful, within their scope, frequently to the logical extreme of their scope.
pathologically cryptic, requiring users to become experts before using them
Some little languages are not designed with efficiency in mind at all. Instead, it's intended to save the developer time and effort by allowing her to express her intentions at a much higher level of abstraction. This allows the developer's programs to be much shorter than equivalent programs in other languages.
The "little" part primarily refers to the scope of what the language tackles. (For example, TeX is purely focused on typesetting, so it qualifies as a little language no matter how big the implementation).
Little Languages
are related to:
DomainSpecificLanguage
s: a little language is a kind of domain specific language in a very narrow domain.
MinimalistLanguage
, a language whose interpreter/compiler can be run on systems with very little RAM. Unfortunately, this typically requires user programs to be much longer than equivalent programs in other languages, as the user manually implements stuff the interpreter left out.
LowKeystrokeFormalLanguages
?
Below is a long discussion about the
TuringComplete
ness of the languages above. Let's summarize here what we know about the
TuringComplete
ness of the above:
RegularExpression
s: not TC, equivalent to
FiniteAutomata
, but is TC if match and replace and also repeats are allowed
ed/sed: TC (but data may be tricky to represent)
lex/yacc: not TC per se, equivalent to PushDownAutomata
?
(ContextFreeGrammars
?
)
AWK: TC
vi/ex: TC
sh: almost TC, only needs some way to manipulate data structures (dd is enough; dd/sh is even used to distribute CLC-INTERCAL)
troff/nroff: ?
TeX: TC
make: not TC, lacks means for representing data. Needs a shell to do anything.
cpp: some implementations are TC (but loops have to be written by #include'ing the current file)
m4: TC
dc/bc: TC (but data may be tricky to represent)
IDEAL: not TC
Other little languages:
"dc is the oldest language on Unix; it was written on the PDP-7 and ported to the PDP-11 before Unix [itself] was ported." (
KenThompson
)
Tcl "
ToolCommandLanguage
" ( see "little language" --
)
"SQL used to be a little language"
the Berkeley Packet Filter (BPF)
control languages for the BPF, such as OpenBSD's pf (
)
Would Jakarta Struts application configuration (struts-config.xml) be considered a little language?
Only if you consider every XML DTD to be a little language.
BitScope
?
RebolLanguage
???
REBOL isn't a little language itself, but it's designed for creating them. --Gregg Irwin
LOGO ???
Logo is a dialect of Lisp, but it's not a little language. The little language inside Logo is the one related to Turtle Graphics. --Gregg Irwin
In general,
LowKeystrokeFormalLanguages
tend to be LittleLanguages
?
Some
Little Languages
are
TuringComplete
. For example, I see no reason why somebody couldn't write a Universal
TuringMachine
interpreter in AWK to prove it. (If that sounds like too much work, you could simulate a URM machine - I would have thought the AWK associative arrays would be great for that.) how about a sed Universal
TuringMachine
? <
> -- (That's down, try
)
How about Lex/Yacc, TeX, and AWK?
A related sort of little language is the little language that isn't designed with efficiency in mind at all. Instead, it's intended to save the developer time and effort by allowing her to express her intentions at a much higher level of abstraction.
SQL used to be one of these, I think. Prolog and the various expert system shells also. The idea seems sadly quiescent these days; instead we're all standing around marvelling at bytecode, container libraries, and garbage collection as if these things somehow represented advances in the state of the art.
--
WilliamGrosso
Lex/Yacc, sure. TeX? Maybe at one time. It no longer seems very little to me anymore. I guess it still could fit, due to ancestry, but I personally would never list it. AWK? probably, though it's also growing. Part of my argument against AWK would be that most things people do in perl could also be done in AWK, and I would certainly not call perl little. AWK is admittedly smaller, and it was originally little (the version on the AIX box at work is easily a
Little Language
. The version on my Linux box at home probably isn't.
For the record: on my Linux box, sed is 35k, mawk is 88k, and gawk is 255k.
)
The size of the implementation code is not the point, especially given the Moore's Law side effect that most programs keep growing larger over time, whether they need to or not. Someone might implement any of these things (bc, ed, lex, tic tac toe) in a hundred billion line C++ program that requires a petabyte of RAM sometime in the future, but that wouldn't necessarily mean that it's no longer a "little language" (although it would certainly make the term ironic, and one would have to wonder if bc really needed a real-time ray tracer etc to draw the numerals in a pretty way)
The "little" part primarily refers to the scope of what the language tackles. TeX is purely focused on typesetting, so it qualifies as a little language no matter how big the implementation.
First of all, the
TuringTest
refers to an AI problem rather than computability.
TuringComplete
is framed in terms of mathematical operations on the integers {0,1,2,...} rather than in terms of machine words or whatever other data type you use in practice. (So long as your data types are finite, you could code them up as numbers and compute over them with functions.)
The fact that you can't write a device driver in AWK, or interface with a graphics system is irrelevant from the computability theory perspective. The argument would run like this:
Allowing for finite-space limitations, the computational problems solved by the device driver or graphics system are effectively computable. 2. Unix and its device drivers and graphics systems are effectively computable - so it is possible to write a universal
TuringMachine
program which emulates the Unix system and its device drivers.(I said it is possible, not that it's fun!)
Write a universal
TuringMachine
simulator in AWK.
Run the
TuringMachine
simulator in AWK, and load in the Unix emulator as data.
You end up having solved the graphics, operating systems and device driver computations solely using AWK. The fact that it's not practically feasible doesn't matter.
(An alternative strategy would be to produce a universal
TuringMachine
to AWK compiler rather than write the emulator.)
Then write a C compiler to target the UTM.
TuringComplete
is about being able to solve any effectively computable mathematical problem in a language - it's not about practical software architecture issues such as interfacing with device drivers. -- some guy
GregMcFarlane
?
wrote a set of macros to demonstrate that vi is
TuringComplete
; they're distributed as part of the standard vim distribution at
. AWK should be no problem; egrep probably isn't
TuringComplete
; Sed neither. Csh?
First, having been corrected on my misunderstanding of
TuringComplete
, I believe I've corrected the introductory description.
I'd say shells in general have problems - basically, shells are big
EscapeHatch
es; most of the shell's abilities are to run other programs, and they have very limited abilities on their own.
That being said, I would propose that ksh, bash, and zsh are probably
TuringComplete
, and Bourne Shell is definitely not
TuringComplete
.
Why do you think Bourne Shell is not
TuringComplete
?
Sed? Around 1992 or so,
KevinBraunsdorf
told me about a 100-line sed script written to do arbitrary-precision integer mathematics. It wasn't pretty, it apparently got sed banned from all future obfuscated code contests, but it apparently worked. Beyond putting fear into me (I'm not sure if it was because someone could do that in sed, or that someone did do that in sed, that scared me more) it made me decide to not doubt sed's computational abilities. --
EdGrimm
Here's a C++ program you can't write in sed:
#include <iostream> main() { for(;;) { cout << "foo" << endl; } return 0; }
Er, yes it can:
:loop s/.*/foo/p b loop
--
JimPerry
I found a proof of sed's turing completeness:
Look it's even shorter in sed!
>:)
A Little Language is designed for a specific task, and not for throwing at any computational task that comes along. As such, it usually has no need to be
TuringComplete
- at least, that is what is expected. But along comes a task that lies just on the wrong side of the border of its abilities, and the temptation to extend it a little bit to handle the edge case can be irresistible. If such a
LittleLanguage
ends up being
TuringComplete
then it's pretty much by accident, and the result is virtually guaranteed to be a particularly uncomfortable
TuringTarpit
.
If a
LittleLanguage
is designed from the outset to be
TuringComplete
then those borders don't exist and the pressure from that direction to extend the language is eliminated; it has a better chance of retaining what conceptual purity (coherent semantic model, robustness of implementation, etc.) it started out with, even if it is subsequently extended for other reasons. It may still be a
TuringTarpit
in the general case, but if you're working anywhere in the vicinity of its bailiwick, at least you won't suddenly run into an impossibility or gotcha.
For an example of an "accidentally TC"
LittleLanguage
I nominate sendmail; and for a deliberately TC
LittleLanguage
,
PostScript
.
It bothered me that a page on
Little Languages
should not contain a reference to
JonBentley
or
ProgrammingPearls
, so here they are. (Actually, Bentley's column on
Little Languages
appeared in the second collection,
MoreProgrammingPearls
.)
Also, I have the feeling that the idea of
LanguageAsInterface
is relevant (or that, if it isn't, it ought to be).
--
CameronSmith
"sed scripts don't need to be tokenized; they already are"
I've often read this but never known what it means. Would someone explain? --
AnonymousDonor
All sed commands are one byte long, not including arguments. --
EdGrimm
More languages than just sed have this property or a similar one. The qmail security guarantee talks about using this (and null-terminated lines) under the subject of parsing. dc is similar; there are only one and two character commands, some of which have a mandatory one character argument, and no two-character command overshadows a one character command except !.
If a little language is
TuringComplete
, many properties of program written in that language become undecidable: Such languages suffer from the
HaltingProblem
.
SQL is another well known little language that has no way to express loops nor recursion, and which is not
TuringComplete
.
But queries are a form of implicit looping over all records...
In fact,
I have written a SQL statement that did run forever reading a table with one row. - Joshua
Yes, there is queries looping over records (you can even make it access multiple tables and do a bunch of other stuff), and you can make it to do things with it by creating a trigger and then inserting into a read-only view that has that trigger attached. They can even be made recursive. You can even do conditionals (with a WHERE clause), and a lot of other stuff. Numeric loops are missing, although a virtual table provides that, so you can use that.
Keeping a little language declarative does have some advantages such as making it possible to use the scripts for multiple purposes (code generation, sanity checks, documentation, ...)
For those interested - see a paper I wrote in 1997 titled Little Languages: Little Maintenance? (it's on my homepage), which also discusses whether a little language should be
TuringComplete
. --
ArieVanDeursen
Also, the Berkeley Packet Filter (BPF), can be considered as a "little language". It is also decidedly turing-incomplete.
The basic
RebolLanguage
book describes it as a
MinimalistLanguage
. Implementations have a very small footprint. Is it appropriate to think of
Little Language
as a logical categorization of a language while
MinimalistLanguage
emphasizes the physical size of the implementation? --
DavidNess
OlinShivers
?
has a nice take on little languages at:
. He argues, that instead of little languages, we should use a single extensible language plus a lot of libraries. Why redesign things like variables and functions over and over?
Wasn't that the idea behind
ToolCommandLanguage
?
RegularExpression
s are also
TuringComplete
, if they get applied in turn until none of them matches. Actually, plain text substitutions suffice - they are an instance of SemiThueGrammars
?
. --
PanuKalliokoski
No...as phrased this isn't right. Plain old regular expressions, as you know, are not TC. Applying them in turn doesn't help, that's just (RE)*, another RE, and strictly speaking, it doesn't even matter if they're NDFA or DFA. What you must have meant to say is that regular expression match
and replace
is equivalent to a SemiThueGrammar
?
, since then you can have arbitrary RHS and LHS on each grammar rule. --
DougMerritt
By which point regular expressions have become overkill, since search-and-replace on plain substrings is sufficient to implement a Semi-Thue grammar.
So why are
LittleLanguage
s seen to be a good idea but
FourthGenerationLanguage
s seen to be a bad idea? The 4GLs I have used seemed to be collections of related
LittleLanguage
s.
4GL began as a technical term but was emptied of all meaning by marketroids back in the 1980s, so it currently tends to be considered to be marketing fluff unless proven otherwise. Nor is there a "fifth generation language" by which to contrast, despite the passage of time. Terminology trends change. "fourth generation" and "generation" in general used to be commonly applied to many things, not just languages, and now they are (mostly) not. The last usage I personally saw was Bentley calling awk a 4GL, and meaning that in a positive sense (which he described in detail).
Wasn't Prolog given the fifth generation tag by Japanese marketroids? -
ScottElliott
I forgot about that one. But I meant used
meaningfully
; the Japanese 5th generation label was empty in general, and there was no reason to apply that label to Prolog (except that it was the official language of their 5th Gen. project). "Fourth Generation" was once in a while used in a non-empty way.
One interesting thing about little languages is that they must interface to the world. When they do, it will usually display some awkwardness. Otherwise little languages are really nice.
Take a rather libre view of the classification of little languages, C is good at managing the memory, but some part of the world is better interfaced using OO, there comes the awkwardness of writing GUI applications in C.
Awk and sed are good at parsing flat files. When you want to parse EBNF using awk and sed, you would hate yourself. Yacc is for that.
A few more examples would be good.
When we talked about little languages, there must be mentioned that a good method for these little languages to interface with to the world is just equally important. In UNIX, that is the pipe. With pipe, the little languages can stay little.
The pipe is not perfect though, for it is unable to prevent people from inventing Perl. Or we could say that awk and sed is of no use to yacc and lex. When we want to parsing EBNF with another little language, the pipe can't let us utilize the other previously existing little languages. When we want to use a functional style to parse the EBNF instead of the C used in yacc, again we can not effectively utilize the yacc and lex but have to be forcef to implement our own yet another yacc in our own favorite functional language, ie. haskell etc.. The pipe cannot help us on that.
--
ZhaoWay
For a description of a possible class of
LittleLanguage
s in the
FlowBasedProgramming
context, see
.
FlowBasedProgramming
supports a network of "pipes", and so should be a great environment for hooking together different (types of)
LittleLanguage
s. --
PaulMorrison
Does
FurryScript
count? It is domain specific, and I think for mostly a narrow domain; it can be used with other stuff but not very well. What about,
DadaEngine
and rmutt, which have some similar purposes (even though none of them was based on the other)?
Is
MusicMacroLanguage
(MML) a
LittleLanguage
?
See Minilanguages: Finding a Notation That Sings
See also
DomainSpecificLanguage
s,
MinimalParsing
,
HelpersInsteadOfWrappers
CategoryLanguage
View edit of
September 28, 2014
or
FindPage
with title or text search
|
http://c2.com/cgi/wiki?LittleLanguage
|
CC-MAIN-2015-35
|
refinedweb
| 3,085
| 52.49
|
Notice:
The steps involved in establishing a socket on the server side are as follows:
When a socket is created, the program has to specify the address domain and the socket type. Two processes can communicate with each other only if their sockets are of the same type and in the same domain.
There are two widely used address domains, the unix domain, in which two processes which share a common file system communicate, and the Internet domain, in which two processes running on any two hosts on the Internet communicate. Each of these has its own address format.
The address of a socket in the Unix domain is a character string which is basically an entry in the file system.
The address of a socket in the Internet domain consists of the Internet address of the host machine (every computer on the Internet has a unique 32 bit address, often referred to as its IP address).In addition, each socket needs a port number on that host.Port numbers are 16 bit unsigned integers. The lower numbers are reserved in Unix for standard services. For example, the port number for the FTP server is 21. It is important that standard services be at the same port on all computers so that clients will know their addresses. However, port numbers above 2000 are generally available.
There are two widely used socket types, stream sockets, and datagram sockets. Stream sockets treat communications as a continuous stream of characters, while datagram sockets have to read entire messages at once. Each uses its own communciations protocol.
Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented protocol, and datagram sockets use UDP (Unix Datagram Protocol), which is unreliable and message oriented.
The examples in this tutorial will use sockets in the Internet domain using the TCP protocol.
C code for a very simple client and server are provided for you. These communicate using stream sockets in the Internet domain. The code is described in detail below. However, before you read the descriptions and look at the code, you should compile and run the two programs to see what they do.
server.cclient.c
Download these into files called server.c and client.c and compile them separately into two executables called server and client.
server.c
client.c
server
client
They probably won't require any special compiling flags, but on some solaris systems you may need to link to the socket library by appending -lsocket to your compile command.
-lsocket
Ideally, you should run the client and the server on separate hosts on the Internet. Start the server first. Suppose the server is running on a machine called cheerios. When you run the server, you need to pass the port number in as an argument. You can choose any number between 2000 and 65535. If this port is already in use on that machine, the server will tell you this and exit. If this happens, just choose another port and try again. If the port is available, the server will block until it receives a connection from the client. Don't be alarmed if the server doesn't do anything;
cheerios
It's not supposed to do anything until a connection is made.
Here is a typical command line:
server 51717
To run the client you need to pass in two arguments, the name of the host on which the server is running and the port number on which the server is listening for connections.
Here is the command line to connect to the server described above:
client cheerios 51717
You can simulate this on a single machine by running the server in one window and the client in another. In this case, you can use the keyword localhost as the first argument to the client.
localhost
The server code uses a number of ugly programming constructs, and so we will go through it line by line.
#include <stdio.h>
This header file contains declarations used in most input and output and is typically included in all C programs.
#include <sys/types.h>
This header file contains definitions of a number of data types used in system calls. These types are used in the next two include files.
#include <sys/socket.h>
The header file socket.h includes a number of definitions of structures needed for sockets.
#include <netinet/in.h>
The header file in.h contains constants and structures needed for internet domain addresses.
void error(char *msg)
{ perror(msg); exit(1);}
stderr
int main(int argc, char *argv[]){ int sockfd, newsockfd, portno, clilen, n;
sockfd
newsockfd
portno stores the port number on which the server accepts connections.
portno
clilen stores the size of the address of the client. This is needed for the accept system call.
clilen
n is the return value for the read() and write() calls; i.e. it contains the number of characters read or written.
n
read()
write()
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
sockaddr_in
netinet/in.h
Here is the definition:
struct sockaddr_in{ short sin_family; /* must be AF_INET */ u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; /* Not used, must be zero */};
in_addr
s_addr
The variable serv_addr will contain the address of the server, and cli_addr will contain the address of the client which connects to the server.
serv_addr
cli_addr
if (argc < 2) { fprintf(stderr,"ERROR, no port provided"); exit(1); }
sockfd = socket(AF_INET, SOCK_STREAM, 0);if (sockfd < 0) error("ERROR opening socket");
socket()
Recall that there are two possible address domains, the unix domain for two processes which share a common file system, and the Internet domain for any two hosts on the Internet. The symbol constant AF_UNIX is used for the former, and AF_INET for the latter (there are actually many other options which can be used here for specialized purposes).
AF_UNIX
AF_INET
The second argument is the type of socket. Recall that there are two choices here, a stream socket in which characters are read in a continuous stream as if from a file or pipe, and a datagram socket, in which messages are read in chunks. The two symbolic constants are SOCK_STREAM and SOCK_DGRAM.
SOCK_STREAM
SOCK_DGRAM
The third argument is the protocol. If this argument is zero (and it always should be except for unusual circumstances), the operating system will choose the most appropriate protocol. It will choose TCP for stream sockets and UDP for datagram sockets.
The socket system call returns an entry into the file descriptor table (i.e. a small integer). This value is used for all subsequent references to this socket. If the socket call fails, it returns -1.
In this case the program displays and error message and exits. However, this system call is unlikely to fail.
This is a simplified description of the socket call; there are numerous other choices for domains and types, but these are the most common. The socket() man page has more information.
bzero((char *) &serv_addr, sizeof(serv_addr));
bzero()
portno = atoi(argv[1]);
atoi()
serv_addr.sin_family = AF_INET;
struct sockaddr_in
short sin_family
serv_addr.sin_port = htons(portno);
unsigned short sin_port
htons()
serv_addr.sin_addr.s_addr = INADDR_ANY;
struct in_addr
unsigned long s_addr
INADDR_ANY
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding");
bind()
sockaddr
listen(sockfd,5);
listen
clilen = sizeof(cli_addr);newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);if (newsockfd < 0) error("ERROR on accept");
accept()
bzero(buffer,256);n = read(newsockfd,buffer,255);if (n < 0) error("ERROR reading from socket");printf("Here is the message: %s",buffer);
It will read either the total number of characters in the socket or 255, whichever is less, and return the number of characters read. The read() man page has more information.
n = write(newsockfd,"I got your message",18);if (n < 0) error("ERROR writing to socket");
return 0;}
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>
netdb.h
hostent
void error(char *msg){ perror(msg); exit(0);}int main(int argc, char *argv[]){ int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server;
error()
sockfd, portno
The variable server is a pointer to a structure of type hostent. This structure is defined in the header file netdb.h as follows:
struct hostent{ char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses from name server */ #define h_addr h_addr_list[0] /* address, for backward compatiblity */};
h_name Official name of the host.h_aliases A zero terminated array of alternate names for the host.h_addrtype The type of address being returned; currently always AF_INET.h_length The length, in bytes, of the address.h_addr_list A pointer to a list of network addresses for the named host. Host addresses are returned in network byte order.
h_addr
char buffer[256];if (argc < 3){ fprintf(stderr,"usage %s hostname port", argv[0]); exit(0);}portno = atoi(argv[2]);sockfd = socket(AF_INET, SOCK_STREAM, 0);if (sockfd < 0) error("ERROR opening socket");
server = gethostbyname(argv[1]);if (server == NULL){ fprintf(stderr,"ERROR, no such host"); exit(0);}
argv
cs.rpi.edu
struct hostent *gethostbyname(char *name)
The field char *h_addr contains the IP address.
char *h_addr
If this structure is NULL, the system could not locate a host with this name.
In the old days, this function worked by searching a system file called /etc/hosts but with the explosive growth of the Internet, it became impossible for system administrators to keep this file current. Thus, the mechanism by which this function works is complex, often involves querying large databases all around the country. The gethostbyname() man page has more information.
/etc/hosts
bzero((char *) &serv_addr, sizeof(serv_addr));serv_addr.sin_family = AF_INET;bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);serv_addr.sin_port = htons(portno);
server->h_addr
void bcopy(char *s1, char *s2, int length)
length
s1
s2
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting");
connect
Notice that the client needs to know the port number of the server, but it does not need to know its own port number. This is typically assigned by the system when connect is called.",buffer); return 0;}
fgets
The sample server code above has the limitation that it only handles one connection, and then dies. A "real world" server should run indefinitely and should have the capability of handling a number of simultaneous connections, each in its own process. This is typically done by forking off a new process to handle each new connection.
The following code has a dummy function called dostuff(int sockfd).
dostuff(int sockfd)
This function will handle the connection after it has been established and provide whatever services the client requests. As we saw above, once a connection is established, both ends can use read and write to send information to the other end, and the details of the information passed back and forth do not concern us here.
read
write
To write a "real world" server, you would make essentially no changes to the main() function, and all of the code which provided the service would be in dostuff().
dostuff()
To allow the server to handle multiple simultaneous connections, we make the following changes to the code:
fork()
#dostuff
Here is the code.
while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); pid = fork(); if (pid < 0) error("ERROR on fork"); if (pid == 0) { close(sockfd); dostuff(newsockfd); exit(0); } else close(newsockfd); } /* end of while */
The above code has a problem; if the parent runs for a long time and accepts many connections, each of these connections will create a zombie when the connection is terminated. A zombie is a process which has terminated but but cannot be permitted to fully die because at some point in the future, the parent of the process might execute a wait and would want information about the death of the child. Zombies clog up the process table in the kernel, and so they should be prevented. Unfortunately, the code which prevents zombies is not consistent across different architectures. When a child dies, it sends a SIGCHLD signal to its parent. On systems such as AIX, the following code in main() is all that is needed.
wait
main()
signal(SIGCHLD,SIG_IGN);
void *SigCatcher(int n){ wait3(NULL,WNOHANG,NULL);}...int main(){ ... signal(SIGCHLD,SigCatcher); ...
SigCatcher()
wait3
This example showed a stream socket in the Internet domain. This is the most common type of connection. A second type of connection is a datagram socket. You might want to use a datagram socket in cases where there is only one message being sent from the client to the server, and only one message being sent back. There are several differences between a datagram socket and a stream socket.
sendto()
receivefrom()
These two programs can be compiled and run in exactly the same way as the server and client using a stream socket.
Most of the server code is similar to the stream socket code. Here are the differences.
sock=socket(AF_INET, SOCK_DGRAM, 0);
fromlen = sizeof(struct sockaddr_in);while (1){ n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen); if (n < 0) error("recvfrom");
listen()
recvfrom()
read()
n = sendto(sock,"Got your message",17, 0,(struct sockaddr *) &from,fromlen); if (n < 0) error("sendto"); }}
sockadd_in
The client code for a datagram socket client is the same as that for a stream socket with the following differences.
connect()
recvfrom
sendto
Here is the code for a client and server which communicate using a stream socket in the Unix domain.
U_server.c
U_client
The only difference between a socket in the Unix domain and a socket in the Internet domain is the form of the address. Here is the address structure for a Unix Domain address, defined in the header file.
struct sockaddr_un{ short sun_family; /* AF_UNIX */ char sun_path[108]; /* path name (gag) */};
sun_path
ls
There are a number of different ways to design servers. These models are discussed in detail in a book by Douglas E. Comer and David L. Stevens entiteld Internetworking with TCP/IP Volume III:Client Server Programming and Applications published by Prentice Hall in 1996. These are summarized here.
Concurrent, connection oriented servers
The typical server in the Internet domain creates a stream socket and forks off a process to handle each new connection that it receives. This model is appropriate for services which will do a good deal of reading and writing over an extended period of time, such as a telnet server or an ftp server. This model has relatively high overhead, because forking off a new process is a time consuming operation, and because a stream socket which uses the TCP protocol has high kernel overhead, not only in establishing the connection but also in transmitting information. However, once the connection has been established, data transmission is reliable in both directions.
Iterative, connectionless servers
Servers which provide only a single message to the client often do not involve forking, and often use a datagram socket rather than a stream socket. Examples include a finger daemon or a timeofday server or an echo server (a server which merely echoes a message sent by the client). These servers handle each message as it receives them in the same process. There is much less overhead with this type of server, but the communication is unreliable. A request or a reply may get lost in the Internet, and there is no built-in mechanism to detect and handle this.
Single Process concurrent servers
A server which needs the capability of handling several clients simultaneous, but where each connection is I/O dominated (i.e. the server spends most of its time blocked waiting for a message from the client) is a candidate for a single process, concurrent server. In this model, one process maintains a number of open connections, and listens at each for a message. Whenever it gets a message from a client, it replies quickly and then listens for the next one. This type of service can be done
with the select system call.
|
http://linuxhowtos.org/C_C++/socket.htm
|
CC-MAIN-2018-05
|
refinedweb
| 2,682
| 61.56
|
Under Tapestry, a component template is a file that contains the markup for a component.
Component templates are well formed XML documents. That means that every open tag must have a matching close tag, every attribute must be quoted, and so forth.
Note:: Component Templates
Templates are handled.). are the most common (X)HTML doctypes:
<!DOCTYPE html> <" "">
The first one is for HTML5 and is recommended for Tapestry 5.2.5 and later. In versions prior to Tapestry 5.2.5, Tapestry didn't support the HTML5 doctype directly (but see the comments at TAP5-1040 for a work-around).
The Tapestry Namespace.
For backwards compatibility, you may continue to use the old namespace URIs:; 5_3.xsd and 5_4.xsd are identical.. in the
items list, with each <tr> including three <td> elements. It will also write a dynamic "class" attribute into each <tr>.
Parameter Namespaces
Main Article: Component Templates and Chrome Developer Tools.
Template Inheritance.>
|
https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=75964315
|
CC-MAIN-2019-30
|
refinedweb
| 156
| 62.24
|
lighterhtmllighterhtml
The hyperHTML strength & experience without its complexity 🎉
faster than hyperHTMLfaster than hyperHTML
Even if sharing 90% of hyperHTML's code, this utility removed all the not strictly necessary parts from it, including:
- no
Component, no
defineand/or intents, no
connector
disconnect, and no promises (possibly in later on), everything these days can be easily handled by hooks, as example using the dom-augmentor utility
- html content is never implicit, since all you have to do is to write
htmlbefore any template when you need it. However, the
{html: string}is still accepted for extreme cases.
Removing these parts made the output smaller in size (less than 6K) but it also simplified some underlying logic.
Accordingly, lighterhtml delivers raw domdiff and domtagger performance in an optimized way.
If you don't believe it, check the DBMonster benchmark 😉
simpler than lit-htmlsimpler than lit-html
In lit-html, the
html function tag is worthless, if used without its
render.
In lighterhtml though, the
html tag can be used in the wild to create any, one-off, real DOM, as shown in this pen.
// lighterhtml: import the `html` tag and use it right away;// a one off, safe, runtime list 👍const list = 'some' '<b>nasty</b>' 'list';documentbody;
Strawberry on top, when the
html or
svg tag is used through lighterhtml
render, it automatically creates all the keyed performance you'd expect from hyperHTML wires, without needing to manually address any reference: pain point? defeated! 🍾
"but ... how?", if you're asking, the answer is simple: lighterhtml is based on the same augmentor's hooks concept, followed by automatically addressed hyperhtml-wires, which in turns brings a battle tested solution for the O(ND) Eugene W. Myers' Algorithm based domdiff, and its extra variations.
Available as lighterhtml-plus too!Available as lighterhtml-plus too!
Born just as own fork of this project,
lighterhtml-plus enhances the HTML5 experience through these extras:
onconnectedcallback, as in hyperHTML, to have Custom Elements like callbacks
ondisconnectedcallback, as in hyperHTML, to have counter events when nodes get disconnected
onattributechangedcallback, as in wickedElements, to have attributes change notifications, Custom Elements like
How to import lighterhtml/-plusHow to import lighterhtml/-plus
Following, the usual multi import pattern behind every project of mine:
- via global
lighterhtmlCDN utility:
<script src=""></script>, and
const {render, html, svg} = lighterhtml
- via ESM CDN module:
import {render, html, svg} from ''
- via ESM bundler:
import {render, html, svg} from 'lighterhtml'
- via CJS module:
const {render, html, svg} = require('lighterhtml')
What's the API ? What's in the export ?What's the API ? What's in the export ?
The module exports the following:
htmltag function, create as one-off any sort of html content, or wired content when used within a
rendercall
svgtag function, create as one-off any sort of SVG content, or wired content when used within a
rendercall
render(node, fn)to pollute a
nodewith whatever is returned from the
fnparameters, including
htmlor
svgtagged layout, as well as any real DOM content, if needed
hook(useRef)that returns hooks compatible
htmland
svgutilities, using a
useRef(null)reference to provide a keyed updated per each component
Holeclass for 3rd parts (internal use)
You can test live a
hook example in this Code Pen.
What's different from hyperHTML ?What's different from hyperHTML ?
- the wired content is not strongly referenced as it is for
hyperHTML.wire(ref[, type:id])unless you explicitly ask for it via
html.for(ref[, id])or
svg.for(ref[, id]), where in both cases, the
iddoesn't need any colon to be unique, and it's the string
defaultwhen not specified. This makes content hard wired whenever it's needed.
- the
ref=${object}attribute works same as React, you pass an object via
const obj = useRef(null)and you'll have
obj.currenton any effect. If you'll pass
{set current(node) { ... }}that'll be invoked per each update, in case you need the node outside
useRef.
- intents, hence
define, are not implemented. Most tasks can be achieved via hooks.
- promises are not in neither. You can update asynchronously anything via hooks or via custom element forced updates. Promises might be supported again in the future to align with isomorphic SSR, but right now these are not handled at all.
- the
onconnectedand
ondisconnectedspecial events are gone. These might come back in the future but right now dom-augmentor replaces these via
useEffect(callback, []). Please note the empty array as second argument.
- an array of functions will be called automatically, like functions are already called when found in the wild
- the
Componentcan be easily replaced with hooks or automatic keyed renders
const render html = lighterhtml;// all it takes to have components with lighterhtmlconst Comp = html`Hello !`;// for demo purpose, check in console keyed updates// meaning you won't see a single change per second;{;}
DocumentationDocumentation
Excluding the already mentioned removed parts, everything else within the template literal works as described in hyperHTML documentation.
A basic exampleA basic example
;documentbody;// as automatically rendered wired content 🤯;{;{items;;}{items;;}}
What about Custom Elements ?What about Custom Elements ?
You got 'em, just bind
render arguments once and update the element content whenever you feel like.
Compatible with the node itself, or its shadow root, either opened or closed.
const render html = lighterhtml;customElements;
Should I ditch hyperHTML ?Should I ditch hyperHTML ?
Born at the beginning of 2017, hyperHTML matured so much that no crucial bugs have appeared for a very long time.
It has also been used in production to deliver HyperHTMLElement components to ~100M users, or to show W3C specifications, so that in case of bugs, hyperHTML will most likely be on the fast lane for bug fixes, and lighterhtml will eventually follow, whenever it's needed.
On top of this, all modules used in lighterhtml are part of hyperHTML core, and the ./tagger.js file is mostly a copy and paste of the hyperHTML ./objects/Update.js one.
However, as tech and software evolve, I wanted to see if squashing together everything I know about template literals, thanks to hyperHTML development, and everything I've recently learned about hooks, could've been merged together to deliver the easiest way ever to declare any non-virtual DOM view on the Web.
And this is what lighterhtml is about, an attempt to simplify to the extreme the
.bind(...) and
.wire(...) concept of hyperHTML, through a package that requires pretty much zero knowledge about those internals.
lighterhtml is also relatively new, so that some disabled functionality might come back, or slightly change, but if you like the idea, and you have tested it works for your project, feel free to ditch hyperHTML in favor of lighterhtml, so that you can help maturing this project too.
|
https://www.npmjs.com/package/rlighterhtml
|
CC-MAIN-2022-40
|
refinedweb
| 1,118
| 50.67
|
Write a program that makes 2 + 2 = 5
Write a program that seemingly adds the numbers 2 and 2 and outputs 5. This is an underhanded contest.
Your program cannot output any errors. Watch out for memory holes! Input is optional.
Redefining 2+2 as 5 is not very creative! Don't doublethink it, try something else.
Why is this underhanded? Two plus two *is* five.
THERE! ARE! FOUR! LIGHTS!
@Geobits - I agree: 2+2=5 you can see it in this calculator.
`echo "2+2=5";`
I always thought that `2 + 2 = 5` for very large values of 2.
`(1<<2)+(2>>1)`
Big Brother? NOT ROOM 101 :(
Python: >>> 1 + 2e-60 + 2e-60 == 1+ 5e-60 True
To see discussions of this question and its answers: Reddit and Hacker News.
C/C++ `char flush[] = "\n \003"; printf("%d\n", 2 + 2 [flush]);`
#include int main(int argc, char** argv) { char c = '2'; int a = (int)c; printf("%c+%c=%d\n", c, c, a/10)); return 0; }
(function () { var two = 2; console.log(two+++two); })();
@MT0 I thought you were referring to this 100% accurate model
Not enough reputation for a post, so C# alternative is here: `int x = 2, y = 2;` `Action action = () => Console.WriteLine(x + y);` `x++;` `action();`. Not working in .Net 4.5+
@MichaelT I can't believe my question made it to reddit, haha
`int i = 2 + 2; Console.Write(++i);` C#
The teacher Jonofon Serates shows an way to do it mathematically it is in Portuguese, anyway the math is the same in any language :D
Drat. I have a really short FORTRAN answer that *actually happened to me once*, but not enough reputation to add it.
Sadly, I don't have enough reputation to post, but I really wanted to post something. First off, this is probably invalid ;-; but here's my Brainf*** code, which sizes in at 63 bytes: `++++[>++++[>+++<-]<-]>>++.-------.+++++++.+++++++++++.--------.`
I'm closing this question in compliance with our policy on underhanded challenges.
Java
Reflection is indeed the right way to go with abusing Java... but you need to go deeper than just tweaking some values.); } }
Output:
5
Explanation:
You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.
Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127.
cache[132]is the spot where 4 would normally be. Set it to 5.
Warning: Doing this in real code will make people very unhappy.
Thought of this one as soon as I saw the question :)
That. Is. Evil. Absolutely evil. +1
@JanDvorak in chat it was suggested `Integer[] array = (Integer[]) c.get(cache); fisherYatesShuffle(array);` Just imagine how many things would break...
@MichaelT this got me thinking about a new kind of russian roulette ;-)
Since you're already using reflection, you could easily make this independent of the cache size (which does depend on runtime flags after all): `Field f = Integer.class.getDeclaredField("value"); f.setAccessible(true); f.set(4, 5)` Could be made even more reliable by just grabbing the first non-static field - any reasonable implementation will only have a single field after all.
Answers like this make me love this site more than SO.
@Voo true, and I did consider that a bit. However, its not quite as subtle/underhanded... the code above doesn't even use the digits 4 or 5.
@Michael Fair point, considering the goal of making it underhanded. So right you are, way less obvious this way
@MichaelT `Collections.shuffle(Arrays.asList(array));`
To make this underhanded, the manipulation has to be hidden a bit more.
@MichaelT I'm new to Java, can you explain why this ability exists at all? Seems dangerous to leave in a language.
@qwr reflection belongs to a type of programming known as metaprograming - writing programs *about* structures within the language. That type of thing exists in many languages and is a key part of how some things are done. You can see similar things in python and can be used to do some really neat things but that comes at the cost of being able to do dangerous stuff.
@qwr as an aside, I'm frequently in The Whiteboard chat room of Programmers.SE and would be more than happy to go through some of the uses of metaprogramming in Java (there are really *neat* things you can do with it if you use a 'safer' approach of annotations with libraries that understand them (rather than just poking around in the innards of a class)).
It is very sad that one can do this.
evil.js, evil.sh, evil.css and **evil.java**
@SebastianGodelet there are a number of design choices that facilitate this, all for very good reasons. Metaprogramming that allows for advanced debuggers, introspection, and libraries. A Flyweight pattern in the Integer for performance when boxing and reduce memory usage. And a varargs structure allowing for variable length parameter lists (but then must be Objects rather than primitives). This combination of design choices can allow someone to poke in places they shouldn't but also allows for much more powerful programs and libraries.
I just love Java's reflection. Way more freedom than .NET world.
Anyone intending to do this should make sure to only have this happen a small fraction of the time. And then make sure to add a check in front of one of your statements something like "if 2+2= 5 then" with some comment about "for some reason sometimes 2+2=5, this accounts for these situations" so anyone reading it in the future is confused even more.
zomg, java answers never get top votes! +1 for bringing java to the top :)
@enderland The dailyWTF munger program does just that, constantly reconfigures `Integer`s
There are other Java reflection tricks, like changing immutable strings. The internal functionality of the String class has changed slightly over the years, but this should still be possible.
@JohnGaughan there was an answer that did that though I can't seem to find it (I thought it was a good one) and exposes some interesting bits on how String interning worked and where things where done when. That said, I'm still quite pleased with this approach because of its lack of use of the numbers `4` and `5` in the code.
With this, any calculation that would normally result in 4 will result in 5 correct? `1 + 3 = 5`, `4 * 1 = 5`, `2 * 2 = 5`, `9 - 5 = 5`...
@Mr.Mindor when cast to an Integer either with autoboxing or `valueOf()` - yes. I change the value of the entry where `4` sits in the IntegerCache class to be the same as `5` and anything that uses that will have the value of 5.
Changing the value of a constant? Java emulating old FORTRAN! This is the final proof that real programmers can write FORTRAN in any language ;-)
So, sometimes Java lets you do crazier things than you could do in LISP...
Interestingly, `printf("%d",2+2)` prints 5, but `System.out.println(2+2)` prints 4. Can anyone offer any insight into what's going on there?
@DavisYoshida printf(String format, Object... args)) takes an `Object` array while println(int x)) takes an int. Thus, the value returned by `2+2` must be cast to an Object (an Integer in this case) by being auto boxed using `valueOf(2+2)`. Look at valueOf and the cache.
@Cruncher so you are giving votes because he is _receiving_ votes? When does it end?
@Cyoce When there's noone else to vote? And other people that don't share my sentiment? lol. I do only count for one vote ya know ;)
Haskell
I just love how you can throw anything at ghci and it totally rolls with it.
λ> let 2+2=5 in 2+2 5
What does `let 2+2=5 in 5+5` do? ಠ_ಠ
Define function named `2+2` that return `5`
@JanDvorak `Non-exhaustive patterns in function +` - I'm defining a new function (+) here, and If I plug in anything that isn't `2+2` it will error because I never defined what should happen in that case.
@Flonk I got it. That's why I used my look of disapproval ;-)
@JanDvorak haha, okay ಠ_ಠ
The plus operator is a function, and `let` can redefine existing functions. `let (+) 2 2 = 5 in (+) 2 2`
@SHiNKiROU shadow, not redefine
that almost sounds like: "And God said let 2+2=5 in 2+2" ))
@N0ir unfortunately, Genesis doesn't make for a valid Haskell code. Not even the first chapter. Not even the verse you mention.
I'm a fan of the `where` version: `2 + 2 where 2 + 2 = 5`. It even pops up on t-shirts! It doesn't work in GHCi though :(.
`let 2+2=5; x+y= x Prelude.+ y in 5+5` only redefines 2+2 and leaves the rest of addition alone.
How does this even work? How is this actually allowed?!
@user3217013 Learn Haskell, it's good for your heart.
@Jefffrey Thanks for your condescending comment, but I am actually well-versed in Haskell. I just have never seen this pattern before.
@user3217013 You are just defining the function (+) using equational style, where you define what should happen when the first argument is 2 and the second is 2, and you don't define all the other cases (thus, an inexhaustive definition). Kind of `case (x, y) of (2, 2) -> 5`
@user3217013 A `let` expression in Haskell defines a local variable to a specified value within the context of that expression. But "variable" here in fact encompasses not just things like `x` and `y`, but also infix operators like `+`, and values encompass not just things like `5` or `"Hello World!"`, but also functions. When an expression is evaluated in Haskell, the variables' values are looked up in the nearest defining scope. So in this example, `+` is redefined, in the scope of this expression only, to a function that produces `5` when both arguments are `2`.
I don't see why this gets so many votes. It doesn't make it appear that adding 2 + 2 gives the answer 5 at all. It's too explicit - big bzzzzzt!
It is rather too explicit. Better would be to redefine it in one place, and have the call in another, further down the stack. It isn't possible to compile a Haskell program with a modified version of the Haskell prelude, is it?
@JanDvorak Damn it, I always get that part wrong.
C
Pretty cheap trick but I'm sure I will trap the most of you.
int main() { int a = 2 + 2; a++; printf("%d",a); return 0; }
Scroll the code to the right.
I'm not sure on Windows/Linux but on OSX, the scrollbar is not visible.
Anyway, this is a good reason to enable "space visualization" on your favorite code editor.
Scrollbar is visible in Chromium, but who pays attention to it at first? :)
To confuse folks, you might add a comment line that is long enough to "explain" the existence of a scrollbar, but dull enough so that noone cares to (scroll in order to) read it.
Well, I had spotted the scrollbar (in Firefox).
In OS X, scrollbar visibility by default depends on whether a mouse is connected. If there's just a touchpad, scrollbars are overlaid and fade out when not in use. If there's a mouse connected, scrollbars steal space from the context box and are always visible. You can test this by unplugging and plugging in a USB mouse to a MacBook. This can be configured in System Preferences, of course.
Clever, but on mobile it just wordwraps :)
This is the only time that scrolling SE code windows *don't* make me want to break someone's fingers.
Rather than space-visualization, get an IDE which properly formats code. That will fix not just this problem, but a host of others.
You. are. *evil*. Great answer.
This is how i passed my remake 'malloc' assignment
@Ruslan Me? Now *that* is evil.
@AnonymousPi you must have intended to address not me...
@Ruslan No, I meant that I noticed the scrollbar and that Michael's post was evil because it seems that few people noticed it...
@Logan not for me in the Stack Exchange Android app (Nexus 5).
That got me ahahaha! Check out my C answer, love seeing C used on CodeGolf :D
You got me. This trick will be much fun if someone designs an editor that allows colouring the letters and setting a camera on programmers while they debug the code.
When you click "Run it here" and then "Run" it wordwraps.
GolfScript
4:echo(2+2);
Prints
5.
Of course GolfScript has a syntax that is markedly different from other languages, this program just happen to look like something Basic or C-ish.
4- Put the number 4 on the stack. Stack content: 4
:echo- Save the value at the top of the stack to the variable echo. Stack content: 4
(- Decrement the value at the top of the stack by 1. Stack content: 3
2- Put the number 2 on top of the stack. Stack content: 3 2
+- Add the two numbers on top of the stack. Stack content: 5
2- Put the number 2 on top of the stack. Stack content: 5 2
)- Increment the value at the top of the stack by 1. Stack content: 5 3
;- Remove the top element from the stack. Stack content: 5
GolfScript will by default print anything left on the stack after execution has finished.
Can you explain that for people who don't speak GolfScript please?
@MadTux Here you go.
Thanks. (I'll upvote later because I reached my daily limit, here's a beer.)
Simple and cheaty, I love it. +1
i like it becaus it doesn't seem like it's tricking you with math or semantics, it seems so straightforward and yet 5 ^^
Maybe using `print` will catch more programmers. Then again, most programmers know `echo`!
Java
Always have to round your doubles, folks
public class TwoPlusTwo { public static void main(String... args) { double two = two(); System.out.format("Variable two = %.15f%n", two); double four = Math.ceil(two + two); // round just in case System.out.format("two + two = %.15f%n", four); } // 20 * .1 = 2 private static double two() { double two = 0; for(int i = 0; i < 20; i++) { two += .1; } return two; } }
Output:
Variable two = 2.000000000000000 two + two = 5.000000000000000
Explanation:
No, seriously, you always have to round your doubles. 15 isn't enough digits to show that the
two()method actually produces
2.0000000000000004(16 is enough, though).
In the raw Hex representations of the numbers, it's only a 1 bit difference (between
4000000000000001and
4000000000000000)... which is enough to make the
Math.ceilmethod return 5, not 4.
`Math.ceil(two + two); // round just in case` I see what you did there
Making both a function and a variable with the same name... Wow.
If you chose a small enough increment, could you get your `two()` up to `2.5`?
@BenJackson if I did, the function `two()` wouldn't return `2` anymore.
@configurator that's nothing, there isn't even a class named `two`. Production grade java is `Two two = Two.two.two();` with Two.two being of type TwoFactory.
Two.Infinity.And.Beyond()
Ugh, too many twos to count!
@Caleb oh please all languages have issues with `double` rounding
@durron597: Not "all". Perl 6 for example doesn't have problems with this example.
Why is ```two = 2.0000000000000004```? As far as I see it, ```two = .1 * 20```, so where does the 0.0000000000000004 come from?
@ACarter Thats because 0.1 can't be represented exactly in the double datatype.
@RalZarek you mean 1/10 can't be represented exactly? o_O
@nyuszika7h doubles are stored in base 2 internally. This means that only fractions where the denominator is a power of 2 have a finite number of "decimals". 1/10 for example is .001100110011... in base 2.
@RalZarek that's interesting, I didn't know.
@TimS I ceil what you did there
@JannisFroese this is now my favourite comment on this SE
BBC BASIC
EDIT: For Andrea Faulds and Squeamish Ossifrage, a more convincing version using a different interpreter:
MODE 6 VDU 23,52,254,192,252,6,6,198,124,0 PRINT PRINT "2+2=";2+2 PRINT "2+3=";2+3
This actually prints the number 4, but the
VDU 23redefines the font for ASCII 52 so that it looks like a 5 instead of a 4. Screen mode 6 was selected for aesthetic reasons (characters of a reasonable size.)
The original image using the emulator at. (with slightly different code) can be seen in the edit history.
Those fonts look different though. Do you think you could make it use the correct font?
@AndreaFaulds I'm using the emulator from. It supports the font redefinition of original BBC Basic on an 8x8 grid. But the default font of the emulator is clearly higher res than 8x8. So I could probably do a better job, but it wouldn't be perfect. I suppose I could redefine the font for all 5 as well as 4, then they would look the same.
@AndreaFaulds The question didn't say that the result should be indistinguishable from other 5s. I think this is actually a feature. `2+3=5` and `2+2=5'`
This matches the original font in the BBC Micro: `VDU 23,52,126,96,124,6,6,102,60,0`
@squeamishossifrage thanks for the info. It won't match the font in the emulator though. Your example is 7 pixels high, just like mine. Also it has a zero at the bottom, just like mine, whereas it looks like I need to move it down a bit (i.e, have the zero at the top instead of the bottom.) A key difference is that I have 126,64 whereas you have 126,96, and you have some 6's instead of my 2's. That's because the original BBC font had thick vertical lines, so it could be read easily in 80 column format on a standard TV screen.
@squeamishossifrage I tried another interpreter, which uses a similar (but not identical) 8x8 font and got much more convincing results. Your original font does look 100% authentic though.
@BenJackson and I didn't think it did, but it would be so much nicer if it looked the same :(
@AndreaFaulds Take a look at the answer now. I fixed this a couple of days ago by using Brandybasic instead of BBCwin. The one I used before is a much better emulator in general, but in this case the fact that Brandybasic uses an 8x8 font made it possible to copy the font exactly.
@steveverrill Aha, awesome :)
This trick would also work on the Amstrad CPC (464, 6128, etc.), however, if you try to copy the character back into memory (e.g. with the copy cursor) it will read both `4` (which now looks like `5`) & `5` as `4`, because it tries to match the pattern of pixels to a character and `4` comes before `5`!
Brainfuck
+++++ +++++ + + + + + +++++ +++++ +++ +++++ + + + +++++ + + +++++ +++++.
Output:
5
I know this might sound a little to simple, but I tried to be creative, as suggested in original post.
I don't know brainfuck, it took me a couple of minutes to figure this out. ASCII 53, right?
As long you have the `+++++.` you can paint anything.
@steveverrill : yes you are right. (and this is the only way to output ascii characters in BF).
Bash
Since this is a popularity-contest, I guess I should use a long-winded method...
For people who don't know Bash:
$((...expr...))is a syntax to evaluate arithmetic expressions.
$(bc<<<...expr...)does the same using the
bccommand-line calculator.
v=2 #v is 2 v+=2 #v is 4 v=$(($v*5)) #v is 20 v=$(($v-16)) #v is 4 v=$(bc<<<"sqrt($v)+2") #v is 4 (sqrt(4) is 2) v=$(bc<<<"$v/4+3") #v is 4 (4/4 = 1) echo '2+2=' $v #So v is 4...?
Output
2+2= 5
Explanation
The second line concatenates v and 2 instead of adding them, to make 22.
Actual explanation:
v=2 #v is 2 v+=2 #v is 22 v=$(($v*5)) #v is 110 v=$(($v-16)) #v is 94 v=$(bc<<<"sqrt($v)+2") #v is 11 (by default, bc rounds to integers) v=$(bc<<<"$v/4+3") #v is 5 (11/4 is 2 with rounding) echo '2+2=' $v #TADAAAM
Nice maths trick going on there!
@tomsmeding It was quite fun, although about halfway through I realised that I had put `15` instead of `16` in line 4. Luckily, it still worked because of `bc`'s rounding
Oh this is just fabulous. lmao
See if you like the look of this style which is also valid Bash (eliminates the dollar signs, allows spaces around the equal sign and allows combined assignment operators): `((v = v * 5))` or `((v *= 5))`
Nice one, but I spotted the `+=` thing immediately.
@nyuszika7h It's probably easy to spot if you're very familiar with Bash. But users of other languages will expect Bash to handle `2` as an integer.
i don't understand how this meets the requirements. there isn't a single addition expression of the form "2+2" anywhere in the code. the only underhanded aspect of this code is the misleading comments. you could have read the value "A=2.5" from a file, added a false comment that says it has the value "A=2", and then printed the result of "A+A"
@ardnew yes there is. the first two lines (`v=2` and `v+=2`): to someone unfamiliar with Bash variable handling, that would be equivalent to `2+2`, but it is in fact `"2"+"2"`, i.e. `"22"`. the other comments in the code are only wrong because of this. I know, not everyone finds this funny
Python
Inspired by the Java answer:
>>>>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch) >>> 2 + 2 5
Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via
ctypes.
patchis just an obfuscated
"12-7", a string with
len4, which
eval's to 5.
A more obfuscated version
exec("\x66\x72\x6f\x6d\x20c\x74\x79\x70e\x73\x20\x69\x6d\x70\ \x6f\x72\x74\x20c\x5f\x69\x6e\x748\x20a\x73\x20x\x3bf\x72\x6f\ \x6d\x20\x73\x74\x72\x75c\x74\x20\x69\x6d\x70\x6f\x72\x74\x20\ ca\x6cc\x73\x69\x7ae\x20a\x73\x20x0\x3bx\x2ef\x72\x6f\x6d\x5f\ a\x64\x64\x72e\x73\x73\x28\x69\x64\x284\x29\x2bx0\x28\x27\x50\ \x50\x27\x29\x29\x2e\x76a\x6c\x75e\x3d5")
Beyond 2+2
As OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse.
from __future__ import division, print_function import struct import ctypes import random # Py 2.7 PyIntObject: # - PyObject_HEAD # - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG] # - (Py_ssize_t) ob_refcnt # - (_typeobject) *ob_type # - (long) ob_ival # two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above) offset = struct.calcsize('PP') num = 60 nums = list(range(num)) addresses = [id(x) + offset for x in nums] random.shuffle(nums) for a, n in zip(addresses, nums): ctypes.c_ssize_t.from_address(a).value = n print('2 + 2 =', 2+2) print('9 - 4 =', 9-4) print('5 * 6 =', 5*6) print('1 / 0 =\n', 1/0) print('(1 + 2) + 3 = ', (1+2)+3) print('1 + (2 + 3) = ', 1+(2+3)) print('(2 + 3) + 1 = ', (2+3)+1) print('2 + (3 + 1) = ', 2+(3+1))
Running with Python 2.7...ignore that line at the end. Works in Windows 64-bit and Ubuntu 32-bit, the two systems I have easy access to.
$ python awful.py 2 + 2 = 24 9 - 4 = 49 5 * 6 = 55 1 / 0 = 0.76 (1 + 2) + 3 = 50 1 + (2 + 3) = 68 (2 + 3) + 1 = 50 2 + (3 + 1) = 61 Segmentation fault (core dumped)
Unsurprisingly, we can break the associative property of addition, where (a + b) + c = a + (b + c), as seen in the 1st and 2nd
1+2+3lines, but inexplicably we also break the commutative property (where a + b = b + a; 2nd and 3rd lines). I wonder if the Python interpreter just ignores superfluous parentheses around addition expressions.
Yes, we definitely all just casually ignore segfaults...
It's worth mentioning that this isn't really a Python trick and is only specific to the C implementation of Python.
Python 2.7.6, windows, 64-bit did not work with `from_address(id(4)+8))`. I changed this to `from_address(id(4)+16))` and it worked fine. Are you sure your windows 64-bit installation is 64-bit python, or is it 32-bit python running in 64-bit windows?
@DavidJFelix I fully know that the short example at the top doesn't work in x64 without a correction like you make. That's why I mention my subsequent code being "multi-width", wherein it uses `struct.calcsize('PP')` to come up with the offset
@NickT Ah! okay. I was under the impression that you had tried the original under the same 64-bit windows, 32-bit ubuntu setup
`exec('\x66\x72\x6f\x6d\x20\x63\x74\x79\ \x70\x65\x73\x20\x69\x6d\x70\x6f\ \x72\x74\x20\x63\x5f\x69\x6e\x74\ \x38\x3b\x20\x69\x6d\x70\x6f\x72\ \x74\x20\x73\x74\x72\x75\x63\x74\ \x3b\x20\x63\x5f\x69\x6e\x74\x38\ \x2e\x66\x72\x6f\x6d\x5f\x61\x64\ \x64\x72\x65\x73\x73\x28\x69\x64\ \x28\x34\x29\x20\x2b\x20\x73\x74\ \x72\x75\x63\x74\x2e\x63\x61\x6c\ \x63\x73\x69\x7a\x65\x28\x27\x50\ \x50\x27\x29\x29\x2e\x76\x61\x6c\ \x75\x65\x3d\x35')` Is a modified first version. I made this so I could drop it into $PYTHONSTARTUP in /etc/profile as red team in hacking competitions.
@DavidJFelix that's awful :P
@NickT It's not the most underhanded thing I've done for red team tactics. I actually think you could probably break 3/5 python scripts if you changed the value of 1 to 0.
Something is messed up with my paste... I don't think it handled my code correctly above.
@DavidJFelix it probably converted newlines into spaces, so then your backslashes don't mean anything
Yeah. Sidenote, it seems that 1, 0 and -1 are some of the numbers that python immediately segfaults with. I was thinking those would be the worst for screwing up python programs behavior. It may be possible to utilize fuckitpy to contain these errors.
@professorfish I wanted to upvote your comment, but I don't want to change the number of 42 votes :P
@DavidJFelix: I don't think fuckitpy contains segfaults. It would be rather impressive if it did. (I can think of one way: trap the segfault, longjmp out of the broken stack frame, and resume execution at the next bytecode...but this will probably cause a ridiculous amount of breakage)
FYI, for anyone looking to continue being a jerk in python3, Python 3 uses longs now. In python3 64 bit, the byte offset seems to be "24" or `calcsize('PPP')`. I haven't tested this in 32bit yet.
eek... don't try the 1/0 one
JavaScript:
g = function () { H = 3 return H + H } f = function () { Η = 2 return Η + H } // 3 + 3 = 6 alert(g()) // 2 + 2 = 5 alert(f())
Check it at
Both H (Latin letter capital h) and Η (Greek letter capital eta) are set to the global scope because they were not defined as local to the functions with the var keyword. While they look similar, they are actually 2 different variables with 2 different values. Using Ctrl+F in your browser you will find that Η (eta) shows up significantly less than H (h) on this page.
can you explain this please?
@Sam even though the two 'H's look the same, they are in fact 2 entirely different characters. In Unicode there can be different characters that look the same but have different code-points. In this specific case; the other "H" is actually the greek letter Eta.
Using homoglyphs to "confuse" readers is now officially not funny.
The homoglyphs become funny in combination with javascript's ridiculous global variables.
This is not `2+2=5`, it is `2+2'=5` note the ref on the 2nd 2. not the same
smart! I liked it.
@Funkodebat what do you mean by that?
It's not the "Unicode Η character", it's Latin H and Greek Eta (Η).
On my screen it might as well be saying `2+3=5`, which doesn't seem underhanded at all. That's exactly what I would expect.
I didn't realize that if you don't use the var keyword, the variable is global. interesting
@KonstantinWeitz he's not doing h + h, because in the example, one of the h's is not h, its like doing a + b. one of the h's isn't 2. its like saying `2 + (not really 2) = 5`
@JanDvorak The problem with "officially" is that only 27 people at this time have agreed to make it official. Posting in that thread does not make it authoritatively not funny.
@Vortico hmm... what do you wish when a FAQ question doesn't suffice? A FAQ question linked from the help center? Note that only moderators can apply the [meta-tag:faq] tag. As for the answer - the question states "score +5 or more and at least twice as many upvotes as downvotes". The answer has 27 upvotes and no downvote. That sounds to me like fulfilling the criteria stated in the answer, and the amount of upvotes is pretty impressive for the second oldest answer on a question on the meta site of a site where only 124 people have voted more than 10 times. How many would _you_ like? Everyone?
@JanDvorak If those who agree would downvote this question, there would be no need for a meta question like that. The community will eventually grow sick of this kind of humor and no longer upvote these answers, so there is no need for a remark to remind people that humor is objective.
@Vortico well, I did downvote. I am genuinely surprised by the amount of upvotes this has got. Reddit?
Just not funny as the C(From Michael) example.
@Funkodebat: By that same logic the C example is not doing `2+2=5`, but rather `2+2+1=5` and wouldn't be special either.
Haha, on mobile it's grey and very obvious
You can also mess with the `alert()` and/or `console.log()` functions themselves. For instance:
bacchusbeale 7 years ago
This is question in book "1984" by George Orwelll.
|
https://libstdc.com/us/q/codegolf/28786
|
CC-MAIN-2021-25
|
refinedweb
| 5,222
| 73.78
|
CodePlexProject Hosting for Open Source Software
Hi,
I am about to port my application from PRISM to nRoute and would like to know what the best approach is for implementing a wizard. The wizard will have one view model and multiple views. I am going to use the future desktop as a base. The wizard will
not be in a popup, it will appear in the main content area of the future desktop. Also I would potentially like to have the next previous finish wizard navigation buttons appear on the bar that you have the add workspace, refresh favourite button
on the future desktop example. Finally if possible I would like to have a general wizard control which I can pass views/viewmodel and then the navigation buttons for the wizard should appear and operate correclty when a wizard is active within the main container/content
area.
Thanks in advance for any help.
Now, there are many ways to do this, some options are:
1. One parent View and VM, along with multiple child Views:
Start with one set of View and VM, in the View just put a NavigationContainer, and then within the container you can have your Wizard Pages/Views flow. Importantly, the Wizard Pages/Views shouldn't specify a VM, this way they would inherit the parent VM.
So what you get is one ViewModel paired with Multiple Wizard Pages/Views.
2. One VM, and Multiple Mapped Views
Basically, just map one or more Views to different Urls, and then have the Views map to a single VM, something like:
[DefineNavigationContent("Pages/Wizard/Page1/", typeof(Page1))]
[DefineNavigationContent("Pages/Wizard/Page2/", typeof(Page2))]
[DefineNavigationContent("Pages/Wizard/Page3/", typeof(Page3))]
[MapViewModel(typeof(Page1))]
[MapViewModel(typeof(Page2))]
[MapViewModel(typeof(Page3))]
public class WizardViewModel
{
// do the do
}
3. One View and VM, with a Url Token
If possible I'd prefer this, rather than having multiple views just have a parametrized Url. This way you can change the View per the value of Url parameter/token:
[DefineNavigationContent("Pages/Wizard/{StepIndex}/", typeof(WizardPage))]
[MapViewModel(typeof(WizardPage))]
public class WizardViewModel : NavigationViewModelBase
{
// get the value StepIndex by overriding OnInitialize method
}
As you can tell, all the above options aren't standardized like a Wizard control, which unfortunately I can't provide out of box with nRoute. However, you can create one yourself, the NavigationContainer model is very flexible and can provide you
with all the required infrastructure, you just need to layer the Wizard-specific functionality onto it.
Hope this helps,
Rishi
PS: I'd recommend use of StatefulBrowsingNavigationContainer, read more about it here
Thank you. I will give it a try.
Hi Orktane, sorry but I am struggling to know how to start (this is the very first part of my app that I am porting over to nRoute). Would you be able to explain option 1 in more detail please?
How do I add the wizard pages to the container? To start I would like to have one viewmodel and one view. The View will have an area for displaying the current wizard step/view, the wizard navigation buttons (Previous, Next, Finish and Cancel) and ideally
tabs for each wizard step with the current step highlighted/selected. Do containers support tabs, can you add a number of views toa container and then make it a tabbed container? If not can I add all the pages to the container and then somehow say which
one should be visible based on the current navigation step/index?
Also how can I access the navigation container from within the view model when I look at the static methods for NavigationService I only see a method for getting the default container. Is there some way of accessing container by name such as "WizardContainer"
and then I could set which view within the container is active/displayed? Also you mention that if a view is added to the container and the view doesn't have a view model sepcified then it will be given the parent view model, will this happen automatically?
Let me try answer your questions, point-by-point:
Q. How do I add the wizard pages to the container?
A. Well, you don't have to add them all at once, that's what you use navigation for. So like navigate from one page to another just use the NavigateAction behavior.
Q. Do containers support tabs?
A. Well, you must understand that a "navigation container" is something that can handle a navigation request/response (see the INavigationHandler interface). So tabs natively are not navigation containers, though minimally by either implementing INavigationHandler
by inheriting it or by creating a Navigation Adapter for it you can make it handle navigation (see for
an example on how to create adapters)
Q. About using Tabs?
A. Personally, I wouldn't use tabs for creating a Wizard control but you could. The problem with the tabs control is that tends to re-load pages when switched on/off a tab. You can create a similar effect/solution by just using the provided containers -
as all you'll be doing is to show one view at a time.
Q. Also how can I access the navigation container from within the view model?
A. You don't - in VMs you keep away the View related stuff. Also if you know how containers work (just like web browsers), when you navigate (like when you click a hyperlink) within a container it just picks up the container itself by walking up the
visual tree, unless you specify another container.
Q. Is there some way of accessing container by name?
A. Yes, see the "Globally Named Navigation Containers" section
Q. Also you mention that if a view is added to the container and the view doesn't have a view model sepcified then it will be given the parent view model, will this happen automatically?
A. Yes. And that's the setup I talked about in option 1. So you parent view will look something like:
<UserControl ...>
<i:Interaction.Behaviors>
<n:BridgeViewModel />
</i:Interaction.Behaviors>
<n:NavigationContainer
</UserControl>
As you can see above we've initialized the container to start with the url "Pages/MyWizard/Page1" - that Url maps to a UserControl (say Page1.xaml) which has been earmarked with the MapNavigationContent attribute:
[MapNavigationContent("Pages/MyWizard/Page1")]
public partial class Page1 : UserControl
{
//..
}
Now, importantly, this page doesn't have it's own VM - so it would inherit the parent's VM. So Page1.xaml could navigate to Page2.xaml which would be the second screen in your Wizard, and Page2 would be mapped with the Url like "Pages/MyWizard/Page2".
So basically all you need to do is navigate from one Url to another, and you should get your wizard going.
Hope you got the basic idea?
Rishi
Hi Rishi,
Thanks for the reply but I still don't see how the navigation would work between the different wizard pages. Are you suggesting that each wizard step/view has its own navigation buttons rather than having the navigation buttons within the general wizard
control? What I am unsure of is when the user is on Page 1 how do they get to Page 2, where is the url for page 2 defined? I would like to avoid having the to add wizard buttons to every view that is going to be a wizard step.
In my current prism implementation I have a general wizard control view/view model. I then add each wizard step/view to a Pages Collection (each page has the same viewModel). The wizard view has the navigation buttons and one region for displaying
the current wizard step. within the view model I then add the current wizard step to the region. The Next, Previous, Finish and Cancel buttons are bound to commands within the wizard viewmodel. I then need to know what buttons should be enabled based
on the current wizard step. so previous wouldnt be enabled when on the first step etc.
Here is an example below of the same general wizard being used in 2 different instances. The idea being that the CustomerViewModel and customer views and WidgetConfigurationViewModel and widget configuration views know nothing about the wizard.
Is it possible that I am trying to use nRoute in a way that it has not been designed for?
//Customer wizard
WizardViewModel wizardViewModel = new WizardViewModel();
wizardViewModel.Pages.Add(NewCustomerStep1View);
wizardViewModel.Pages.Add(NewCustomerStep2View);
wizardViewModel.Pages.Add(NewCustomerStep3View);
//Widget configuration wizard
WizardViewModel wizardViewModel = new WizardViewModel();
wizardViewModel.Pages.Add(WidgetConfigurationStep1View);
wizardViewModel.Pages.Add(WidgetConfigurationStep2View);
wizardViewModel.Pages.Add(WidgetConfigurationStep3View);
All Classes are:
Let me do a sample for you, will post it after work.
Cheers,
Rishi
Sorry to pester you but is there any update on the sample?
Well, sorry got really caught up in work during the week - anyway, so rather than one I've done two types of wizards. One with a single backing VM, and another with multiple VMs. Download the code from
Let me know if it works for ya.
Hi Rishi, thanks for the samples they have helped me port over the existing wizards.
I have implemented the wizard and its working great. However one final question on the subject, I would like to move the Navigation buttons next, previous etc out of the wizard
general view into the application shell view (to save space). So my question is can I associate two VMs with one view so the shell View would have the Shell VM and Wizard VM associated with it when the wizard is active so that I can bind the Wizard view
model navigation ActionCommands to the buttons. I think the answer to this is no, but would like to double check.
If this isn’t possible do you think an appropriate solution would be to use the eventAggregator/pub sub mechanism: When the wizard is active it publishes a message to say
that it is active and the shell view model subscribes to this and displays the navigation buttons. When a navigation button is then clicked the Shell VM publishes a message to say that "Next" button etc has been clicked and the Wizard
VM subscribes to these messages and acts appropriately?
@Ultramods, did you have a look at the Widgets wizard (not the customers one) - it used nRoute's event aggregrator/pub-sub mechanism (called Channels) to publish the responses. And the next/back/forward buttons are separate from each
step View. Also, you can't have two VMs for a View, at least, not in the normal way we interpret VMs, and even if you did have two VMs you'll need to choose one to apply at runtime. However, you can reach into another VM via a relay or something.
Rishi
Ok thanks, I will use that approach.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later.
|
http://nroute.codeplex.com/discussions/225598
|
CC-MAIN-2017-17
|
refinedweb
| 1,832
| 52.19
|
Subject: Re: [boost] namespace boost?
From: Kim Barrett (kab.conundrums_at_[hidden])
Date: 2011-01-15 17:12:37
On Jan 15, 2011, at 4:46 PM, Dave Abrahams wrote:
>>> +1, although I think the name should be boost::ratio rather than
>> boost::ratios
>
> If it has a type called "ratio" in it, "ratios" might be a better
> choice for the namespace. That, at least, is how tuple did it. I
> can't find a good rationale for that choice now, but once upon a time
> it used to be our recommended practice.
"For those who are really interested in namespaces"
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2011/01/175022.php
|
CC-MAIN-2020-16
|
refinedweb
| 122
| 76.42
|
What will we cover?
In this tutorial we will show how to calculate the Stochastic Oscillator with Pandas DataFrames.
Step 1: Retrieve the Data from CSV file with Pandas DataFrames
We first need to read the data from a CSV file into a DataFrame. You can get the CSV file from here or directly from Yahoo! Finance.
Alternatively you can you PandasDataframes as described in this tutorial.
import pandas as pd import matplotlib.pyplot as plt %matplotlib notebook data = pd.read_csv("AAPL.csv", index_col=0, parse_dates=True)
Step 2: Calculate the Stochastic Oscillator with Pandas DataFrames
The Stochastic Oscillator is defined as follows.
- 14-high: Maximum of last 14 trading days
- 14-low: Minimum of last 14 trading days
- %K: (Last Close – 14-low)*100 / (14-high – 14-low)
- %D: Simple Moving Average of %K
That can be done as follows.
high14 = data['High'].rolling(14).max() low14 = data['Low'].rolling(14).min() data['%K'] = (data['Close'] - low14)*100/(high14 - low14) data['%D'] = data['%K'].rolling(3).mean()
Notice, we only keep the %K and %D. The high14 and low14 are temporary variables to make our calculations easier to read.
Step 3: Visualize the Stochastic Oscillator with Matplotlib
To visualize it.
fig, ax = plt.subplots() data[['%K', '%D']].loc['2020-11-01':].plot(ax=ax) ax.axhline(80, c='r', alpha=0.3) ax.axhline(20, c='r', alpha=0.3) data['Close'].loc['2020-11-01':].plot(ax=ax, alpha=0.3, secondary_y=True)
Resulting in the following.
Next Steps?
Want to learn more?
This is part of the FREE online course on my page. No signup required and 2 hours of free video content with code and Jupyter Notebooks available on GitHub.
Follow the link and read more.
|
https://www.learnpythonwithrune.org/stochastic-oscillator-with-pandas-dataframes/
|
CC-MAIN-2021-25
|
refinedweb
| 290
| 69.79
|
Before you start writing your first Python program, you’ve got to learn the basics. We will walk you through Python syntax basics that will help as a building block for your Python career.
Throughout the article, we are going to use Python 3 to cover the topic.
To get started, let’s first write a very basic Python program.
Writing your First Python Program
There are two ways in which you can write and execute a basic Python program:
- In Interactive mode – where you write a program and execute it
- Using Script mode – where you execute and already saved Python program(.py file)
Let’s see those in action.
Writing “Hello, World!” on Interpreter
To enter the interactive Python mode enter the following command on your Terminal.
$ python
And, now you should be in the interactive mode.
But, if you are using an IDE you don’t need to type the command above to get into interactive programming mode.
Here is Basic Python syntax for executing a Hello World Program.
When you write this program and press enter, your IDE should display “Hello, Word!”
print("Hello World”)
Anything that you write within “ “ of print(“ ”) gets printed on your IDE.
In our case, the output that you should see on your screen would be
Hello, World!
Running Your First Python Program in Scripting Mode
When you wrote your Hello World program earlier, let’s assume that you saved it in a Python file. When you save your first program, look for a .py extension file.
Assuming that you saved it as Hello_Python.py, here’s how you would execute this code in a scripting mode.
First of all, the file you saved has to be made executable. We ideally do that by the command:
Recommended Python Training
For Python training, our top recommendation is DataCamp.
$ chmod +x test.py
Now that your file is executable, let’s run the program in scripting mode.
$ python Hello_Python.py
Once you execute this command, you will see “Hello, World!” was printed on your Terminal.
"Hello, World”
And, there you have learned your first Python Syntax.
Python Keywords and Identifiers
There are a total of 31 keywords and 5 major identifiers that you should know in Python.
Keywords and identifiers are something you will easily get used to as you work on your Python skills.
What are Identifiers in Python
A Python identifier usually is a variable, a function, a class, a module or it can be any other object. You give a name to an entity in Python, it is called an identifier. A valid identifier starts with a letter(A-Z, a-z both apply) or an underscore(_) which can be followed by zero, letters, underscores or numbers(0-9).
Types of Identifiers in Python:
- Variables
- Functions
- Modules
- Class
- Other Objects
Let’s go over and check what Keywords are available in Python
Python Syntax Basics – Keywords
To see all 3 Python Keywords, open your IDE and type the following:
import keyword >>> keyword.kwlist
You should see something like this as the output
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
These keywords may often change as new Python versions are released. A couple things in mind:
- These are fixed and cannot be used as identifiers
- They are case sensitive
These Keywords are also often referenced as Reserved words.
Python Statement
The next thing you should know before we move ahead with Python Syntax basics is Lines and Indentation.
Indentation is help organize code blocks in Python. And, it is rigidly enforced and makes your code visually scannable.
The space that goes with indentation varies under each situation. Observe the code below:
person = ["Dave", "Ben", "Emily"] for x in person: if x == "Ben": print(x) else: print("not Ben")
Notice how the “for” statement has one space(indentation), and how “if” has two. That establishes a hierarchy of what’s happening within the code.
Try reading the snippet below where we replaced code with the text:
List of Persons Go through the list of Persons: See if Ben is there: If yes, print Ben's name else: print that it's not Ben
When you end a line in Python with a semicolon(;), you end a statement in Python.
Also, you can effectively use to write multiple statements in a single line too. Look at the Python Syntax example below:
person="John Doe";age=12;location="unknown"
Python Syntax Basics – Comments
There are two different ways to write comments in Python:
- Single line comments using “#”
- Multi line comments using “”” “””
When you enter anything within triple quotes you can actually write multi line comments without having to add “#” in front of each line of comment. A good example of this would be the “Hello, World!” program at the start.
When you execute a code, it doesn’t print comments that you add in the code.
Python Basic Syntax – Command Line Arguments.
[:]
How To Create A Virtual Environment
Virtual environments are going to be one of those things that you’ll create for each new project.
You can still work on new Python projects without creating virtual environments. But, doing so would mean that you will end up with a situation where:
- You’ll change/modify dependencies (e.g. upgrading your default Python version from 2.7 to 3.x)
- Your other Python projects may not execute properly
To create a virtual environment, go to your Terminal and type the following:
$ virtualenv newevironment
The name of the virtual environment we just created it newenvironment.
To launch this newly created environment, type the following command:
source newenvironment
Python Basic Syntax – Installing A Library and Packages
The best way to install Python libraries and packages is by using PyPI.
To install a package, simply type the following command:
pip install "package"
Here “package” should be replaced by the library you wish to install.
In case if you wish to install a specific version of a package, change the previous command:
pip install "package==2.801"
However, if you are unsure of the package version availability, but want to install a stable or a more reliable package – here’s your command:
pip install "package>=2.8"
There are other ways to install Python packages too, you can go to source distributions and download these packages directly.
Taking User Input
There are two basic Python syntax types that can request a user input:
- raw_input
- input
Both will prompt a user to enter an input.
raw_input():
This method is no longer valid Python 3 and the new input is input().
input()
To request a user input see the example below
user_input_request = input("Enter your name: ")
Once you enter this, your IDE will ask you to enter you your name.
Recommended Python Training
For Python training, our top recommendation is DataCamp.
|
https://www.pythonforbeginners.com/basics/python-syntax-basics?utm_source=rss&utm_medium=rss&utm_campaign=python-syntax-basics
|
CC-MAIN-2021-31
|
refinedweb
| 1,155
| 61.77
|
from Graphics import Point
Point(0, 0) - Point(10, 10)
14.142135623731
import random import time import itertools
def exact_TSP(cities): "Generate all possible tours of the cities and choose the shortest one." return shortest(alltours(cities)) def shortest(tours): "Return the tour with the minimum total distance." return min(tours, key=total_distance)
alltours = itertools.permutations # The permutation function is already defined in the itertools module cities = {1, 2, 3}
list(alltours(cities))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
def total_distance(tour): "The total distance between each pair of consecutive cities in the tour." return sum(distance(tour[i], tour[i-1]) for i in range(len(tour)))
City = Point # Constructor for new cities, e.g. City(300, 400) def distance(A, B): "The distance between two points." return abs(A - B)
A = City(300, 0) B = City(0, 400) print(distance(A, B))
500.0
def Cities(n): "Make a set of n cities, each with random coordinates." return set(City(random.randrange(10, 890), random.randrange(10, 590)) for c in range(n)) # Let's make some standard sets of cities of various sizes. # We'll set the random seed so that these sets are the same every time we run this notebook. random.seed('seed') cities8, cities10, cities100, cities1000 = Cities(8), Cities(10), Cities(100), Cities(1000)
cities8
set([<Point (x=476,y=312)>, <Point (x=888,y=54)>, <Point (x=607,y=12)>, <Point (x=229,y=343)>, <Point (x=409,y=128)>, <Point (x=781,y=385)>, <Point (x=231,y=241)>, <Point (x=596,y=456)>])
%%time tour = exact_TSP(cities8) print(tour) print(total_distance(tour))
(<Point (x=607,y=12)>, <Point (x=409,y=128)>, <Point (x=231,y=241)>, <Point (x=229,y=343)>, <Point (x=476,y=312)>, <Point (x=596,y=456)>, <Point (x=781,y=385)>, <Point (x=888,y=54)>) 1808.86268316 Time: 00 s, 987 ms
def alltours(cities): "Return a list of tours, each a permutation of cities, but each one starting with the same city." start = first(cities) return [[start] + list(tour) for tour in itertools.permutations(cities - {start})] def first(collection): "Start iterating over collection, and return the first element." for x in collection: return x
alltours({1, 2, 3})
[[1, 2, 3], [1, 3, 2]]
alltours({1, 2, 3, 4})
[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2]]
%%time tour = exact_TSP(cities8) print(tour) print(total_distance(tour))
[<Point (x=476,y=312)>, <Point (x=229,y=343)>, <Point (x=231,y=241)>, <Point (x=409,y=128)>, <Point (x=607,y=12)>, <Point (x=888,y=54)>, <Point (x=781,y=385)>, <Point (x=596,y=456)>] 1808.86268316 Time: 00 s, 168 ms
def plot_tour(algorithm, cities): "Apply a TSP algorithm to cities, and plot the resulting tour." # Find the solution and time how long it takes t0 = time.clock() tour = algorithm(cities) t1 = time.clock() # Plot the tour as blue lines between blue circles, and the starting city as a red square. calico.ScatterChart(['x', 'y'], XY(list(tour) + [tour[0]]), {'width': 600, "height": 300, 'legend': 'none', "lineWidth": 1, "pointSize": 3}).display() print("{} city tour; total distance = {:.1f}; time = {:.3f} secs for {}".format( len(tour), total_distance(tour), t1-t0, algorithm.__name__)) def XY(points): "Given a list of points, return a list of [(X, Y), ...]" return [(p.x, p.y) for p in points] plot_tour(exact_TSP, cities8)
8 city tour; total distance = 1808.9; time = 0.136 secs for exact_TSP
def greedy_TSP(cities): "At each step, visit the nearest neighbor that is still unvisited." start = first(cities) tour = [start] unvisited = cities - {start} while unvisited: C = nearest_neighbor(tour[-1], unvisited) tour.append(C) unvisited.remove(C) return tour def nearest_neighbor(A, cities): "Find the city in cities that is nearest to city A." return min(cities, key=lambda x: distance(x, A))
cities = Cities(9) plot_tour(exact_TSP, cities) plot_tour(greedy_TSP, cities)
9 city tour; total distance = 2030.1; time = 1.079 secs for exact_TSP
9 city tour; total distance = 2350.9; time = 0.003 secs for greedy_TSP
plot_tour(greedy_TSP, cities100) plot_tour(greedy_TSP, cities1000)
100 city tour; total distance = 7000.7; time = 0.034 secs for greedy_TSP
1000 city tour; total distance = 20854.9; time = 1.206 secs for greedy_TSP
def all_greedy_TSP(cities): "Try the greedy algorithm from each of the starting cities; return the shortest tour." return shortest(greedy_TSP(cities, start=c) for c in cities) # We will modify greedy_TSP to take an optional start city; otherwise it is unchanged. def greedy_TSP(cities, start=None): "At each step, visit the nearest neighbor that is still unvisited." if start is None: start = first(cities) tour = [start] unvisited = cities - {start} while unvisited: C = nearest_neighbor(tour[-1], unvisited) tour.append(C) unvisited.remove(C) return tour # Compare greedy_TSP to all_greedy_TSP plot_tour(greedy_TSP, cities100) plot_tour(all_greedy_TSP, cities100)
100 city tour; total distance = 7000.7; time = 0.026 secs for greedy_TSP
100 city tour; total distance = 6742.8; time = 1.367 secs for all_greedy_TSP
def greedy_exact_end_TSP(cities, start=None, end_size=8): """At each step, visit the nearest neighbor that is still unvisited until there are k_end cities left; then choose the best of all possible endings.""" if start is None: start = first(cities) tour = [start] unvisited = cities - {start} # Use greedy algorithm for all but the last end_size cities while len(unvisited) > end_size: C = nearest_neighbor(tour[-1], unvisited) tour.append(C) unvisited.remove(C) # Consider all permutations of possible ends to the tour, and choose the best one. # (But to make things faster, omit the middle of the tour.) ends = map(list, itertools.permutations(unvisited)) best = shortest([tour[0], tour[-1]] + end for end in ends) return tour + best[2:] plot_tour(greedy_exact_end_TSP, cities100) plot_tour(greedy_exact_end_TSP, cities1000)
100 city tour; total distance = 6853.2; time = 1.390 secs for greedy_exact_end_TSP
1000 city tour; total distance = 20830.3; time = 2.862 secs for greedy_exact_end_TSP
def greedy_bi_TSP(cities, start_size=12, end_size=6): "At each step, visit the nearest neighbor that is still unvisited." starts = random.sample(cities, min(len(cities), start_size)) return shortest(greedy_exact_end_TSP(cities, start, end_size) for start in starts) random.seed('bi') plot_tour(greedy_bi_TSP, cities100) plot_tour(greedy_bi_TSP, cities1000)
100 city tour; total distance = 7096.5; time = 0.442 secs for greedy_bi_TSP
1000 city tour; total distance = 20824.9; time = 17.009 secs for greedy_bi_TSP
from Widgets import Lines def compare_algorithms(algorithms, maps): "Apply each algorithm to each map and plot results." lines = Lines(len(maps)) for algorithm in algorithms: t0 = time.clock() results = [total_distance(algorithm(m)) for m in maps] t1 = time.clock() avg = sum(results) / len(results) label = '{:.0f}; {:.1f}s: {}'.format(avg, t1-t0, algorithm.__name__) lines = Lines(lines, sorted(results), label) calico.LineChart(lines, {"width": 800, "height": 300, "chartArea": {"width": 300}}).display() print('{} x {}-city maps'.format(len(maps), len(maps[0]))) def Maps(M, N): "Return a list of M maps, each consisting of a set of N cities." return [Cities(N) for m in range(M)] compare_algorithms([greedy_TSP, greedy_exact_end_TSP, all_greedy_TSP], Maps(10, 50))
10 x 50-city maps
|
https://nbviewer.ipython.org/urls/bitbucket.org/ipre/calico/raw/master/notebooks/Python/Travelling%20Salesperson.ipynb
|
CC-MAIN-2022-27
|
refinedweb
| 1,191
| 58.48
|
django-admin-sortable2 0.2.6
Generic drag-and-drop ordering for objects in the Django admin interface
======================
Generic drag-and-drop ordering for objects in the Django admin interface
------------------------------------------------------------------------
Project home:
Ask questions and report bugs on:
Introduction
------------
This is another generic drag-and-drop ordering module for sorting
objects in the list view of the Django admin interface. It is a rewrite
of
`django-admin-sortable <https: github.`__. You can use your existing ordered field, just as you always
did, or add a new one with any name you like, if needed.
Build status
------------
|Build Status|
Installation
------------
The latest stable release from PyPI:
``pip install django-admin-sortable2``
or the current development release from github:
``pip install -e git+``
In ``settings.py`` add:
.. code:: python
INSTALLED_APPS = (
...
'adminsortable',
...
)
Integrate your models
---------------------
Each database model which shall be sortable requires a position value in
its model description. Rather than defining a base class, which contains
such a positional value in a hard coded field, this plugin lets you
reuse existing sort fields or define a new field for the sort value.
Therefore this plugin can be applied in situations where your model is
derived from an existing abstract model which already contains any kind
of position value. The only requirement for this plugin is that this
position value be specified as the primary field used for sorting. This
in Django is declared through the model's Meta class. Example
``models.py``:
.. code:: python
class SortableBook(models.Model):
title = models.CharField('Title', null=True, blank=True, max_length=255)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta(object):
ordering = ('my_order',)
Here the ordering field is named ``my_order``, but any other name is
valid. There are only two requirements:
1) ``my_order`` is the first field in the ``ordering`` tuple of the
model's Meta class.
2) ``my_order``'s default value must be 0. The javascript which performs
the sorting is 1-indexed, so this will not interfere with the order
of your items, even if you're already using 0-indexed ordering
fields.``
**Warning:** (be sure to put the mixin class before model.ModelAdmin):
.. code:: python
----------------------------
.. code:: python sorting
field (e.g. ``my_order``), which does not yet contain any values, then
you may set initial ordering values by pasting this code snippet into
the Django shell:
.. code:: python
shell> ./manage.py shell
Python ...
>>>
from myapp.models import *
order = 0
for obj in MySortableModel.objects.all():
order += 1
obj.my_order = order
obj.save()
or using South migrations:
.. code:: python
shell> ./manage.py datamigration myapp set_order
this creates an empty migration named something like
``migrations/0123_set_order.py``. Edit the file and change it into a
data migration:
.. code:: python
class Migration(DataMigration):
def forwards(self, orm):
order = 0
for obj in orm.MyModel.objects.all():
order += 1
obj.my_order = order
obj.save()
then apply the changes to the database using:
::
shell> ./manage.py migrate myapp
Run Example Code
----------------
To get a quick first impression of this plugin, clone this repositoty
from GitHub and run an example webserver:
::
git clone
cd django-admin-sortable2/example/
./manage.py syncdb
# add an admin user
./manage.py loaddata testapp/fixtures/data.json
./manage.py runserver
Point a browser onto, log in and go to
*Sortable books*. There you can test the behaviour. augments its functionality. In OOP design this does not qualify
for an IS-A relationship.
Fortunately, Python makes it very easy to distinguish between real IS-A
relationships and augmenting functionalities. The latter is now in
trouble. He has to choose between one of the two, as he cannot dervie
from them both, because his model class would inherit the base class
``models.Model`` twice. This kind of diamond-shaped inheritance is to be
avoided under all circumstances.
By using a mixin class rather than deriving from a special abstract base
class, these problems can be avoided!
Related projects
================
-
-
-
-
-
Release history
===============
- 0.2.6 Fixed: Unsortable inline models become draggable when there is
a sortable inline model
- 0.2.5
- Bulk actions are added only when they make sense.
- Fixed bug when clicking on table header for ordering field.
- 0.2.4 Fix CustomInlineFormSet to allow customization. Thanks
**yakky**.
-.
License
-------
.. |Build Status| image::
:target:
- Downloads (All Versions):
- 188 downloads in the last day
- 1333 downloads in the last week
- 1423 downloads in the last month
- Author: Jacob Rief
- Keywords: django
- License: MIT
- Platform: OS Independent
- Categories
- Package Index Owner: jrief
- DOAP record: django-admin-sortable2-0.2.6.xml
|
https://pypi.python.org/pypi/django-admin-sortable2/0.2.6
|
CC-MAIN-2015-11
|
refinedweb
| 746
| 58.18
|
Bug #12109
Exception during class load can cause partially-loaded class
Description
I noticed this bug using Rails, which lazy-loads classes (via ActiveSupport.)
Here's a minimal test case:
#!/usr/bin/env ruby begin # simulate loading a class from file at runtime eval %q{ class Foo def self.bar fail 'bar' end bar def self.baz puts 'baz' end end } rescue => e puts "rescued: #{e}" end # => rescued: bar Foo.baz # => undefined method `baz' for Foo:Class (NoMethodError)
EXPECTED
Either:
* No exception - finish adding the method to the class, or
* 'undefine' the class, at least making it obvious that the class didn't load completely (or in the case of rails/activesupport, allow it to be reloaded on-demand later)
History
#1
[ruby-core:74331]
Updated by shyouhei (Shyouhei Urabe) about 1 year ago
You can write virtually anything inside a class definition. I don't think it's practically possible to revert all operations inside of a require (that needs a full ACID properties I guess).
Then on the other hand is it a wise idea to ignore exceptions? I don't think so. Because there should be a way for a class author to bail out the creation of a class on some reason. That is not a well-doing, but should there be a way to do so at least.
I heard that chef scripts intentionally raises from inside their definitions, to abnormally quit a provisioning. That sort of things sometimes happen.
#2
[ruby-core:74385]
Updated by marcandre (Marc-Andre Lafortune) about 1 year ago
- Status changed from Open to Rejected
Closing as this is not a bug.
I don't see any change of the sort happening as both of your expectations make no sense. Please understand that when loading a file, ruby executes them. The statements are executed in order. The
def could be changed to
define_method which is not a keyword but an instance method of
Module.
Is it rails that rescues the exception when autoloading? I can't remember. If so, patch that behavior if you really want to.
Also available in: Atom PDF
|
https://bugs.ruby-lang.org/issues/12109
|
CC-MAIN-2017-13
|
refinedweb
| 352
| 64.71
|
Basic animation in Qt and Windows Phone
This article demonstrates how to create basic animation in Qt and WP7. For a more detailed explanation of animation on each framework see the topics QML Animation and Transitions and Windows Phone Animation Overview, respectively.
Windows Phone 8
Windows Phone 7.5
Symbian
Komalpatel - What is storyboard and DoubleAnimation?
I am also getting error in method start_Animation. // Start the animation when the object loads.}
komalpatel 17:11, 3 January 2012 (EET)
Somnathbanik - What is storyboard and DoubleAnimation?
DoubleAnimation can be used to archive animated behavior in WP7 similar to as that of PropertyAnimation/ NumberAnimation/RotationAnimation in Qt Quick .
In this article the DoubleAnimation creates a transition between two double values, i.e. To and From of its property. And to animate the property we use Storyboard which targets Name and Property of the animation.Please share the error
somnathbanik 09:28, 4 January 2012 (EET)
Komalpatel - What do lines at the top most portion of .xaml file maens for?
To try provided code to understand many topics, I need to make changes in lines: <phone:PhoneApplicationPageSo I need to know about that first.
komalpatel 06:27, 5 January 2012 (EET)
Somnathbanik - What do lines at the top most portion of .xaml file maens for?
These are the namespace (xmlns) of the reference added in the project.I believe remaining you can understand with the syntax, in simple word they are the resources and properties used in the project.
somnathbanik 09:14, 5 January 2012 (EET)
Somnathbanik - Compatibility
This article is Compatible for both Windows Phone 7 and Windows Phone 8.We will update the title accordingly.
somnathbanik 12:12, 5 June 2013 (EEST)
|
http://developer.nokia.com/community/wiki/Basic_animation_in_Qt_and_Windows_Phone
|
CC-MAIN-2014-10
|
refinedweb
| 280
| 50.02
|
> From: Dmitry <address@hidden> > Date: Tue, 02 Sep 2014 01:53:12 +0400 > > 1. New, empty buffer. > 2. (insert "a\tb") > 3. (posn-actual-col-row (posn-at-point)) > => (3 . 0) > > It should probably return (9 . 0). No, it should return (3 . 0), as it does. You misunderstand the contract of this function (which is not surprising, since the issue is a subtle one, and the documentation, while it tries to be accurate, has a hard time communicating its intent due to inherent ambiguity of the related terminology). This sentence from the doc string of posn-actual-col-row says it all: These are the actual row number in the window and character number in that row. "Character number in that row". IOW, it counts characters, not visual columns. This function, and the data in its POSITION argument which it accesses, are designed to make it easy to find the glyph (or "display element") in a screen line, so it simply provides the ordinal number of the "thing at point" on its screen line, disregarding the screen dimensions of that thing. So this is not a bug, but intended, if obscure, behavior. > I'm not 100% this is actually a bug, but (posn-actual-col-row > (posn-at-point)) returns the "visually" correct column values in the > more complex cases (after text with `display' or `compose-region' called > on it), so not accounting for tab-width looks surprising. As long as posn-actual-col-row deals with characters of the same dimensions (i.e. the same font), it will always produce seemingly accurate "column" counts, no matter whether these characters come from a buffer, a display property, or an overlay string. (It counts characters on display, so the source from which they came is irrelevant.) But as soon as you have something in the line whose glyph is larger or smaller than the other characters in that line, the "column" produced by the function will be skewed, because it's actually not a visual column, but a count of "display elements" from the beginning of the screen line. E.g., try insert-image or put a display property which uses ':align-to' or ':width', and you will see that the image and the stretch of whitespace produced by those are counted as a single "column", no matter what are their actual dimensions. IOW, posn-actual-col-row is not reliable when you want screen coordinates in row/column units. > Originally: And you were right to resolve that by using posn-col-row instead. That function translates pixel coordinates into row/column units, which is much closer to what you want. (Yes, it's not easy to do the job of the display engine.)
|
https://lists.gnu.org/archive/html/bug-gnu-emacs/2014-09/msg00046.html
|
CC-MAIN-2021-43
|
refinedweb
| 453
| 61.56
|
Gleb Albovsky5,341 Points
Opposite Number Game problem
I was trying to except string and numbers > 10, but got an error:
import random def game(): try: secret_num = int(input("Please enter a number from 1 to 10: ")) except ValueError: print("{} is now a number!".format(secret_num)) except secret_num > 11: print("{} greater than 10!".format(secret_num)) guesses = [] while len(guesses) < 3: computer_num = random.randint(1, 10) if secret_num == computer_num: print("Well done! The number was {}".format(secret_num)) break else: print(computer_num) game()
Please say, how to except strings and numbers > 10
Gleb Albovsky5,341 Points
Traceback (most recent call last):
File "opposite_number_game.py", line 8, in game
secret_num = int(input("Please enter a number from 1 to 10: "))
ValueError: invalid literal for int() with base 10: 'dfivdu'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "opposite_number_game.py", line 24, in <module>
game()
File "opposite_number_game.py", line 10, in game
print("{} is now a number!".format(secret_num))
UnboundLocalError: local variable 'secret_num' referenced before assignment
treehouse:~/workspace$
2 Answers
Shabbir Salumberwala4,313 Points
Opposite Number game for reference (Try refactoring it for best practices) :
import random import time def game(username,Secret_Num,Guess_limit): guesslimit = Guess_limit while guesslimit > 0: print("Mr. Computer. Whats your guess?") time.sleep(3) guess = random.randint(1,10) if guess == Secret_Num: print("You got it! the number was {}".format(Secret_Num)) elif Secret_Num - guess > 3: print("Your guess {} is Too low".format(guess)) guesslimit -= 1 elif Secret_Num - guess < -3: print ("Your guess {} is to high!".format(guess)) guesslimit -= 1 else: print("Bummer! {} was close".format(guess)) guesslimit -= 1 if guesslimit == 1: print("last chance Mr.Computer!\n") time.sleep(1) else: print("\nThe secret number was : {}. Better Luck Next Time!".format(Secret_Num)) repeat_game = input("\n{} do you want to play again? press Y for Yes and N for No: ".format(username)) if repeat_game.lower() == "y": main() else: print("bye!") def main(): secret_Num = input("\n hey {}! Enter your secret number. Let the computer Guess :-)".format(Username)) try: int(secret_Num) except ValueError: print("How do I add {} + {}?".format(secret_Num, secret_Num)) repeat_process = input("\nYou may want try again? if so, then press Y for Yes otherwise press N to end: ") if repeat_process.lower() == "y": main() else: print("bye!") else: if 1 <= int(secret_Num) <= 10: game(Username,int(secret_Num),3) else: repeat_process = input("\n The number should be between 1-10. You may want try again? if so, then press Y for Yes otherwise press N to end: ") if repeat_process.lower() == "y": main() else: print("bye!") Username = input("\n What is your name buddy?") main()
Tri Pham18,671 Points
- You did greater than 11 not 10. And it only goes into an exception if there's an error. int(input("11")) is perfectly fine to do.
- If its gonna error, its gonna error with int('a non-number string') so secret_num won't get assign to anything.
You should put result = input("Please enter a number from 1 to 10: "). It should never error there. Then use result instead of secret_num in your exception
Alexander Davison65,426 Points
Alexander Davison65,426 Points
What's the error?
|
https://teamtreehouse.com/community/opposite-number-game-problem
|
CC-MAIN-2020-29
|
refinedweb
| 519
| 61.22
|
Have a look at section B.1.3 in the VXL book for examples of how to set up your CMakeLists.txt file. You are missing this line:
FIND_PACKAGE(VXL)
Fred
From: Hao Wu [mailto:haowu128@gmail.com]
Sent: Friday, July 19, 2013 12:17 PM
To: vxl-users@lists.sourceforge.net
Subject: [Vxl-users] HelloWorld
Hi,
I am new to VXL and I just installed it on Windows. I want to test it by building my first project "VXL_HelloWorld" but it failed when building in Visual Studio 2010.
Here is my CMakeLists.txt:
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(VXL_HelloWorld)
IF(VXL_FOUND)
INCLUDE(${VXL_CMAKE_DIR}/UseVXL.cmake)
ENDIF(VXL_FOUND)
ADD_EXECUTABLE(HelloWorld HelloWorld.cxx )
TARGET_LINK_LIBRARIES( HelloWorld vcl )
And here is my source code:
#include <vcl_iostream.h>
int main()
{
// send string "hello world" to the standard output stream cout.
vcl_cout << "Hello world\n";
return 0;
}
After I use CMake to compile and generate the project, I opened the .sln file and try to build it but it failed and gives the following errors:
Error 1 error C1083: Cannot open include file: 'vcl_iostream.h': No such file or directory
2 IntelliSense: cannot open source file "vcl_iostream.h"
3 IntelliSense: identifier "vcl_cout" is undefined
I guess there may be some problem with my CMakeLists.txt.
Could you help me find out the problem?
Thanks and best regards,
Hao Wu
|
https://sourceforge.net/p/vxl/mailman/attachment/4455E9A5C5F75C43947FEC05DE1BCAE223264C35@ALPMBAPA01.e2k.ad.ge.com/1/
|
CC-MAIN-2016-50
|
refinedweb
| 224
| 68.97
|
[SRU] SDL_syswm.h can't find mir_toolkit/mir_client_library.h
Bug Description
I believe something is wrong with MIR support. A daily build of openmw just failed with:
/usr/include/
#include <mir_toolkit/
In SDL_syswm.h:
#if defined(
#include <mir_toolkit/
#endif
the file is:
/usr/include/
http://
openmw buildlog:
https:/
it built successfully until the fix for bug #1295389 libsdl2 commit hit that enabled mir.
Assigning "high" since it has the potentially to cause a large number of FTBFS in the archive.
SRU Info:
*Note* This patch has landed in libsdl2 upstream:
https:/
(which also reverts https:/
1) The issue is we include mir_client_
2) A simple way to test the current Mir problem:
http://
3) Regression potential: Low - upstream has had this change for a month without problem
Related branches
- Martin Pitt: Approve
- Scott Howard (community): Approve
- Diff: 75 lines (+33/-7)4 files modified.pc/applied-patches (+1/-0)
debian/patches/mir_forward_declaration_syswm.diff (+29/-0)
debian/patches/series (+1/-0)
include/SDL_syswm.h (+2/-7)
- Martin Pitt: Approve
- Diff: 91 lines (+41/-7)5 files modified.pc/applied-patches (+1/-0)
debian/changelog (+8/-0)
debian/patches/mir_forward_declaration_syswm.diff (+29/-0)
debian/patches/series (+1/-0)
include/SDL_syswm.h (+2/-7)
ok, so it looks like libsdl2 has to update/use pkgconfig and pass those headers.
This is related to:
/bugs.launchpad .net/mir/ +bug/1161064 /bugs.launchpad .net/mir/ +bug/1161240
https:/
https:/
I don't know what's the best way to handle this - many packages in the archive don't know about mir, and SDL just pulled it in - and SDL isn't telling the build process where MIR is located. There isn't enough time to find them all and fix it before trusty is released.
Since we're so close to an LTS release, should MIR support be dropped from SDL2?
|
https://bugs.launchpad.net/ubuntu/+source/libsdl2/+bug/1306629
|
CC-MAIN-2022-05
|
refinedweb
| 306
| 56.45
|
NRF24+ Module: Spontaneous 5A heating mode?
This is a phenomenon that I've had two or three times already:
- NRF24+ Module from itead.com
- PCB from @sundberg84 Easy PCB because it's awesome
Built a new sensor, works perfectly. Put the sensor into a housing, let it run for a few (last time: less than one) hours and the sensor stops working. Opened the housing that was already warm. The PCB is hot and I burnt my finger on the 3.3v regulator.The NRF24+ is even hotter.
I checked the PCB and saw no problem. Checked my software: all ok. Dared to blow up another NRF24+ ... that worked. Has been working without a flaw since three days.
As I said, this is about the third time that happened. Do you experience that problem too? I rule out a hardware problem on the easypcb and the software, because with another NRF24+ module all is fine...
Could it be an ESD problem? I have no ESD protected setup at home...
Looking forward to your answers
P.S.: the 5A are not measured. I just invented that number.
cu
Markus
@The-Grue said in NRF24+ Module: Spontaneous 5A heating mode?:
I burnt my finger on the 3.3v regulator.The NRF24+ is even hotter.
That's the best clue here - check the wiring to the nrf24 at both ends. Make sure no little strands are where they shouldn't be. The NRF shouldn't get hot at all really. Maybe you have a bad batch or something? Did you add capacitors to the NRF as recommended. If so can you post a photo of the capacitor added to the nrf module?
@The-Grue is it an amplified nrf24 module? Officially the amplified ones only accept 3v3 level at their CE pin, while most 5v designs seem to ignore this.
Or maybe a ground-loop is messing with your setup? It's the pcb running stand-alone when it gets hot or is it eg connected to a power supply and a pc through a serial connection?
I also experienced this in a breadboard setup with jumper wires. After reconnecting the power supply, the nrf cooled down to normal temperature and still worked. I thought that the reason was cheap nrf modules but the same module didn't have issues in other setups. Unfortunately I never got behind the reason of this problem, but it was always in breadboard setup with external power supply (no batteries). Also it was not reproducable and occurred sporadically.
- sundberg84 Hardware Contributor last edited by
@The-Grue - sounds like some sort if hardware issue. I think you can rule out software. Maybe an image if the faulty hardware?
This is the first time I hear about this to be honest - unless there has been for example solder shorts but since its working after changing the radio it seems like an issue with the radio.
Hello, thanks for all your feedback!
I'll send pictures soon. But since I'm using @sundberg84 's easy PCB, I rule out bad wiring. I haven't seen any solder bridges, but I'll have a closer look.
The PCB is only connected to a 9V power supply
Maybe it's realy a bad batch... I thought itead.com is the preferred supplier - are there better ones?
And by the way: the sensor stopped working again ;( I'll have a real close look over the weekend.
cu
Markus
Hello,
I built the board from scratch and am none the wiser
To recap: I have built a mysensors sensor to read the wind speed of an Adafruit Anemometer. That sensor literally burned Nrf24l01+ modules and I have no idea why.
The only special thing about this sensor is that I connected the AREF pin of the Arduino to 3.3V because the Aneometers output is 0.4..2V and I didn't want to waste a ADC bit because of the standard 5V reference voltage. I did this by connecting AREF directly to 3.3V and I let the capacitor from AREF to GND in place.
I connected the new module to a 2 channel lab power supply: 9V to the RAW input (because the Anemometer needs 7 to 12V power supply) with a maximum current of ~100mA. 0.4V to A0 with barely some current flowing to simulate the Anemometer. I powered up the module and everything worked. The module consumed about 23mA which is the value that I expected from earlier tries. Yay!
About 15 minutes later: Communication was broken again. The Arduino LED that indicates SPDIF clock was dark, the Power supply showed >110mA power consumption. Sh*t.
I lowered the Supply voltage to 5V (maybe to cause less damage...) and power cycled the module. It started with 35mA and was working (presentation to the controller and sends wind speed). And then... the consumed current rises! The longer, the faster. I let it run for about 1.5 minutes and the consumed current doubled to more than 60mA.
I'm running out of NRF modules and out of ideas. I attach some pictures that show my module and really hope that you have some new ideas. Did I mess up the AREF?
Ah, what? The forum doesn't allow uploading source code? Well, then as code. * ******************************* * * DESCRIPTION * This sketch reads wind speed information from an Adafruit Wind Speed Sensor 1733 * * * */ // Enable debug prints #undef MY_DEBUG // Enable and select radio type attached #define MY_RADIO_NRF24 // Enabled repeater feature for this node #define MY_REPEATER_FEATURE /** * @def MY_NODE_ID * @brief Node id defaults to AUTO (tries to fetch id from controller). */ #define MY_NODE_ID 105 /** * @def MY_PARENT_NODE_ID * @brief Node parent defaults to AUTO (tries to find a parent automatically). */ #define MY_PARENT_NODE_ID 0 #include <MySensors.h> #include <limits.h> // (External) Reference voltage in Volts // We use the external 3.3V because it's closer to the 2V maximum of the sensor. // This way we loose less of the ADC range #define U_REF_V (3.3) // Set this to the pin you connected the DHT's data pin to #define WIND_ANLOG_PIN A0 #define SECOND (1000) // seconds to milliseconds // Sleep time between sensor updates (in milliseconds) static const uint64_t UPDATE_INTERVAL_MS = 10 * SECOND; // Force sending an update of the temperature after n sensor reads, so a controller showing the // timestamp of the last update doesn't show something like 3 hours in the likely case, that // the value didn't change since; // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms] static const uint8_t FORCE_UPDATE_N_READS = 6 * 5; // each 5 minutes #define CHILD_ID_WIND 0 #define LSB_TO_VOLT (U_REF_V/1024) // V/LSB #define V_MAX_mps (70) // Maximum wind speed in m/s #define U_MIN_V (0.4) // Minimum voltage in V #define U_MAX_V (2.0) // Maximum voltage in V #define SENSOR_PRECISION_MPS (0.1) // precision of the sensor in m/s // m=70/(2-0.4) m/(sV) // t=-0.4*m m/s // v=m*u+t #define M (V_MAX_mps/(U_MAX_V-U_MIN_V)) // m/(sV) #define T (-U_MIN_V*M) // m/s float lastWindSpeed_mps; uint8_t noUpdates; MyMessage msgWindSpeed(CHILD_ID_WIND, V_WIND); float lsbToWindSpeed(const float lsb) { const float u_V = lsb * LSB_TO_VOLT; float speed_mps = M * u_V + T; if( speed_mps <0 ) { speed_mps = 0; } return speed_mps; } void presentation() { // Send the sketch version information to the gateway sendSketchInfo("WindSpeed", "1.1"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID_WIND, S_WIND); } void setup() { analogReference(EXTERNAL); // use the external reference voltage pinMode(WIND_ANLOG_PIN, INPUT); lastWindSpeed_mps = -1; noUpdates = 0; } void loop() { int adcValue = analogRead(WIND_ANLOG_PIN); float windSpeed_mps = lsbToWindSpeed(adcValue); #ifdef MY_DEBUG Serial.print("ADC: "); Serial.println(adcValue); Serial.print("SP1: "); Serial.println(windSpeed_mps); #endif if ( abs(lastWindSpeed_mps - windSpeed_mps) >= SENSOR_PRECISION_MPS || noUpdates== FORCE_UPDATE_N_READS ) { lastWindSpeed_mps = windSpeed_mps; noUpdates = 0; send(msgWindSpeed.set(windSpeed_mps, 1)); #ifdef MY_DEBUG Serial.print("SP2: "); Serial.println(windSpeed_mps); #endif } else { ++noUpdates; } // Sleep for a while to save energy sleep(UPDATE_INTERVAL_MS); }
Here you can see a video with the rising power consumption:
Next days I'll remove the 3.3V modification and try it with the default. The extra bit resolution is not really necessary. But I can't imagine that's the reason.
The Culprit seems to be the yellow capacitor next to the gray 100nF Capacitor. Should be 10uF, I think. If I cool that one with ice spray, power consumption normalizes immediately.
It seems to be really hard to buy high quality components, even at shops that have a good name.
- Technovation last edited by
@The-Grue
That yellow capacitor looks like a tantalum capacitor (hard to be certain from the top view, but I guess it is the same type as the other yellow one on the board on which you can read the printing). In the case of it actually being a tantalum cap, you may have by accident installed it in the wrong orientation. Tantalum caps have a polarity and if wrongly applied (i.e. reverse polarity/voltage) it will typically show a gradual increase in leakage current - what appears to match with your description.
So that is probably one of the reasons why you see tantalum caps being used less nowadays as it is easy to put them in the wrong way and hard to troubleshoot afterwards (visually quickly overlooked).
Hello @Technovation,
as embarrassing as it is: you are completely right
. For more than 30 years, I've either used elkos (where I know they have a polarity) or ceramic capacitors (which don't have one) or used the correct polarity by accident and was completely baffled when I learned that tantalum capacitors have a polarity. It doesn't help that the only indication is so non-descript...
Well, you never stop learning. I'm looking forward to much more stable mysensors
And I apologize for blaming the NRF24 modules and the shops for my ignorance.
- Technovation last edited by
@The-Grue: Don't be embarrassed by it...pretty sure you are not the first one that fell for this trap and certainly not the last one. Hopefully also other readers on the forum can benefit from your (bad) experience in this way.
Thanks for reporting back and good to hear that some of your trust has returned towards the nrf24 and your part shops with a "good name"
.
|
https://forum.mysensors.org/topic/11124/nrf24-module-spontaneous-5a-heating-mode
|
CC-MAIN-2022-33
|
refinedweb
| 1,697
| 65.73
|
All of dW
-----------------
AIX and UNIX
Information Mgmt
Lotus
Rational
Tivoli
WebSphere
-----------------
Java technology
Linux
Open source
SOA & Web services
Web development
XML
-----------------
dW forums
-----------------
alphaWorks
-----------------
All of IBM
What open source development is really like
PDF - A41 KB
PDF - Letter1 KB
Get Adobe® Reader®
Document options requiring JavaScript are not displayed
Discuss
Connect to your technical community
Help us improve this content
Level: Intermediate
Nicholas Chase (ibmquestions@nicholaschase.com), Freelance Writer
06 Feb 2007
The last time I wrote a "Geronimo renegade" column, I was wondering what the big deal was about Spring, and when I followed up, I joked that now I needed someone to tell me why JavaServer Faces (JSF) was so hot. Wouldn't you know it that the next thing that crossed my desk was a request to do a piece on the intersection between Apache Geronimo and Apache MyFaces, focusing on their implementation of JSF? Well, it turns out to have been a good thing. I struck up a conversation with Tim McConnell at IBM®, who's in the process of integrating Geronimo and MyFaces, and I learned a lot more than I expected about how specifications like this actually get implemented.
What is Apache MyFaces?
The first question I needed to know was why Apache Geronimo was even concerned with Apache MyFaces in the first place. Tim explained that it was part of the migration from Java™ 2 Platform, Enterprise Edition (J2EE) 1.4 to Java Platform, Enterprise Edition (Java EE) 5. "Geronimo is already a J2EE 1.4-compliant application server, but as part of the 1.5 specification, JSF needs to be supported, and the way we're doing that is with Apache MyFaces."
Already I was intrigued. Here's a technology considered so important that it has actually been added to the Java EE specification. But what is it? "The idea behind JSF," Tim told me, "is to make it easier for Web application development. It's modeled after the Model-View-Controller (MVC) paradigm. It's actually almost an implementation of that. That's really the idea behind it. A lot of people who haven't done Web development are still familiar with MVC, so they can pick up and learn JSF quickly and more efficiently and develop their Web applications."
That sounded reasonable, but there had to be more. So I sat down to research exactly what JSF was. What I found is that I've been causing myself considerable pain in avoiding JSF.
If you've been doing Java Web development, you already know about JavaServer Pages (JSP). These are pages in which you can embed Java code directly within HTML and have it be executed accordingly. But more important than that, JSP enables you to create custom tags that represent Java code. Not only is this more efficient from a server performance standpoint, but it's much more maintainable and gives non-technical people the ability to edit pages.
JSF takes this process a couple of steps further. It looks at the common things that people need to program into Web pages -- forms, for the most part -- and includes pre-made components -- those custom tags I was talking about -- to help you do it. (MyFaces also includes hundreds of additional components to add functionality.) For example, consider the JSF form shown in Listing 1.
<%@ taglib uri="" prefix="h" %>
<%@ taglib uri="" prefix="f" %>
<html>
<head>
<title>JSF Sample Page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText
</h1>
<h:form
<h:outputText
<h:inputText
<br />
<h:outputText
<h:inputText
<h:commandButton
<h:commandButton
</h:form>
</f:view>
</body>
</html>
Notice that it's a mix of straight HTML along with tags from two tag libraries, each designated as a URI (which represents the namespace) aliased to a prefix. These tags have certain behaviors, which in this case is to output specific HTML. But notice that there's something a little different in the inputText elements. Here it's referencing a specific Java bean, so there might be a class like that shown in Listing 2.
inputText
package com.backstop.renegade;
public class UserBean {
String username;
String password;
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.Password;
}
public void setPassword(String password) {
this.password = password;
}
...
}
This bean represents the data structure you're writing a form for. To tie them together, you have the faces-config.xml file (see Listing 3).
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"">
<faces-config>
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>com.backstop.renegade.UserBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
You'll have to check the Resources for a link to more information on how to set this up, but for now, notice that you link the object name used in the form (userBean) to the class (com.backstop.renegade.UserBean) and specify the scope to refer to a single Web request.
userBean
com.backstop.renegade.UserBean
But JSF has one more trick up its sleeve. You still need to submit the form, but to where? On a traditional HTML page, having different actions for each button would be cumbersome to say the least. JSF lets you take care of the problem by using navigation rules in the faces-config.xml file (see Listing 4).
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"">
<faces-config>
<navigation-rule>
<from-view-id>/pages/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/pages/processlogin.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>register</from-outcome>
<to-view-id>/pages/registration.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>jsfks.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
This way, you can specify where the server should go from your login page, based on the from-outcome, as determined by the action you specified on your buttons. Of course, there are other ways to trigger movement, but that's well beyond the scope of this article.
from-outcome
The point is that JSF simplifies Web development quite a bit. And that's how it got on Tim McConnell's to-do list.
Moving to Java EE (formerly known as J2EE 1.5)
"There was no JSF specification in the J2EE 1.4 requirements, so this is new," Tim explained. "Because this is open source, it's not a concrete plan, but we hope that Apache Geronimo is [Java EE] 5-compliant as of next year, and that would include the JSF 1.2 spec. We're striving to do that in a much more efficient way than we got to J2EE 1.4."
I'm always interested in the inner workings of a project like Geronimo, so I asked Tim, "What's different this time?"
"I think there's more involvement from IBM now," he answered, "more of a push to have it compliant. There are a lot of enterprise customers who won't use it unless it is compliant." He pointed out that there are a number of new specifications in Java EE 5. "So there's a lot of work to do."
Something he'd said earlier intrigued me. "You say it's almost an implementation of the Model-View-Controller pattern. Why almost?"
"It's different because it's Web development," he explained, "and there are little caveats and sophistications that have been added to the specification. For example, what's interesting about one thing that they specify is that they have the notion of events that are triggered when a form -- or even a form element on a Web screen -- is changed, so that the implementer can register to listen to events that are effectively changes to that field. So a programmer can register to listen to events on that field so he doesn't have to check to see if it's changed, because he'll get a notification if it's changed. It's actually pretty slick. To me that's fairly sophisticated in that a lot of the work to expose those events is done by the implementation and not the programmer; the programmer just has to register an interest in that change. The idea is to make development easier."
Tim went on to explain what that means for implementing JSF in Geronimo. "There are some things that are incumbent upon the server in the specifications, such as the APIs that have to be supported. They have to come from the server, not the Web application. For example, in MyFaces 1.1, the programmer -- the person developing the Web application -- just has to include the JAR file, so for 1.2, we need to override that to make sure that it's coming from the [Java EE] 5 stack. The idea is that when it's compliant with [Java EE] 5, the programmer won't have to do that, because it'll be included with Geronimo; they won't have to provide the JAR, just the application itself. There's code that we have to develop to adhere to the specs, and there's code that we have to develop to enable these applications that are using 1.2. Also, the spec gives you a way to determine if the application is using JSF, and then you have to do things of that nature."
Implementing a specification
All of that got me thinking: What is it like to actually implement some of these specifications? I mean, it's nice when you have it and it just works, but how does that happen? It's much like the day my wife made mayonnaise. These things don't magically appear, fully complete; somebody has to build them. (Or get together the eggs and lemon juice and make them, but you get the idea.)
"Right now I am implementing the JSR 88 spec, which is the deployment spec," Tim told me. "That one is not so bad because it's very well written and easy to understand. Not that JSF is hard to understand, but the specification is more about what the exposed API should look like. It's like any other specification. Some are better than others."
I asked Tim if he could provide me with a little bit more detail, and as he pointed out package definitions and descriptions, I began to realize that these specifications are not so different from the specifications we developers deal with every day. The JSR-252 specification, which defines JSF 1.2, defines the packages involved and provides an XML schema for documents that must be supported. What each component must do is defined in the text of the specification.
So implementing a JSR specification is much like implementing any other specification, except that things
are essentially written in stone, because changing them involves going through the Java Community Process,
so it's certainly more complicated than just going to your boss and hashing it out.
Developing for open source versus non-open source
Tim calls working on Apache Geronimo his "dream job," so I asked him what was so special about working on open source.
"The thing about doing open source development is that your contribution is actually the code that you develop. You don't get to become a committer on Geronimo or any other open source that I know of without demonstrating your level of proficiency with Java coding or coding in general, without contributing code to it. So in a sense, it's really 'code speaks the loudest.' To me there's good and bad about that, but it's just the way that open source has evolved."
Tim is a software engineer for IBM proper -- as opposed to solely working on Geronimo -- so I asked him how open source differed from commercial product development. "In open source [development]," he told me, "once you contribute code, it's reviewed by the community, so everyone has a chance to look at it, review it, and give you feedback. That's the process. Product development at IBM is a lot more stringent. You have a development methodology that's followed, and then you have distinct phases: analysis, plan, design, implementation, unit test, function and system test.
"You do that in open source [development]," he continued, "but it's a little more concise. You don't have really distinct phases. In Geronimo, it's all community driven, but in product development, your work is typically dictated based on the architecture of the product. In open source, the community agrees it will do this one thing, and let's say this one thing is [Java EE] 5 compliance. The thing that's neat about open source is that anybody can work on anything they want to. Like, you say 'I'll work on JSF, and I'll work on the JSR 88 deployment spec.' So you publish that, and you get feedback from the community. They say they're fine with it, and you say, 'This is how I plan to to this,' and the community reviews and either agrees or doesn't do anything, which is a kind of implicit agreement. There's more freedom, because you can work on just about anything once you show you can do it and you become a committer. So as a developer, you do your unit testing, obviously, and the review process is part of the committing of the code, because once you commit, everyone can see what you did and review it and comment on it. So there's no distinct schedule, as in, in two weeks we'll be in this phase. Particularly for IBM product development, it's a very rigid methodology, which is good, because in my experience you get good quality software. The quality of the open source software is very good too, it's just a different methodology."
But Tim had one more distinction between open source and commercial product development: "Open source is a lot more fun, too; it really is."
Summary
Tim had given me a lot to think about. First, I had a new tool in my arsenal: JSF in general and Apache MyFaces in particular. I've been using JSP for years; this seems like a great way to simplify application development. Just the navigation rules can simplify development, so when you add in all of the other features I didn't have room to touch on in this article, you have a real winner here!
Tim had also given me some insight into the real world of contributing to an open source project, demystifying the process of implementing a specification and working with the community. a registered trademarks of IBM in the United States, other countries or both. Java is a trademark of Sun Microsystems in the United States, other countries, or both. Other company, product, or service names may be
trademarks or service marks of others.
|
http://www.ibm.com/developerworks/java/library/os-ag-renegade12/
|
crawl-002
|
refinedweb
| 2,536
| 62.88
|
Tools for talking to the Tessitura API
Project description
Tessitura
Tools for talking to the Tessitura API from Python. This is all just wet paint at the moment.
Requires Python 3.6+
To install just do:
$ pip install tessitura
To use see the following example:
import tessitura import pprint endpoint = "" credentials = "username:group:location:password" # The REST API method you wish to call. This may need to be created with other information depending on the request, such as a session id -- See Tessitura documentation for more information. Please note there should be no trailing slash at the end. method = "Diagnostics/Status" # The type of request you wish to make. Currently supports GET and POST. request_type = "GET" # Use this to add any query string parameters to a GET request params = {} # Use this to add any form data to a POST request data = {} # Call the API rsp = tessitura.rest_call(endpoint, credentials, request_type, method, params=params, data=data) # Print out the results in JSON format pprint.pprint(rsp)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/tessitura/0.0.4/
|
CC-MAIN-2021-10
|
refinedweb
| 188
| 56.55
|
Wikipedia's Wales Reverses Decision on Problem Admin 241."
But more importantly... )
Wait and see if he actually does resign, first. By the way, I love the fact that his WP user page [wikipedia.org] is headed "stamus contra malum" -- "we stand against evil." Suuuuure you do, Essjay.
Jimbo's change of mind is a good thing but I suspect it's too late. A lot of damage has been done: journalists will have a field-day with this fiasco, and WP now has a reputation as a community that rewards lying. Not a good way of attracting contributors; not honest ones, at least. Couldn't be much worse, really. Well, no, it)
Wait a second here. Of course Jimbo knew that "Essjay" was not Essjay's real name, since "Essjay" isn't a person's name. The point is that, if Jimmy's company, Wikia, hired Essjay last December or January, then Essjay had to come clean then about the fact that he wasn't a tenured Ph.D. theologian guy after all. That's heavy-duty deception that Jimmy presumably had to have learned about then. Indeed, Jimmy admitted that he knew as much The New Yorker: what else was "I don't have a problem with it" refer to? All that Jimmy says he learned this morning is that Essjay used his false credentials to win debates on Wikipedia. And he couldn't be bothered to check whether his employee had done this? And isn't it obvious, in any case, that Essjay must have risen through the Wikipedia ranks faster partly on the strength of his credentials?
These are legitimate questions, not "cheap shots.")
So the argument about credentials being irrelevant, is in fact itself irrelevant, as it is the deception that is the issue, not the perceived effects of it in influencing Wikipedia editing.
Bizarrely, Wales appears to think the latter is the most important thing, and that up until he found out about that, was perfectly happy with the deception.
This suggests a very big disconnection from reality for the figurehead (indeed more than that) of a project like Wikipedia.
Re: )
"Wales has been a passionate adherent of Ayn Rand's Objectivism.. In general, Wikipedia may be totally discredited by this scandal.
One nagging question that I have is why there is no push to validate academic credentials on Wikipedia. Ordinary users that do not claim to have any academic credentials beyond their own knowledge are fine, ones that claim to have advanced degrees in such-and-such should be required to prove this, or at least be able to validate their credentials when asked. I have no idea how this would be done, only that it SHOULD be done.. Essjay is an excellent example as to why.
I shudder to think how many more Essjays are out there right now, editing articles and claiming expertise, when in fact they have none.
-PxB
Re: )
Mod the parent up.
This is very serious for Wikipedia in the real world. You can pretty much assume all the hagiographies written in the media recently will end. Essjay lied to the New Yorker and a pulitzer prize winning reporter; and Jimbo Wales backed him up. This will taint every serious article written by a journalist from this point forward.
As for Wikipedia and academia, this is the death-knell. The ultimate authority at Wikipedia -- Wales -- stated plainly that faked credentials don't matter.
then isn't this a serious blow for The New Yorker? (Score:3, Insightful)
Re: (Score:2)
that doesn't address the issue, though (Score:2)
Re: (Score:2, Insightful)
Wikipedia is not built on credentials. That Essjay occasionally pointed to his hoax bio when editing articles may have influenced other editors, but did not gain him special privileges. The privileges he does (to this day) have are janitorial, not editorial, and were based on the fact that he made thousands and thousands of edits, most of them administrative in nature (of the 19891 edits he made, only 1372 were in the article namespace -- see edit count tool [wikimedia.de]). There is no process by which a person with an
Wait, wait... are you suggesting that citations from the Wikipedia should be acceptable for academic research? Even without this case of someone contributing with fraudulent credentials, the Wikipedia just isn't authoritative enough to cite.
Don't get me wrong. I love the Wikipedia. It's incredibly useful and it's a great example for people to understand the power of mass-collaboration that the internet allows. When someone brings up a topic I'm not familiar with, the Wikipedia is often the first place I look to get an overview. However, there is nothing, absolutely nothing, which certifies that any given fact in the Wikipedia is going to be correct at any given time. Sure, the general ideas are probably correct (excepting cases of vandalism, which happens too), and incorrect facts are likely to get fixed sooner or later. However, there isn't any authority that is even attempting to make sure that the page you're about to load will be absolutely correct at the exact moment you load it.
College professors refuse to accept citations from Wikipedia are right to refuse. This is especially true given that they're dealing with fricken college students. If you're a college student, it's your job to do research. You have few responsibilities other than to ensure that your research is reliable, and if you can't handle that, then what the hell are you doing in college?
Re: (Score:2)
I don't see how this changes anything (Score:2)
In any case, I'm in academia myself, and plenty of people here use it. You just have to, like any other source, use it appropriately. I wouldn't cite Wikipedia as an authoritative source for scientific facts, but then I wouldn't cite Britannica as an authoritative source for scientific facts, either. What I (and most people I know
Re: (Score:2)
Oh rubbish. Hardly anybody will remember it in a month - although I'm sure Larry Sanger will. Hey Larry, you say this will determine how much you personally will support Wikipedia in the future, so in what ways do you support Wikipedia now? Apart from critising it, that is, a necessary job which you do fairly well, but not as well (or as fervently) as Andrew Orlowski, among others.
And I don't give a FRA about whether college profs accept Wikip)
Some of us have known for a long time that Wikipedia administrators are evil. See what the highly reliable Conservapedia [conservapedia.com] has to say about them:
As everyone knows, Conservapedia editors are all, by any practical definition of the words, foolproof and incapable of error.
Re: )
Umm, he claimed to be a widow with kids. If I say that I'm black and that I think blacks are no longer suffering discrimination in society that carries more weight than if I was perceived as a white guy saying "blacks are not discriminated against". Now you may say that it shouldn't. And I agree it shouldn't carry more weight. But the fact is that it
Re: (Score:3, Insightful)
There is a massive difference between writing a letter to your brother's newspaper and writing for an encyclopedia. Few would take a letter in a newspaper as more than a single example or an opinion, if they believed it at all. An encyclopedia is supposed to consist of a higher grade of)
Most of us put "lying" and "misleading" on roughly the same footing.
Yes. Because at this point, it's probably impossible to tell how much influence he improperly exerted through his lies. Every single article he's touched has to be considered tainted until it can be generally agreed that:
Essjay's damage is particularly bad because it could be so subtle. How many people deferred to his judgment at the expense of correctness? We'll probably never know.
Indeed: so what? Silence Dogood was a middle-aged widow. What particular authority did that lie grant Franklin, assuming that he wasn't writing about childbearing or what it's like to lose your spouse? Essjay, though, directly stated that he had the educational background to make authoritative statements in his pages. Surely you can see that there's much more than a semantic difference between the two actions?
Essjay screwed you over.
but people don't really defer to credentials much (Score:2)
So now apparently Wikipedia is unreliable because it: 1) defers too much to experts; and also 2) doesn't defer enough to experts.
Re: (Score:2)
But everyone else seems to; that's the Slashdotter's constant lament. And Wikipedia isn't just "Wikipedians", but lots of regular people who have something to add to an article or two. A jaded editor isn't likely to be bullied around, but that's not the kind of person this hurts most.
but on Wikipedia, he had no 'arbitrary authority' (Score:2)
Re: (Score:2, Funny)
I vote to keep essjay deleted on grounds of non notability.
Sucks to be on the receiving end of WikiBureaucracy doesn't it essjay
|
https://slashdot.org/story/07/03/03/233224/wikipedias-wales-reverses-decision-on-problem-admin?sdsrc=prev
|
CC-MAIN-2017-04
|
refinedweb
| 1,547
| 62.98
|
Hi all
I'm a real newbie to c++ and have the following issue that I was hoping you guys could solve for me.
I want to use strings end up with error :-( Heres my code
#include <iostream.h>
#include <string.h>
int main(int argc, char* argv[])
{
int fred;
string jas;
fred = 0;
cout << "In main\n" << fred;
return 0;
}
When I try and compile this I get error C2065: 'string':undeclared identifier, and this is driving me nuts for something so simple...
Any ideas what I need to do to overcome this? I've hunted through MSDN and it seems to imply that the header I included is correct so something is obviously up...
I have noticed that if I only include <string> I can sucessfully declare a string by doing std::string fred.
Should I always use std::string or should I be able to use the code in my example.
Thanks for advice!!
|
https://cboard.cprogramming.com/cplusplus-programming/52837-simple-string-query.html
|
CC-MAIN-2017-51
|
refinedweb
| 157
| 80.21
|
Okay, so if you're programming in C++, and you don't know what Precompiled Headers are, chances are that compiling a project takes you something like 4 seconds, and on bigger projects it can even take 20 seconds, and much more just for a simple build.
Obviously, this gets very frustrating.
So if this is the case, this tutorial is a gold-mine for you. this knowledge was for me when I learned it.
Precompiled Headers have literal meaning.
They are headers, that the compiler compiles, then saving them in a file (which I'll describe soon), and uses that file when compiling (which leads to saving you a lot of time).
How?
Instead of building the header files over and over again, at each build, we just hold that information inside a file.
Usualy it ends with the extension .pch and .gch.
So how can we do it?
We create a header file. usually called stdafx.h. it will hold the header files we want to precompile.
Those header files would usually be specific headers that we use frequently in the project.
We'll then create a cpp file that will #include the stdafx.h file we created.
We'll let the compiler know we want to use precompiled headers.
And finally, we'll use them, simply by including stdafx.h.
So let's begin:
Creating stdafx.h
Create a header file, name it stdafx.h for learning purposes. you can actually name it however you want but it's usually named like so.
In the file use the directive #pragma once, and then you can begin inserting the header files you're using. for this instance I'll use Windows.h
stdafx.h
#pragma once #include <Windows.h> // You can #include much more header here of course. this is the place!
Creating stdafx.cpp
Now you'll need to create another file, that will just include the header file we just created.
Name it stdafx.cpp for now (once again, you can name it however you want).
You just include stdafx.h here! YOU DO NOT INCLUDE ANY MORE HEADER FILES HERE!
stdafx.cpp
#include "stdafx.h"
That's it.. that's the whole file.
Setting the compiler
* I'm using Visual Studio. if you use a different compiler, find out how it is done by yours.
Now, we got our files but they're no different from any other files in our project (and in their essence - they are).
So we need to let the compiler know they are actually precompiled headers, and not just source code.
So in Visual Studio to do this.
Press Alt+F7 or at the Visual Studio's menu go to Project --> Project Properties.
Navigate to:
Configuration Properties --> C/C++ --> Precompiled Headers
Set the Precompiled Headers property value to Create (/Yc).
And make sure the Precompiled Header File property value holds the correct name for your precompiled header file. (in our case stdafx.h).
Using the headers
Now you #include stdafx.h to your project's files (and remove any #include you already had there which exists in stdafx.h, of course).
And that's it. have a first build so the compiler will create the file so it won't be very fast. but from there your build would take 1 or less then a second.
Good luck.
If you found any errors or mistakes, feel free to let me know.
|
http://www.dreamincode.net/forums/topic/281665-precompiled-headers-fast-build/
|
CC-MAIN-2016-30
|
refinedweb
| 571
| 77.53
|
Marcus
OO Game Design
#1 Members - Reputation: 122
Posted 26 November 1999 - 07:15 PM
Marcus
#2 Members - Reputation: 122
Posted 23 November 1999 - 10:25 AM
You should just pass the right parameters (ie, the surface) to the function which draws the sprite.....
That's what I would do
------------------
Dance with me......
#3 Members - Reputation: 134
Posted 23 November 1999 - 11:20 AM
1 - DirectDraw. Just blits in DX and inits DX.
2 - Blitting. Abstraction for blitting, so its API/OS independent.
3 - Draw Queue. Makes a queue that can add/clear list of things to draw. Can draw images, text, animations, etc.
4 - Elements, like sprites and text. These can each have things like sprite->Draw(). text->Draw(). Which will create an index in the DrawQueue...
-Geoff
#4 Members - Reputation: 122
Posted 23 November 1999 - 11:39 AM
Well, some people will tell me I am stupid, but I would create a global instance of class DrawManager.
Define this global variable somewhere in your main.cpp or winmain.cpp or something like that like so:
DrawManager MyDrawManager;
In your main.h or winmain.h or something like that put in a:
extern DrawManager MyDrawManager;
Well, that's all. Now you have access to MyDrawManager from everywhere in your program (you will have to include main.h into the implementation file of sprite. Then you could do something like that:
.....
#include "main.h"
void Sprite:
raw(long x, long y)
{
MyDrawManager.DrawSprite(this,x,y);
}
Too many global variables are shit, but a few of them are great, cause you have access to them everywhere without casting pointers around all over the time. Pointers are dangerous cause they cause a GPF when they are NULL, and checking them all the time is shit, too !!
Hope this helps.
Phillip
#5 Crossbones+ - Reputation: 1450
Posted 25 November 1999 - 01:25 AM
Now you see that the Instantiating classes needs to know details of the DisplayManager (like what buffering, unless you blit all of them EVERY frame)...so I recommend one of the following....global variable or static class memeber (IF you do not intend to support multiple monitor or video card setups)..otherwise you might need to pass the DisplayManager to each of the redraw functions...this way additional monitors can be added by just making TWO seperate Image lists...each one associated with a particular DisplayManager.
I could send you source or look at your source if you'd like.
#6 Anonymous Poster_Anonymous Poster_* Guests - Reputation:
Posted 25 November 1999 - 03:50 PM
class Game {
int score;
public:
int Give_Score(){return score;}
void Change_Score(int score1){score=score1;}
};
Then if yo need to print score jus do :
printf("WHATEVER:%s",Game.Give_Score());
and yo no how to change score
I think thatl work
#7 Members - Reputation: 122
Posted 25 November 1999 - 04:27 PM
- Splat
#8 Anonymous Poster_Anonymous Poster_* Guests - Reputation:
Posted 26 November 1999 - 07:15 PM
|
http://www.gamedev.net/topic/4194-oo-game-design/
|
CC-MAIN-2014-42
|
refinedweb
| 488
| 66.13
|
Standards, Environments, and Macros
- profile within a function
#define MARK #include <prof.h> void MARK(name);
MARK introduces a mark called name that is treated the same as a function entry point. Execution of the mark adds to a counter for that mark, and program-counter time spent is accounted to the immediately preceding mark or to the function if there are no preceding marks within the active function.
name may be any combination of letters, numbers, or underscores. Each name in a single compilation must be unique, but may be the same as any ordinary program symbol.
For marks to be effective, the symbol MARK must be defined before the header prof.h is included, either by a preprocessor directive as in the synopsis, or by a command line argument:
cc –p –DMARK work.c
If MARK is not defined, the MARK(name) statements may be left in the source files containing them and are ignored. prof –g must be used to get information on all labels.
In this example, marks can be used to determine how much time is spent in each loop. Unless this example is compiled with MARK defined on the command line, the marks are ignored.
#include <prof.h> work( ) { int i, j; . . . MARK(loop1); for (i = 0; i < 2000; i++) { . . . } MARK(loop2); for (j = 0; j < 2000; j++) { . . . } }
|
http://docs.oracle.com/cd/E18752_01/html/816-5175/prof-5.html
|
CC-MAIN-2013-48
|
refinedweb
| 224
| 72.76
|
C++ File Input/Output
Reliability
When you use C++-style I/O, the system automatically detects the type of the variable and performs the approbate conversion. It's impossible to get the types wrong.
With C-style I/O, it's easy to get the arguments to a std::printf mixed up, resulting in very strange results when you run the program. What's worse is that most compilers do not check std::printf calls and warn you if you make a mistake.
std::gets(line);
is exactly like:
std::fgets(line, INFINITY, stdin);
If there are too many characters in an input line, the std::gets function will cause a buffer overflow and trash memory. This single function and its lack of bounds-checking has to be responsible for more crashes and security holes than any other single C function.[2] You should never use it. You can get in enough trouble with the more reliable C functions without having to play Russian roulette with this one.
Speed
I've done some benchmarks on C and C++ I/O for binary files. In general I've found the C I/O to be much faster. That's because the C I/O system is less flexible and has to deal with less overhead than the C++ system.
TIP: I'm not talking about formatted I/O, just raw binary I/O. If you do formatted I/O in either system, you can expect your speed to go down tremendously. It's the single slowest system in the entire C and C++ library.
Which Should You Use?
Which I/O system is best? That depends on a large number of factors. First of all, any system you know is always going to be easier to use and more reliable than a system you don't know.
However, if you know both systems, C-style I/O is good for the simple stuff. If you're not doing anything fancy with classes and just want to write simple formatted reports, the C I/O system will do the job. However, for larger jobs, the C++-object oriented system with its object-oriented I/O system handles complexity and organizes complex information much better than C-style I/O.
But if you're learning I/O for the first time, I suggest that you stick with one I/O system, the C++ one. Learn C-style I/O only if you're forced to. (Say, for instance, you have to maintain some legacy code that uses the old C-style system.)
Programming Exercises
Write a program that reads a file and counts the number of lines in it.
Write a program to copy a file, expanding all tabs to multiple spaces. (For historical reasons--the Teletype again--almost all text files use a tab setting of 8 characters.)
Write a program that reads a file containing a list of numbers and writes two files, one containing all the numbers divisible by 3 and another containing all the other numbers.
Write a program that reads an ASCII file containing a list of numbers and writes a binary file containing the same list. Write a program that goes the other way so you can check your work.
Write a program that copies a file and removes all characters with the high bit set (((ch & 0x80) != 0)).
Design a file format to store a person's name, address, and other information. Write a program to read this file and produce a file containing a set of mailing labels.
Answers to Chapter Questions
The problem is that you are writing an ASCII file, but you wanted a binary file. In Unix, ASCII is the same as binary, so the program runs fine. In MS-DOS/Windows, the end-of-line issue causes problems. When you write a newline character (0x0a) to the file, a carriage return (0x0D) is added to the file. (Remember that end-of-line in MS-DOS/Windows is <carriage return><line feed>, or 0x0d, 0x0a.) Because of this editing, you get an extra carriage return (0x0d) in the output file.
To write binary data (without output editing) you need to open the file with the binary option:
out_file.open("test.out", std::ios::out | std::ios::binary);
The std::printf call does not check for the correct number of parameters. The statement:
std::printf("The answer is %d\n");
tells the std::printf to print the string "The answer is" followed by the answer. The problem is that the parameter containing the answer was omitted. When this happens, std::printf gets the answer from a random location and prints garbage.
Properly written, the std::printf statement is:
std::printf("The answer is %d\n", answer);
The std::printf call does not check the type of its parameters. You tell std::printf to print an integer number (%d) and supply it with a floating-point parameter (result). This mismatch causes unexpected results, such as printing the wrong answer.
When printing a floating-point number, you need a %f conversion. Properly written, our std::printf statement is:
std::printf("The answer is %f\n", result);
The problem is that std::fgets gets the entire line, including the newline character (\n). If you have a file named sam, the program reads
sam\n and tries to look for a file by that name. Because there is no such file, the program reports an error.
The fix is to strip the newline character from the name:
name[strlen(name) - 1] = '\0'; /* Get rid of last character */
The error message in this case is poorly designed. True, you did not open the file, but the programmer could supply the user with more information. Are you trying to open the file for input or output? What is the name of the file you are trying to open? You don't even know whether the message you are getting is an error, a warning, or just part of the normal operation. A better error message is:
std::fprintf(stderr, "Error: Unable to open %s for input\n", name);
Notice that this message would also help us detect the programming error. When you typed in "sam", the error would be:
Error: Unable to open sam
for input
This clearly shows us that you are trying to open a file with a newline in its name.
1. If you take a look at the C++ standard, you'll notice that the formal definition of these functions is somewhat more complex. I've simplified the definition for this book, but this definition is compatible with the formal one.
2. As I am writing this, Microsoft has just released a security patch to Windows XP to fix a buffer overflow bug.
Practical C++ Programming, 2nd Edition
By Steve Oualline
O'Reilly & Associates, December 2002
ISBN: 0-596-00419-2
Page 9 of 9
|
https://www.developer.com/net/cplus/article.php/10919_2119781_9/C-File-InputOutput.htm
|
CC-MAIN-2017-51
|
refinedweb
| 1,150
| 71.14
|
int wait(statusp) union wait *statusp;
int wait((union wait *)0)
#include <sys/time.h> #include <sys/resource.h>
int wait3(statusp, options, rusage) union wait *statusp; int options; struct rusage *rusage;
int wait4(pid, statusp, options, rusage) int pid; union wait *statusp; int options; struct rusage *rusage;
WIFSTOPPED(status) union wait status;
WIFSIGNALED(status) union wait status;
WIFEXITED(status) union wait status;
This is the BSD specification for wait. For the POSIX specification, see wait(2P).
wait() delays its caller until a signal is received or one of its child processes terminates or stops due to tracing. If any child has died or stopped due to tracing and this has not been reported using wait, return is immediate, returning the process ID and exit status of one of those children. If that child had:
Other members of the wait() union can be used to extract this information more conveniently:
The other members of the wait() union merely provide an alternate way of analyzing the status. The value stored in the w_status field is compatible with the values stored by other versions of the UNIX system, and an argument of type int * may be provided instead of an argument of type union wait * for compatibility with those versions.. (This information is currently not available for stopped processes.) `union wait', as returned by wait, wait2,.
wait, wait3, and wait4() are automatically restarted when a process receives a signal while awaiting termination of a child process, unless the SV_INTERRUPT bit is set in the flags for that signal.
wait3() and wait4() return 0 if WNOHANG is specified and there are no stopped or exited children, and return the process ID of the child process if they return due to a stopped or terminated child process. Otherwise, they return a value of -1 and set errno to indicate the error.
wait, wait3, and wait4 will terminate prematurely, return -1, and set errno to EINTR upon the arrival of a signal whose SV_INTERRUPT bit in its flags field is set (see sigvec.2 and siginterrupt.3
wait( (union wait *) 0)
Otherwise the compiler might complain.
Created by unroff & hp-tools. © by Hans-Peter Bischof. All Rights Reserved (1997).
Last modified 21/April/97
|
http://www.vorlesungen.uni-osnabrueck.de/informatik/shellscript/Html/Man/_Man_NeXT_html/html2/wait.2.html
|
CC-MAIN-2013-20
|
refinedweb
| 369
| 62.07
|
06 February 2012 05:13 [Source: ICIS news]
NEW DELHI (ICIS)--Indian polystyrene (PS) demand is likely to decline by 3.5% in 2011-12 on sluggish market conditions, an industry source said over the weekend.
A weak appliances segment affected demand, which is likely to settle at 250,000 tonnes for the year ending 31 March 2012, he added at the sidelines of the 8th PlastIndia exhibition.
The appliances segment accounts for 40% of the PS demand in the country.
“It was a bad year for the industry. ?xml:namespace>
Also, there is a shift in demand in the television sector, as the boom in the LCD TV market is increasingly eroding the demand for PS in the TV segment, he added.
However, the expandable PS (EPS) market, estimated at around 80,000 tonnes, is growing with companies working hard to push the product in the insulation and construction segments, he said.
The 8th PlastIndia exhibition is a six-day event which will end on 6 February.
Additional reporting by Ong Sheau Ling
|
http://www.icis.com/Articles/2012/02/06/9529522/india-ps-demand-may-decline-by-3.5-in-2011-2012-industry.html
|
CC-MAIN-2015-11
|
refinedweb
| 174
| 61.26
|
(preventing race condition):
// java program to demonstrate // use of semaphores Locks import java.util.concurrent.*; //A shared resource/class. class Shared { static int count = 0; } class MyThread extends Thread { Semaphore sem; String threadName; public MyThread(Semaphore sem, String threadName) { super(threadName); this.sem = sem; this.threadName = threadName; } @Override public void run() { // run by thread A if(this.getName().equals("A")) { B to execute Thread.sleep(10); } } catch (InterruptedException exc) { System.out.println(exc); } // Release the permit. System.out.println(threadName + " releases the permit."); sem.release(); } // run by thread B else { A to execute Thread.sleep(10); } } catch (InterruptedException exc) { System.out.println(exc); } // Release the permit. System.out.println(threadName + " releases the permit."); sem.release(); } } } // Driver class public class SemaphoreDemo { public static void main(String args[]) throws InterruptedException { // creating a Semaphore object // with number of permits 1 Semaphore sem = new Semaphore(1); // creating two threads with name A and B // Note that thread A will increment the count // and thread B will decrement the count MyThread mt1 = new MyThread(sem, "A"); MyThread mt2 = new MyThread(sem, "B"); // stating threads A and B mt1.start(); mt2.start(); // waiting for threads A and B mt1.join(); mt2.join(); // count will always remain 0 after // both threads will complete their execution System.out.println("count: " + Shared.count); } }
Output:
Starting A Starting B B is waiting for a permit. B gets a permit. A is waiting for a permit. B: -1 B: -2 B: -3 B: -4 B: -5 B releases the permit. A gets a permit. A: -4 A: -3 A: -2 A: -1 A: 0.
|
https://www.geeksforgeeks.org/semaphore-in-java/
|
CC-MAIN-2018-09
|
refinedweb
| 263
| 52.76
|
create wireframe outline corners around bounding box More...
#include <vtkOutlineCornerSource.h>
create wireframe outline corners around bounding box
vtkOutlineCornerSource creates wireframe outline corners around a user-specified bounding box.
Definition at line 29 of file vtkOutlineCornerSource.h.
Definition at line 32 of file vtkOutlineCornerSource.h.
Return 1 if this class is the same type of (or a subclass of) the named class.
Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h.
Reimplemented from vtkOutlineSource.
Reimplemented from vtkOutlineSource.
Methods invoked by print to print information about the object including superclasses.
Typically not called by the user (use Print() instead) but used in the hierarchical print process to combine the output of several classes.
Reimplemented from vtkPolyDataAlgorithm.
Construct outline corner source with default corner factor = 0.2.
Set/Get the factor that controls the relative size of the corners to the length of the corresponding bounds.
This is called by the superclass.
This is the method you should override.
Reimplemented from vtkPolyDataAlgorithm.
Definition at line 55 of file vtkOutlineCornerSource.h.
|
https://vtk.org/doc/nightly/html/classvtkOutlineCornerSource.html
|
CC-MAIN-2020-34
|
refinedweb
| 173
| 53.68
|
I have managed to solve the problem putting
LoadModule modules/mod_python.so
as the last line of all the LoadModule commands and
AddModule mod_python.c
as the last line of all the AddModule commands.
This helps to kill the problem which I had previously.
Anyway, my test CGI script is very simple.
-- Start of script --
import cgi, os, sys
print 'Content-type: text/plain'
print
print os.environ()
print cgi.FieldStorage()
-- End of script --
On Wed, Nov 21, 2001 at 01:51:59PM -0500, Gregory (Grisha) Trubetskoy wrote:
>
> It would be hard to identify the problem without the seeing the script.
> POST should work fine.
>
> On Thu, 22 Nov 2001, Michael Teo wrote:
>
> >
> > I have forgotten to include my system info.
> > Apache 1.3.22
> > modpython 2.7.6 (compiled as a DSO with a non-threaded Python 2.1.1)
> >
> > Btw, the script works if I do a HTTP GET instead of a HTTP POST.
> >
> > On Thu, Nov 22, 2001 at 12:32:35AM +0800, Michael Teo wrote:
> > >
> > > Have anyone tried doing a HTTP POST from a form to a script running under
> > > mod_python.cgihandler ?
> > >
> > > I keep getting this error
> > > python_handler: Dispatch() returned nothing.
> > >
> > > If I disable mod_python and run this script under the CGI environment, it
> > > works fine.
--
Michael Teo <mailto:michaelteo at bigfoot.com>
PGP 0x6C846A9C DB:7D:51:D4:4D:AB:97:79:E4:68:D9:07:94:36:D5:1A:6C:84:6A:9C
0x6937FB05 08:50:A1:4D:2E:45:58:60:DE:71:1F:30:63:54:EF:7B
|
http://www.modpython.org/pipermail/mod_python/2001-November/012260.html
|
crawl-002
|
refinedweb
| 256
| 77.03
|
You'll need to convert from storage-conf.xml to cassandra.yaml and
import your schema at some point. NEWS.txt outlines the general
approach (see Upgrading).
Gary.
On Tue, Nov 2, 2010 at 13:31, Erik Onnen <eonnen@gmail.com> wrote:
> Hello,
> We're planning an upgrade from 0.6.7 (after it's released) to 0.7.0 (after
> it's released) and I wanted to validate my assumptions about what can be
> expected. Obviously I'll need to test my own assumptions but I was hoping
> for some guidance to make sure my understanding is correct.
> My core assumptions are:
> 1) After taking the upstream services offline and inducing a flush on 0.6
> nodes so that all data is compacted, I should be able to start 0.7 binaries
> on top of the 0.6 data files with no issue.
> 2) When upgrading, I can change from RackUnawareStrategy to a
> PropertyFileSnitch configuration. My understanding is that read repair will
> kick in for the missing facility replicas at a rate roughly equivalent to
> the read repair chance.
> 3) While read repair from #2 is occurring, the now incorrect replica nodes
> will continue to be capable of servicing requests for the data that has not
> been migrated to the correct replicas.
> Thanks!
> -erik
|
http://mail-archives.apache.org/mod_mbox/cassandra-user/201011.mbox/%3CAANLkTi=5O+mDU+CeuBs9kfX-RYYpNJE0hr2OM31tKAry@mail.gmail.com%3E
|
CC-MAIN-2015-35
|
refinedweb
| 215
| 67.45
|
Agenda is to resolve Issues raised during last call.
JT Covered in WCAG already.
PJ This is more important when we are dealing with a user agent.
JT Quite a few WYSIWYG tools move the content around through positioning tricks that re-order the presentation without reordering the document source. But this is already covered in the WCAG
PJ An example where it is not addressed is a MAP which has AREA somewhere else, not related to the presentation
IJ The IMG element does not need to be located with the MAP
WC If someone doesn't load the image they should get the order right still. This is very fine HTML.
PJ I think it is more user agent than tool issue
DD In this case there is an explicit link to the MAP
PJ If you're just a screen reader you don't understand that link
JT It is also an AU tool
PJ It is really UA
JT There are tools that let you create a file out of order
CMN for example you can take a paragraph from the end and have the CSS generated to make it first
PJ Why ask the AU tool, and not the user agent?
WC in the example of MAP it is user agent, but for style sheets you have to rely on the order, and then it is covered by 6.1
PJ We should note that it is covered by WCAG and UA
DB Thre are times when you want to be able to control the order, eg put a navbar at the bottom and make it present at the top
Resolved: covered by WCAG and UA@@
JT Raised by Jim Thatcher.
PJ This is the tool and the author
JT What we need to put here is clarification. Generally we need to distinguish what is done by the tool
IJ All checkpoints use imperative for tool
JT That might be too subtle
PJ I didn't know it
WC If I don't use a WYSIWYG tool, and I hack the HTML...
JT He's saying that is the author's choice.
GR If you are asking it to transform into a table it can ask for the accessibility information
JT The point is good - there is a misunderstanding of what is the tool's job and what is left to the author. We need to acknowledge that the tool cannot produce the content by itself
WC That makes sense. I think a lot of the checkpoints get it
JT Make a clarification, or in the introduction?
DD Say in the intro that anything that is directly done by the author like editing the source is beyond the control of the tool. It has to check what they do.
PJ 1.2, 2.2, 4.3 are closely related - we need to write them carefully to make sure they do not get confused. So 1.2 the intent is that the tool needs to generate content automatically that conforms.
WC say "ensure automatically generated content conforms
DB Need to distinguish what can and what must
PJ This seems to fit in 2 - generating standard markup
IJ/JT That would work well
BR 1.2 could say support production of content that conforms to WCAG
JT No, propose moving it to 2 and say "generate content"
PJ 2.2 says that already
IJ 1.2 is accessible markup, 2.2 is in conformance with a published specification
GR Do we want to maintain the idea that the tool should prompt for information, etc.?
IJ isn't that 1.1?
GR No. For things that need manual checking we should say so.
JT If we say 1 is what we want the author to do, 2 is what we want the tool to do, we have to make sure that is there.
CMN Guideline 3 is all about this
DB The intro to 1 talks about auto-generated markup - we would need to change that
PJ Do we agree that Guideline 1 is for the author and guideline 2 is for the user agent?
CMN No, that represents a big change
IJ We could split 1.2 into author and auto
PJ is that different from 2.1?
IJ Yes
CMN The logic was that 2 talked about general conformance to standards, and then 1 talked about conformance to accessibility standards in particular
PJ I want to open with "support the accessibility features" and separate that out from being standard compliant.
JT So 2 was in support of standards. Do we need to clarify the role of the author vs the tool in 1.2?
PJ 1.1 - Ensure the author can ... 1.3 is ensure the templates are... so 1.2 is about markup generated by the tool.
IJ 2 is about generating standard markup. "generate generate generate". Maybe we should reword guideline 2 to de-emphasise the tool's role.
JT So at 1.2 we are mixing the author's responsibility with what the tool does.
CMN 1.2 is about generated markup - we should say "generate markup". Jim wants to be able to enter non-conformant markup
JT We could split 1.2 to have support the author, and another for the tool.
CMN We have guidelines 3 and 4 to cover support of the author
GR We need to make the point that it is possible to add accessibility content during generation/transformation. We want to say don't lose anything, and allow adding
CMN I agree. I think that 3.1 covers the precise case...
PJ You could conform to 1.2 if there is one way to fix the source. 3 and 4 talk about additional ways to do it. You could meet 1.2, but not 3 and 4, if you don't have the prompting. We have to give the tool vendor minimum guidance with the split.
IJ I would suggest looking at the imperative verbs to ensure consistency. If we use "generate" to consistently mean what the tool does without author control then we should have a different verb for what the author does
PJ I would like "author" and "tool" to be there. for example "ensure the author can use", or "ensure the tool generates"
IJ I agree
Resolved: Do this in an editorial pass - each checkpoint to say "author, tool, ..." and verbs to be used consistently
JT So do we want to split 1.2?
No
JT Our response is that we will change the wording to make it clear that this applies to what the tool does.
PJ I want a where possible, or can
DB are we not looking at the question of whether 1 and 2 are mixed? They seem to be - 1 is mostly about auhtors, 2 is mostly about tools
JT Yes, but the split we are using is standards in general and accessibility in particular
DB I can't see that much difference - for example 2.3
CMN Does the proposed response answer the issue?
JT I think so.
PJ My wording issue on 1.1 may be relevant
...
CMN Ensure the tool allows the author to use accessible authoring practices
IJ I wanted carry out, not implement
PJ Agree
IJ I don't like use
WC Follow?
we like follow...
Ensure the tool allows the author to follow accessible authoring practices
BR We need to define accessible authoring practices
GR the reason for implement is that Judy felt it it wasn't strongly enough worded. This would allow a text editor to meet the checkpoint.
CMN Yes, but there are others it doesn't meet
defining authoring practices...
CMN Accessible authoring practices are the things the author does to make their content accessible
PJ Direct editing, alternative content
WC You don't want to say this is just WCAG.
DB The problem is the definition for accessibility is circular.
IJ I asked Gregg how to define accessibility. "Anything that you do so disabled people can use the web".
GR I think it is a red herring to define accessibility
DB I need a definition
PJ I define it as the attributes of the tool, content, etc. Accessible is a list of things that need to be done, combined with an appropriate technology you have an experience where the person with disability can use the product
JT We had "direct accessibility" and "accessibility through assistive technology"
GR IJ is right for the purposes of this document.
GR Rather than use accessible in the defintition of accessible authoring practices
DB if we have a definition of accessible we can use that rather than use it each time
BR accessible authoring practices are what I want
PJ we should give examples in the definition
CMN eg "Accessible Authoring Practices are things an author does that make their content useable by people with disabilities. For example, providing alternative content.
GR could use "practices".
back to 1.2...
PJ If it has to produce accessible content, why does it have to be over-rideable
DD 4.3 is for thins the tool does not support
JT I think we need to clarify 4.3 to make sure it is clear
CMN I think we should cross-reference to 4.3
JT We don't want to highlight them as the same, we want to higlight the difference (that a tool may not be as smart as the author).
WC say that in the checkpoint
DD The thing is "when the author knows better"
PJ We should add the word accessible in 4.3
CMN The tool doesn't know what to allow override on. So we can't say it clearly...
WC Someone could put in inaccessible markup if they have override power
DD That's fine. That is not a tool issue?
WC if the tool is allowing override, does it have to say "I can't tell?"
PJ 4.3 says the author can override 1.2
BR 4.3 is importing markup that the tool doesn't get
PJ imported or any?
CMN it could be typed up
PJ it is not necessarily imported. The author can override - that was Jim's issue in 1.2
WC side question, did anything meet conformance
Not Yet
GR In HomeSite evaluation, they could get triple-A if they fixed some serious problems.
PJ the question is can anyone conform?
WC So 4.3 could be worded better. Basically we are saying "allow the author to override the tool".
BR To override the tool is too general. I think as it is here is fine
DD How about allow the author to force the tool to retain markup?
PJ As a P2? It covers the ability to post stuff in.
CMN You need to allow external things to come in, but you don't need to require that the author can add code in a given tool.
BR if the tool brings in stuff the author can force it to remain.
WC I like the idea of retain. I used an element in a tool that were unsupported and it would convert markup. I don't want it to change or remove...
DD Good example is new event types. onActivate is not in HTML but with a browser that suports it I want to add onActivate to my source and not have it thrown out. I want a validity check to learn that.
PJ It may not know how to deal with it but it doesn't remove it.
"allow the author to preserve markup not recognised by the tool".
Resolved: 4.3 to be "allow the author to preserve markup not recognized by the tool" (And we like the dialogue technique)
PJ there are tools that cannot support a document because they don't understand it. We should note that we recognise this possibility. For example you can edit the source and preview in a browser and not be able to do WYSIWYG editing.
PJ We haven't defined published, and it may not be necessary if there is a tool. We haven't defined languages that are accessible. To say something conforms to 2.3 you need a W3C spec or a W3C note that says "XX" is accessible.
WC ebook could become an accessible spec.
PJ Can the W3C publish a note recognising ebook as accessible?
IJ I think that is an issue of validating a conformance claim, at WAI CG
PJ 2.3 says "ensure your thing produces in an accessible language". I want the W3C to tell me what is accessible.
IJ I don't think it would be desirable to centralise the endorsement at W3C.
DD I think it is related to WCAG. If WCAG covers ebook, LaTeX, etc then these guidelines are applicable. If WCAG doesn't provide for that there is not much we can do. If you can say "my XX file is WCAG compliant".
PJ This is the language
IJ If one can write WCAG-compliant pages the language enables accessibility.
CMN We could say "use a language that enables writing WCAG-compliant...
JT We should keep the point that we require coverage for extensions, new languages, etc.
IJ It belongs in the conformance
GR It might fit into a note in 2.2, or in techniques
PJ How does someone know if their language is accessible?
CMN We should note in techniques for 1.2 that some languages make that easier.
JT The important thing was to allow content that conforms to WCAG
Resolved: Remove 2.3
BR What is a published specification?
DD We have to answer "what is an applicable language" first. Let's say I have a text editor that generates some markup. I could generate WCAG-compliant stuff that is not HTML - what does it mean?
WC The reason for W3C specs is because they have accessibility review. This carries some of 2.3
IJ 2.1 says "use these".
DD It is worth giving a list of what w3c specifications are applicable?
JT Would your concern be met by noting it in the techniques?
DD I like the WCAG wording. "Use appropriate W3C technologies..."
PJ Should add "supported by browsers"
Resolved: Use the latest versions of W3C recommendations when they are available and appropriate for a task"
DD The second one is to promote the generation of valid stuff. We should stress that point.
WC We don't care here if it is a W3C rec or some other specification
DD Ensure that the tool generates markup that conforms to a public specification
DB What does this have to do with accessibility?
JT This addresses the issue of creating access tools - you have to have the spec, or reverse engineer it, to create the assistive technology.
DD Even if the vendor does not support accessibility then it is possible for a third party to work with it.
WC If this is a proprietary spec then it has to be accessible
PJ It has to be able to be proprietary and conform.
WC There are two points. 1 - it must be valid. and 2. does it have to be a public spec?
PJ We need a checkpoint that says "make valid markup"
DD The part about the published should be folded into the first checkpoint.
PJ It is possible to use a tool that is publicly specified instead.
CMN A specification does not need to be free to be published
JT The problem is if it is not free can people make a User Agent?
GR If you are going to use these things then allow the author to transform this stuff.
CMN If you write in a language that isn't accessible then you fail WCAG, and you lost.
GR We should say "allow the user to transform or add namespaces"
WC That becomes a WCAG problem (or User Agent). What we need here is to require validity.
Resolved:We want 2.2 Ensure the tool generates valid markup.
DD Whenever you extend an industry standard, let the author know you are doing that.
WC HomeSite does that nicely - you can generate W3C strict, or X compatible, or ...
DD I want a checkpoint.
WC 2.2 should allow you to select what you are going to validate to. we need a checkpoint that says "use standard markups".
GR Ensure the author can validate against generic standards.
JT We want to alert the author when we are not using the industry standards
PJ What is the industry standard?
WC In the web there are w3c standards, but there are various other standards groups
GR NISO, ISO, ...
PJ I would accept DD's proposal as a priority 3.
Proposed: "Ensure the author can choose to generate markup that is valid to industry standards"
GR You need to be able to validate proprietary stuff against vendor-neutral
WC Often tools take a specification and add things. we are trying to discourage that.
Resolved: New 2.3 "If markup generated by the tool differs from W3C standard, inform the author." P3
/*lunch*/
JT Is there something we are not covering?
PJ I think it is a technique
Resolved: This is techniques
JT This is already a gimme.
DD The issue is between 3.2 and 3.3. If you have nothing else to use it is OK to use what the tool guesses.
WC No. If the author hasn't provided anything it shouldn't add an alt attribute.
CMN Forces an accessibility error to be caught by 4.1 If it is caught, then it is a user agent
PJ The tool should keep track of known objects.
DB What if I am building a huge database?
PJ You can encode it in the file format, but filename is not usually worth having. The tool doesn't know.
Resolved: Leave as is
BR A word-processing document or spreadsheet could have multimedia.
JT I think he was talking about objects prepackaged
CMN There are two good things there. Auto-generate/extract accessiblity information.
Good Technique for 1.2
CMN And think beyond multimedia as things that have accessibility information.
DD The note is too broad. Is it just for images?
Note should say "don't use for automatic insertion"
PJ Why is 3.3 P2, and 1.3 P1?
WC This is more context-dependent.
PJ It would be good if the tool shipped with working examples
WC Are scripts included in this?
CMN Depends whether they are templates or multimedia...
JT We want the checkpoint, want to change the note, question the priority.
DB The author can add their own text
BR It is not make or break right?
JT Should templates and this be same priority?
PJ Yes. and they should be P2
CMN It is P1 on our goal to have accessible content by default (relative priorities)
PJ I think is undue burden to require it for all templates.
DD Why? Which ones? They all have to be accessible.
PJ The ones that have tons of templates will take releases to fix them all.
DD Whether it is difficult is not a determinant of priority
GR For the average user they need to use the templates.
WC If someone uses templates and it says at the end "the template was no good" then the tool will look silly.
PJ Yes.
IJ Should they be combined?
CMN I don't want to.
DB Will just alt-text be enough?
PJ No, depends on WCAG. If it is a complex image it should have a long description too. If it is a movie it should be synchronised.
DB You won't get many libraries with complete longdesc
CMN That's OK - many clip art libraries don't fall into that category.
DD Your concern is quantitative? It is too much work to make them all accessible.
PJ It may be impossible to do something without a text-page alternative.
DD What about saying those that are not accessible are marked as such?
DB We're not going to ship tools that say "this is not accessible"
DD But then if I use a tool's template and it doesn't tell me it is inaccessible that is not acceptable
PJ I don't have to use the templates, I might use them wrong, ...
JT If an author is going to pick a template, they are encouraged if it is accessible.
PJ So why not mke it P1 to have templates?
JT There are tools where is not appropriate to have templates.
PJ What I find is most advanced sites - they create their own templates
CMN Right, but the one-time users won't
JT They are just going to be baffled when it says "you took what we gave you and it doesn't work"
CMN If you don't have accessible templates you are going to break a wole lot of other checkpoints already.
PJ I want to go on record: Having all templates P1 is undue burden - ensure there are templates is P1, having all templates is P2
DB I agree with Phill.
PJ How do I provide an alternative or accessible template for a heavy Java page?
JT Templates allow for the author to add things.
CMN The template can describe some functional alternative which may require further author addition.
GR for example do a Frameset template that has a comment like "place the content of the nav frame in the noframes as well.
WC This is the same problem with the auto-generated stuff.
JT We would need to cross-reference 1.3, 3.2, 3.3 - we need very good techniques for here.
Resolved with dissent (PJ, DB): 1.3 keeps sliding priority
IJ Propose merging 1.3 and 3.3
JT 3.3 could be a P2
PJ Because when you put in a gif the tool will ask for alt, whether or not it has it supplied (P1 from 4.1)
GR It is possible to disable that request.
PJ Note in 3.3 should be in 3.2, new note should talk about videos, graphics, etc.
JT We offer the content provided as a default, and rely on 3.2
WC would like to reword to take out prewritten and multimedia.
DB We need to make it clear that this has been included with all things as part of the package.
WC The emphasis is that all the multimedia stuff packaged are accessible.
PJ If we point to WCAG that is an improvement...
IJ Proposes 3.3 to say "ensure prepackaged content conforms to WCAG Example: movies with text and audio equivalents. (Refer also to 3.2)" Sliding Priority
PJ Should we put 3.2 after 3.3?
Resolved: 3.3 to say "ensure prepackaged content conforms to WCAG Example: movies with text and audio equivalents. (Refer also to 3.2)" Sliding Priority, order of 3.2, 3.3 reversed
Resolved: Already covered
DB Can you point to a web-based tool to do your checking?
BR You then have to be online
CMN Your conformance statement has to state the scope ("used online")
PJ I can add anything I want to TopPage
WC HomeSite links to W3C validators
PJ TopPage lets you plug in whatever you want
DD I am concerned that then the requirement is for the tool to be used online. I would like to see a lower priority to ensure that the tool can be used offline.
GR I think it is less of a burden to say "get online" than to give them an outmoded checker. We shouldn't exclude the possibility. We should still encourage people to include something local as well
IJ Do you have to provide it natively?
GR I don't want to kill off a tool made in a garage that relies on other web-based services.
DD It is unlikely to get integrated. All 4 can be done, but they may not be compliant with 5.
Resolved: This is techniques material
CMN We decided not to require particular views.
PJ Providing different views means you don't need assistive technology to see how it looks
CMN This goes back down the path of suggesting there is "a" graphics view and "a" text view, which is not true
JT Do we want to have this in techniques?
WC Part of this is relevant to 4.2 - make people do user testing would be ideal, but showing them a simulated alternative view is a technique.
Resolved: Different views is a technique. In 4.2 we want to simulate other views, and would like to have interactivity in it
DD We might ask the author to provide the flexibility about how checking happens. My concern is that people will take the checkpoint and interpret it as requiring lots of interruptive prompting, and claim that the guidelines are unimplementable.
JT We took it to techniques and intro on the request of developers.
Resolved: No, it doesn't.
WC I think that is in 4.2
JT Checking for and alerting the author requires some author participation
PJ Spell out in the note that the vendor doesn't have to make telepathic tools - it may require author participation, and some things may not be possible. What if I don't include function to ask the author? Do I conform?
DD Yeah
PJ Make it "that are machine checkable" P1. P2 is things that require author participation..
DB You mean things the tool can't prompt me for?
WC No, things that the tool can determine that it needs something. HoTMetaL asks if you need a longdesc for images?
DD What if you go over your document and add no longdescs, and run your check again.
CMN Then it should remember. It's a design problem
GR Should be like a spell checker.
WC Are we going to say "so, product X does this..."
That would be helpful
DB If I have the questions the tool can't answer in the documentation does that satisfy it?
CMN That's mostly what Bobby does.
DD There are two things - problems the tool can find, and things that the author needs to know, which is a lower priority.
PJ It almost has to have a test for everything in WCAG.
IJ If it is in the documentation, is it insufficiently visible?
CMN The list is - you have to go through the WCAG checklist
DB So at some point I have to tell them about that every time, every session.
IJ Not necesarily
GR Homesite has a project manager that keeps track of what you have changed and what you have to check.
DB If I add new content then I should be warned about all the uncheckable things.
PJ Can I meet 4.1 by prompting the author to check for alt text once? We have to specify what it takes in the techniques document.
PJ The ER doc should be in the Guidelines Document.
Resolved: Put a reference to the ER note in the checkpoint as an informative link.
DD It is essential to give some help
DB 4.1 implies we tell them there is a problem, 4.2 implies an assistive mechanism
JT But it doesn't tell you how to do it.
WC One of the reasons for this document is so we can help authors who have not read the WCAG. Having Authoring Tools that can help is essential.
PJ So for each WCAG P1 I need to help the author fix it.
DB is documentation on how to fix it enough?
DD Yes.
JT We should point this to ER.
PJ We need to be able to sign off on ER.
YES.
CMN So is the minimum requirement to provide context-senstive help?
PJ The requirement for help is not a P1
DB: The crux of the issue is that I don't think assisting is essential. It's important.
Resolved: Think about this overnight
DD Propose to delete Note 2
Resolved: Delete Note 2 from 4.3
JT There are P1 checkpoints that cover the P1 case, and there aren't many cases.
PJ This was so important it actually got fixed...
Resolved: Still P2
Resolved: P2
DD Does that cover everything - checking, etc?
Resolved: Needs rewording to make it clear that it does.
"Ensure that functionalities related to accessible Authoring practices are integrated into the tool".
JT This is P1 because the average author will go for whatever is first
WC If assistance and templates are P1, then this kind of follows.
PJ I want to delete 5.2 and drop 5.1 to P3
JT Using a Math tool, the first choice is to make the math a gif...
PJ When you prompt the author to make content, prompt them with accessible choices first.
DB How do I find out what are the highest priority
Action editors: Add reference to WCAG P1
DB So we tell people to use CSS and make it the most popular, and it isn't implemented properly.
WC This seems like a technique for 1
PJ Could it only be applicable to certain environments
WC Could 3.1 also say "assist the author in providing alternative information and other WCAG priority 1"
Resolved with dissent(CMN,GR): Priority 2.
WC We still don't have a checkpoint that says "help the author"
CMN But we say a whole lot of verifiable things like "prompt for alternative information" and ...
WC Propose: change 3.1 "prompt" to "assist"
Resolved: 3.1 "Assist the author in providing equivalent alternatives to content"
JT Propose: add "structure" to 3.1
Proposed 3.x "Help the author create structured content"
Resolved: new 3.x "Help the author create structured content"
Proposed: Guideline 3: "Support the Creation of Accessible Content"
/* dinner time */
Second day (Phill is not here yet)
JT currently sliding scale
DD I don't get what the "built from several parts" means.
JT It means you can provide examples that are not accessible as part of building complete examples.
GR It was pointed out that saying "you can't show how to do layout by tables" then it wouldn't fly
DD So clarify the wording. "Ensure that documentation examples show how to produce accessible content" does not need a note.
DB So what do we have to do when we say how to build a table??
DD Mentioning counter-examples might clarify what the note says
CMN ...or identify inaccessible solutions
DB So if you are producing something where you need a text-only version for accessibility do you need to show how to do a text-only version each time?
/* Phill arrives
JT You could link everywhere to the one example
DD so for an IMG you can build up a progressive example
GR You don't want to teach people through negative examples. We used to say "when giving examples make sure the illustrated example is WCAG compliant (and valid)"
JT What about practices that are not accessible
GR I would not use IMG for an example
DD I think it is OK to introduce a concept bit by bit. You progressively introduce things until you have everything.
GR Yes.
Resolved: remove the Note from 6.3
DB What do we do about saying how to use layout tables?
GR Say "the preferred practice is X, there are alternatives Y and Z", for example with a link to the relevant section that has the preferred example.
IJ Would you be showing table markup?
DB They would be showing tables for layout.
PJ Tables for layout are perfectly accessible - still meets WCAG guidelines
JT Do we want to put into the guideline something that says "the accessible example is part of the example.
DB This gets too far into the detail - at what level do you need to link what?
JT What if we added "...as part of the example"
GR Then we are going to get into the making it most obvious...
CMN For which we already have a checkpoint.
GR If someone uses the tool to learn the language
WC As long as they point to WCAG they have lots of examples
CMN No, that is not sufficient.
GR The point is to avoid the ghettoisation of accessibility
JT Which is why we want ti as part of the example
DB So maybe you need some phrase added "...or indicates how it isn't compliant" - adding the accessible example is going to be very hard (although it is already a load of work lined up).
CMN Sounds good to me. The key is that for any example, you can find out how to do it accessibly (which might be "make another, accessible version as well").
IJ "Ensure that all examples conform to WCAG, or explain how they don't"
PJ "include examples that..."
DB No, that is changing it
DB We don't have to require examples
JT Use "...includes how to ..."
DB Makes no big difference
GR There is a user group of people who learn through the help of a tool.
JT Kynn wanted to be able to have alternative ways of doing things, and the wording had to enable that.
IJ Ensure examples illustrate accessible authoring practices or explain why they don't.
BR 6.2 covers authoring practices
IJ 6.3 is specific to WCAG
DB The problem is whether it is interpreted as making the HTML that the help is written in is compliant?
CMN The use of "author" and "tool" (see resolution yesterday) will clarify this.
DB I like the new wording, but maybe "employ" instead of illustrate
JT That gets confusing again whether it is showing or being written in accessible way
IJ in each example ensure that pertinent accessible authoring practices are included.
DB Do I have to have every example show every accessible authoring practice
CMN No - for example if you illustrate some things which require text-only versions you don't need to show how to do that every time, just mention each (relevant) time that it needs to be done.
GR I don't feel that we are hitting the point that if there are two ways of doing something, show how one can make the transformation from one to the other (how to use Style Sheets with deprecated presentation). That is something that help should stress.
CMN We should do some real examples for the techniques
GR We could put a sentence or two into the introduction to the guideline.
Action GR: Write technique for this.
CMN "ensure examples include pertinent accessible authoring practices"
IJ I don't think we need to say pertinent
GR There are property sheets in HomeSite, where it has accessibility practices
CMN You need the pertinent practices, not just some relevant practice.
Noted: Accessible authoring practices should point to WCAG.
BR What is different between 6.2 and 6.3?
DB I can use text editor and WCAG and I am in compliance. Why don't I just point to that. 6.2 doesn't say that.
DD To me, the first one is integrate accesibility wherever relevant, second one is to have a section where all the accessibility features are gathered, the third is to make examples.
IJ The wording used in UA is "ensure all tool functionalities that promote accessibility are documented". P1 (UA 5 Oct 12.2) "describe features known to promote accessibility in a special section" P2. (UA 5 Oct 12.3)
/* It's Ian's fault
DB That sounds like what I was getting at
BR 6.2 says how to use the tool, 6.3 says that the examples should show how to make accessible markup
IJ is there a reason to use the term accessible authoring practices?
PJ say "...show how to conform to WCAG". I don't think we should use the term accessible authoring practices
IJ Should we use it in the document at all?
CMN Accessible Authoring Practices: The things that authors do in order to ensure that their content conforms to WCAG
PJ The tool doesn't want to explain what the author does
CMN Examples want to show what the author does.
PJ 6.2 says "show the author what the tool does".
GR Configuration steps, etc
DB There are steps you can take that are tool independent that produce accessible content.
IJ accessible authoring practices is just a phrase for "conform to WCAG"
JT, CMN, right
PJ Confusion between what the author can do, and what the tool can do itself, and how the tool can help the author
JT It is an editorial device
IJ Propose to remove "accessible authoring practices"
BR The important thing is to have a common understanding of the terms.
PJ 6.1 should be about production of content.
IJ saying "accessible authoring practices" you lose information.
PJ 6.1 is integrate features that promote production of accessible content into help. 6.3 is make sure examples show how to produce accessible content.
JT should we remove the term from the document?
PJ The process is more than using the tool. The term implies things that the tool does not do
WC removing it is not going to be trivial
IJ Yes it is.
DB for 6.2 say "in a section, explain features known to promote
JT We don't want to say put it in a special section, and we wnat to say "production of accessible content"
CMN Yes, we want to gather everything - that is 6.2. 6.1 is making sure there is documentation somewhere.
IJ I would like to limit 6.2 to product features
DD It is good that there is a section that explains all the accessibility features
PJ Why is it a P2?
6.2 "In a section of the tool's documentation, describe features that promote the production of accessible content"
DD It is important to have a pointer in help to WCAG
CMN It is a useful technique.
WC why does it have to be together?
CMN 6.1 says "describe the features, somewhere". 6.2 says "put it in one place for people who are looking for accessibility information
priority is open...
Resolved: 6.2 "In a section of the tool's documentation, describe features that promote the production of accessible content"
PJ Do we mean help topics or documentation?
BR We should just say documentation and define it generally.
Resolved: Define documentation in glossary and reinforce this in the introduction.
CMN Proposed 6.1 "Document all tool features that promote production of accessible content"
PJ Point is to integrate
CMN Integrate documentation of all...
CMN We want to say tool features here
DB There is more than tool features - there is what to do to conform
DB "Integrate steps that produce accessible content in applicable documentation
IJ What does 6.1 say?
JT 6.1 says "integrate into documentation how to use the tool to produce accessible content"
DD Documentation is covered as part of 5.1
CMN 6.1 does not need to be as broad as integrating, it is just "make sure that features used to produce accessible content are documented" (and integrating it is covered by 5.1)
DD That's not what we are talking about - there is the case of help for image, and they don't talk about longdesc
CMN That is an example. What kind of instruction is not an example?
JT The initial wording covered integrate and document.
CMN Split out document as a separate requirement (P1)
CMN Proposed 6.1: "Document all features that promote the production of accessible content", P1.
Resolved: 6.0 "Document all features that promote the production of accessible content"
IJ Proposed 6.2 "In a dedicated section, document all features of the tool that promote the production of accessible content".
Resolved: 6.2 "In a dedicated section, document all features of the tool that promote the production of accessible content"
6.1: Ensure documented features are integrated into the documentation
DD We want naturally integrated
DB are we really saying that or are we saying "ensure that creating accessible content is a naturally integrated part of the documentation."
PJ I would like to add "help" here.
BR We define documentation already to include help
IJ When the documentation tells you how to use the tool it should tell you how to use the accessibility features of the tool
CMN Yes, but it should tell you how to do it, whether that is through a tool feature or something the author has to do...
Resolved: 6.1 ensure that the production of accessible content is a naturally integrated part of the documentation.
6.3...
CMN "Ensure that all examples and instruction show how to create accessible content" which is redundant with our 6.1
PJ and covered by 6.0. 6.3 should be "ensure documented examples conform to WCAG.
PJ Are examples covered someplace?
CMN add the specifics to 6.1 - "..including examples" (and drop 6.3)
GR add to 6.1 Note: This includes examples and markup illustrations
CMN I think that is what is meant by example.
proposed 6.1 to replace 6.3 is "ensure that creating accessible content is a naturally integrated part of the documentation, including examples."
PJ Technique: make examples comply to WCAG
proposed 6.1 - 6.3:
6.1: Document all features that promote the production of accessible content
6.2: Ensure that creating accessible content is a naturally integrated part of the documentation, including examples
6.3: In a dedicated section, document all features of the tool that promote the production of accessible content
Resolved: 6.1 P1
DB I think 6.3 is a 3, but I am torn with 1 or 2 for 6.2
CMN I agree precisely
PJ We have too many P1. This wouldn't be one of the first 3 things I would do.
DB sometimes the part that 6.2 covers is as important as accessibility features like checkers
CMN There are different staged approaches relevant to different developers.
DB 6.2 takes the most work.
BR We may need to sort out more carefully what priorities really mean. We set the bar pretty high for a non-trivial product.
DB What about P1, P2, P3 for these (in that order)
IJ I don't think a better understanding will make it clear cut - they are judgement calls. This one is a judgement call I think.
BR I would rather put off assigning priorities until we have a common understanding.
DB We should assign them, and then revisit.
JT 5.1 (integration) is P2. We also have 6.4 - emphasise the universal benefit of accessible design
PJ Isn't that a technique of proposed 6.2?
DB Yes.
BR It is a hard thing to verify.
GR 5.2 being a P2 doesn't imply that 6.2 should also be. If it is not essential to integrate the tool, then it is essential to integrate documentation.
PJ If the tool is integrated, then the help is secondary
CMN I think this is a judgement call.
PJ We have a responsibility to identify only things we think are essential in P1s
BR The risk is having the baby thrown out with the bathwater
CMN Developers have to decide, if they can't meet the thing in one shot, which bit they aim for
GR P1 is the requirements for the tool to make accessible content authoring what tools provide
BR Maybe we need an easier carrot for developers.
Resolved: 6.4 to technique
Resolved (GR dissenting): 6.2 is P2
/* lunch
Resolved: Covered by 7.1 make sure techniques show this
JT There are only priorities in some.
CMN Ian suggested make it P1 unless it is prioritised.
DD We should say the word guidelines in this
PJ Use "guidelines" instead of conventions.
PJ If it is a P3 on list X does the author have to do it for P1?
PJ I would like to import the EITAAC prioritizing to the techniques as further guidance.
CMN Good idea (= action charles...)
Resolved: We think this is OK and would like to show in techniques how to map priorities
DB Isn't this a general requirement for software?
CMN I can see that this seems like a general requirement, but the editability of each property is crucial, and it is worth having here.
Resolved: Drop 7.3
PJ Does 7.4 then block a transformation tool from conformance?
CMN No - it is possible to access element properties that a transform will affect, and that can be accessible or inaccessible.
PJ The requirement is not to be able to edit everything there is at all times, but for the editing that is there to be accessible
"Allow the author to edit, in an accessible fashion, all properties of each element supported by the tool"
"Allow accessible editing of all editable properties supported by the tool"
DB A property sheet is a technique? edit source?
CMN Yes (but won't make 5.1??)
CMN I agree with Dick - it is covered by 7.1, but I think it is nice to have it there.
Resolved (DB dissent): 7.4 remains
JT Do we need to say explicitly "make things editable"?
GR for 3.1 I would like "provide a mechanism" not just "assist"
Resolved: It is implicitly covered
7.5, 7.6
JT They are not covered by 7.1 and are specific to authoring tools - it is necessary for people who have reduced access to the document needs an enhanced navigation/editing capability.
BR It says these are specific to Web Authoring Tools, and it is really authoring tools in general.
DB these don't say accessible
DB We are here calling out specific examples that are issues under 7.1
GR Would it be helpful to have problem statements in the techniques?
CMN Yes.
Resolved: 7.6 "enable editing of the structure of the document in an accessible fashion", 7.5 to be "provide an accessible means of navigating via the structure of the document", 7.7 "provide an accessible means of searching within an editing view".
DB I disagree with requiring the feature of a search.
PJ Transformation tools need not provide a search. Should we make 7.7 P3
WC We ought to make 7.7 conditional.
JT It is specified as within editing view - if you don't have one it doesn't apply.
Resolved: Specify that these are within an editing view
DB It would be possible to do structure navigation by searching for elements in a source view.
Noted: DB doesn't want 7.5, 7.6, 7.7
PJ We added a checkpoint - 3.2
CMN That sounds like a lot of words for things we have covered
Resolved: Adopt Jon's proposals as techniques - rest is covered.
BR Should note 3.2 to say separate presentation and structure
PJ add to 3.2 "...and ensure separation from presentation"
Resolved: "...and ensure separation from presentation"
JT There are a number of these that need to be tightened up.
CMN Should be ordered alphabetically
Define generate, produce, accessible content, accessibility, valid markup, user agent
Resolved: Define "priority W" - Call it "Relative Priority"
In these guidelines some checkpoints have a relative priority. This is used to XX the priorities of meeting ATAG checkpoints with the priority for requirements in WCAG
Relative Priority is an ATAG priority 1 for content or features of a WCAG priority 1 Checkpoint
Relative Priority is an ATAG priority 2 when it relates to a WCAG priority 2 Checkpoint
Relative Priority is an ATAG priority 3 when it relates to a WCAG priority 3 Checkpoint
In other words, an authoring tool which claims level-A conformance must meet Relative Priority requirements for priority 1 items in WCAG, while an authoring tool which claims triple-A conformance to ATAG must meet the requirements for all priority 1, 2 and 3 items in WCAG.
The priority definition in WCAG maps because...
Some checkpoints talk about production, generation, checking etc of various content that have different priorities in WCAG. The priority for these checkpoints in ATAG varies according to the priority of the checkpoints in WCAG.
Relative Priority is used for ATAG checkpoints which relate to different types of content, to ensure that the priority of each feature matches the priority given to the feature in WCAG, as follows:
It is priority 1 to implement the checkpoint for content features which are a priority 1 requirement in WCAG.
It is priority 2 to implement the checkpoint for content features which are a priority 2 requirement in WCAG.
It is priority 3 to implement the checkpoint for content features which are a priority 3 requirement in WCAG.
For example, checking for accessibility errors (3.1) has relative priority. This means that it is priority 1 for a tool to check for accessibility errors that are WCAG priority 1, but priority 2 to check for accessibility errors that are priority 2 in WCAG.
Some of the checkpoints in this document that promote the production of accessible content have a relative priority. The priority of each of these checkpoints depends on the degree to which the authoring tool produces content that conforms to WCAG.
It is Priority 1 for an authoring tool to satisfy the most important requirements of WCAG (i.e., the Priority 1 checkpoints in that document).
DB I am confident that we know what we want to make clear, and that it can be done outside this meeting
DB Intro to Techniques is better definition of Accessibility
PJ Can each tool developer make sure that the technique they already use for each checkpoint they meet is in the techniques document (or submit them). Action everyone...
/*JB arrives
JB Will we be ready to ask Tim for a Proposed Recommendation on 22 October?
Maybe.
Resolved: We will try for 22 October (lots of work on techniques...)
|
http://www.w3.org/WAI/AI/f2f3-minutes1.html
|
CC-MAIN-2016-44
|
refinedweb
| 8,350
| 72.97
|
Certain methods cannot be executed by the JVM alone. JVM takes the help of the underlying operating system to do the job. Such methods are known as native methods. For example, for all the file operations and thread operations, the JVM should communicate with the operating system and with the operating system cooperation, the task intended will be achieved. File management and thread management etc. are managed entirely by the OS. Any language should communicate and take the help of OS.
Any problem in the communication (known as communication gap) and any programmer's task is not done successfully, the JVM informs through an exception and especially as a checked exception. The name of the checked exception is included in the method signature or constructor signature. Some checked exceptions with constructor signatures are given hereunder.
public FileInputStream(String) throws FileNotFoundException; // a constructor public URL(String) throws MalformedURLException; // a constructor
One example of checked exception is InterruptedException very often used in thread operations. Many thread methods throw InterruptedException. Observe the following two method signatures of Thread class.
public static native void sleep(long) throws java.lang.InterruptedException; // a method public final void join() throws java.lang.InterruptedException; // a method
Both the methods sleep() and join() throw a checked exception – InterruptedException. While using these methods, these methods must be placed in try-catch blocks; else program does not compile.
The following program uses these two methods and handles InterruptedException.
public class Demo extends Thread { public void run() { for(int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch(InterruptedException e) { System.err.println("Sleep is disturbed. " + e); } System.out.println("Iteration: " + i); } } public static void main(String args[]) { Demo d1 = new Demo(); d1.start(); try { d1.join(); } catch(InterruptedException e) { System.err.println("Properly not joined with parent thread. " + e); } } }
The program is given to stress more on InterruptedException. Coding explanation (extending Thread, run() and sleep()) of the above program is available at "Creating and Spawning Threads".
The above main() method can be modified to throw the InterruptedException instead of handling it in try-catch block. Using throws, instead of handling with try-catch block, is not a robust way of programming and can be used in sample code development.
public static void main(String args[]) throws InterruptedException { Demo d1 = new Demo(); d1.start(); d1.join(); }
Why the methods sleep(long milliseconds) and join() throw InterruptedException?
The sleep() method inactivates the smooth running thread for the time passed as parameter in milliseconds. The communication goes from Java to OS to inactivate. Due to the complex algorithm of Thread Scheduler, the sleep time may not have been affected exactly specified. Say, 1000 milliseconds may be affected as 999 or 1001 milliseconds. If it is done like this, the programmer output may differ. Then it is programmers job to take care of this situation (which may be very very rare). He can take some alternative action to rectify the problem in the catch block.
Similarly, join() method communicates with the parent thread. The JVM does not allow the parent thread to die before the child dies. If the child thread dies before the parent, the child becomes orphan thread and the program may give different outputs when executed each time. This problem is indicated by the designers with InterruptedException.
|
https://way2java.com/exceptions/interruptedexception/
|
CC-MAIN-2022-33
|
refinedweb
| 546
| 50.63
|
Feature flags for Wagtail sites
Project description
Wagtail-Flags
Feature flags allow you to toggle functionality based on configurable conditions.
Wagtail-Flags adds a Wagtail admin UI and Wagtail Site-based condition on top of Django-Flags. For a more complete overview of feature flags and how to use them, please see the Django-Flags documentation.
- Dependencies
- Installation
- Usage
- Extended conditions
- Signals
- Getting help
- Getting involved
- Licensing
- Credits and references
Dependencies
- Python 3.6+
- Django 2.2 (LTS), 3.1 (current)
- Django-Flags 4.2
- Wagtail 2.11 (LTS), <3
It should be compatible at all intermediate versions, as well. If you find that it is not, please file an issue.
Installation
- Install Django-Flags and Wagtail-Flags:
pip install django-flags pip install wagtail-flags
- Add
flagsand
wagtailflagsas installed apps in your Django
settings.py:
INSTALLED_APPS = ( ... 'flags', 'wagtailflags', ... )
Usage
Please see the Django-Flags documentation for the most current information about defining and checking feature flags.
First, define the flag in Django
settings.py:
FLAGS = { 'MY_FLAG': [] }
Then use the flag in a Django template (
mytemplate.html):
{% load feature_flags %} {% flag_enabled 'MY_FLAG' as my_flag %} {% if my_flag %} <div class="flagged-banner"> I’m the result of a feature flag. </div> {% endif %}
Next, configure a URL for that template (
urls.py):
from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path(r'mypage/', TemplateView.as_view(template_name='mytemplate.html')), ]
Finally, add conditions for the flag in the Wagtail admin under "Settings", "Flags", "MY_FLAG":
Extended conditions
Wagtail-Flags adds the following conditions to Django-Flags:
site
Allows a flag to be enabled for a Wagtail site that matches the hostname and port in the condition value.
FLAGS = { 'MY_FLAG': [ {'condition': 'site', 'value': 'staging.mysite.com'} ], }
Signals
Wagtail-Flags includes
flag_enabled and
flag_disabled signals that can be received when the "Enable for all requests" and "Disable for all requests" buttons are pressed in the admin. This is intended to enable things like front-end cache invalidation.
from django.dispatch import receiver from wagtail.contrib.frontend_cache.utils import purge_url_from_cache from wagtailflags.signals import flag_disabled, flag_enabled @receiver(flag_enabled) def purge_on_flag_enabled(sender, **kwargs): flag_name = kwargs["flag_name"] purge_url_from_cache(...) @receiver(flag_disabled) def purge_on_flag_disabled(sender, **kwargs): flag_name = kwargs["flag_name"] purge_url_from_cache(...)
Please note: These signals are only sent for manual presses of the "Enable for all requests" and "Disable for all requests" buttons in the admin. Other flag conditions may vary within and only be valid for a specific request cycle.
Getting help
Please add issues to the issue tracker.
Getting involved
General instructions on how to contribute can be found in CONTRIBUTING.
Licensing
Credits and references
- Forked from cfgov-refresh
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/wagtail-flags/
|
CC-MAIN-2021-04
|
refinedweb
| 459
| 50.43
|
POPEN(3P) POSIX Programmer's Manual POPEN(3P)
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
popen — initiate pipe streams to or from a process
#include <stdio.h> FILE *popen(const char *command, const char *mode); that any streams from previous popen() calls that remain open in the parent process are closed in the new child process. The mode argument to popen() is a string that specifies I/O mode: 1. If mode is r, when the child process is started, its file descriptor STDOUT_FILENO shall be the writable end of the pipe, and the file descriptor fileno(stream) in the calling process, where stream is the stream pointer returned by popen(), shall be the readable end of the pipe. 2.. 3. If mode is any other value, the result is unspecified. a null pointer and may set errno to indicate the error.
The popen() function shall fail if: EMFILE {STREAM_MAX} streams are currently open in the calling process. The popen() function may fail if: EMFILE {FOPEN_MAX} streams are currently open in the calling process. EINVAL The mode argument is invalid. The popen() function may also set errno values as described by fork(3p) or pipe(3p). The following sections are informative. == −1) { /* Error reported by pclose() */ ... } else { /* Use macros described under wait() to inspect `status' in order to determine success/failure of command executed by popen() */ ... }
Since(3p). A stream opened by popen() should be closed by pclose(). The behavior environment specified in the Shell and Utilities volume of POSIX.1‐2008 is present, use the function call: sysconf(_SC_2_VERSION) (See sysconf(3p)). Section 2.5.1, Interaction of File Descriptors and Standard I/O Streams).
None.
Section 2.5, Standard I/O Streams, fork(3p), pclose(3p), pipe(3p), sysconf(3p), system(3p), wait(3p), waitid(3p) The Base Definitions volume of POSIX.1‐2008, stdio.h(0p) The Shell and Utilities volume of POSIX.1‐2008, sh POPEN(3P)
|
http://man7.org/linux/man-pages/man3/popen.3p.html
|
CC-MAIN-2017-17
|
refinedweb
| 353
| 65.22
|
Buildroot:DeveloperDaysELCE2018
Contents
- 1 Buildroot Developers Meeting, 20-21 October 2018, Edinburgh
- 1.1 Location and date
- 1.2 Sponsors
- 1.3 Participants
- 1.4 Meeting report
- 1.4.1 Top-level parallel build
- 1.4.2 Reproducible builds
- 1.4.3 More testing
- 1.4.4 Hardening wrapper migration
- 1.4.5 Link-Time Optimization support (LTO) (Alexey)
- 1.4.6 S01logging approach updates
- 1.4.7 Patchwork review
- 1.4.8 Download of extra downloads which have the same filename(different path) and need a unique destination name
- 1.4.9 Buildroot association
- 1.4.10 Points not discussed report
Top-level parallel build
- Thomas has a private autobuilder that builds his PPS branch. Things fail dramatically on that branch.
- For example, Qt5 hardcodes paths in the qmake files, with the effect that by default things get installed in qt5base's staging dir. sed'ing the Makefiles doesn't work either because they get re-generated in some cases.
- Proposal is to make the PPS conditional and merge it, so more people than just Thomas can start testing it.
- Note that in PPS, it is still OK for one package to access the per-package staging directory of another package.
Reproducible builds
- Turn on by default?
- It's currently not really reproducible anyway. We should add some test infra to make sure that it really is reproducible. What other projects (e.g. OpenWRT) do is just do the build twice (same machine) and compare the binaries.
- Proposal: after a successful build, build the same config again in the same location (only variation is time) and diffoscope the results. diffoscope output is uploaded to autobuild server and build is marked a failure. Ideally, the package is identified by matching the diffoscope output with packages-file-list.
- Also randomly turn on reproducible (genrandconfig update).
- Ideal project for a GSoC student.
More testing
- Run an autobuilder in a docker environment without write access to the home dir, this would detect the recent ncurses problem writing to homedir.
- Maybe interesting to use a filesystem namespace per instance with the autobuild-run script managing the setup/launch what the sandbox looks like (R/O mount in pieces we shouldn't touch) - ( bubblewrap looks like it might work, Matt is currently testing with a autobuilder being called by a sandbox script)
- More randomisation, e.g. of hardening options.
- Add option to specify a repository+branch as part of the Autobuilder
- Helps to regression patch series in progress which need feedback
- Should send mails to just the "owner" of that repo instead of to the list + package maintainers
- Ideally the results are still included on autobuild.buildroot.org but separated from the master results.
- Requires a php page update for results to have repo noted and hashes linked to the right repository
- This will increase the noise of number of packages, suggest fixing the next page context bug where any filtering is dropped.
- Arnout will set up a gitlab runner on a dedicated machine; Yann will start one on the same machine as its autobuilder. This will make the gitlab-ci results a bit more stable (today too many of the results are timeouts). Also, trigger the runtime tests explicitly instead of on every commit (there are a lot of runtime tests now, too many to run on every commit). Arnout has sent patches doing that.
- Test scenarios
- Defconfigs - investigate updating the "only" section to just have "schedules", then add a gitlab pipeline scheduled execution trigger once a day
- Runtime tests - add a "only" section like Defconfigs
- check-package/flake8/DEVELOPER - still run per commit
- Mark will add RISC-V 64-bit to the autobuilder configuration and monitor the results.
Hardening wrapper migration
- Patch series looks OK now.
- Add a script in Buildroot that checks hardening
- Config option to enable the check, defaults to no, forces to yes in autobuilders
- Script is called after every package install so package can be identified. Alternatively, detect the failing package at the end of the build.
- End of build check will need to use reproducible hook to find the affected package to show the correct package.
- Create new autobuilder result reason
- Black list files at a per pkg level
Link-Time Optimization support (LTO) (Alexey)
Toolchain should describe if it supports LTO or not.
A global option for LTO would be nice, but some packages will probably break - possibly at runtime. Still, we can do it.
S01logging approach updates
Plan to apply adjusted version of existing patchset and then refactor file naming
Patchwork review
A number of older series have been reviewed and applied (or rejected), but not as much as we would have liked.
Download of extra downloads which have the same filename(different path) and need a unique destination name
Specific package this was required for is eventually openjdk
- For this package one option was to add the mecurial download caching
- Look at an approach to take the *\_EXTRA\_DOWNLOADS and adjust how it's used, i.e., add a optional separator to provide the destination name
Buildroot association
Report of the Buildroot Association general assembly can be found in the br-association github repository.
Points not discussed
The following points were on the agenda, but not discussed.
- Security Assessment Common Product Enumeration (CPE) patches for reporting and maintenance (M. Weber)
- v7 changes:
- Added documentation of how to use the make target and check the state of CPE string correctness
- Added check for glibc library version and if external, add a glibc entry
- Generates the XML update files required for CPE string update/corrections.
- Gobject Introspection (Adam, Yann)
- Remove old gcc version (4.9, 5) ?
- Use the latest gdb version by default ?
- Add the ability to create containers in Buildroot (light containers)
|
https://www.elinux.org/index.php?title=Buildroot:DeveloperDaysELCE2018&oldid=479136&printable=yes
|
CC-MAIN-2021-10
|
refinedweb
| 956
| 55.54
|
Today at MIX11, Brad Olenick announced RIA/JS, a jQuery client for WCF RIA Services. This is an early preview that we want to get your feedback on. Long before WCF RIA Services V1.0 was released, we started talking RIA Services support for AJAX; in fact, you can see the item here on the RIA Services Wish List (11th ranked as of today). We hope that you’ll grab this preview and let us know if you like the direction we’re going.
In today’s state the features are somewhat limited, but many of the basic scenarios are in place:
This jQuery client is broken up into several script files. The factoring of these files will likely change with subsequent releases.
There are a few other script files that you will need to use as well:
The RIA/JS library is available in two forms:
Update: As of the August 2011 drop of RIA/JS, this walkthrough is now obsolete. jquery.array.js and jquery.datalink.js are no longer included in RIA/JS; instead, we have jquery.observable.js included. Additionally, the August 2011 preview works with jQuery 1.5.1+ instead of 1.4.4.
For an updated walkthrough, please refer to the WCF CodePlex site where the BigShelf application is used.
Let’s walk through a super quickstart that illustrates how to query and submit data through the jQuery client.
[EnableClientAccess()]public class CustomerService : DomainService{ public IQueryable<Customer> GetCustomers() { return new[] { new Customer { CustomerId = 1, CustomerName = "John Doe" } }.AsQueryable(); } public void UpdateCustomer(Customer customer) { }} public class Customer{ [Key] public int CustomerId { get; set; } public string CustomerName { get; set; }}
<script src="/Scripts/DataContext.js" type="text/javascript"></script><script src="/Scripts/DataSource.js" type="text/javascript"></script><script src="/Scripts/DomainServiceProxy.js" type="text/javascript"></script><script src="/Scripts/EntitySet.js" type="text/javascript"></script><script src="/Scripts/jquery.array.js" type="text/javascript"></script><script src="/Scripts/jQuery.DataLink.js" type="text/javascript"></script><script src="/Scripts/jquery.datasource.js" type="text/javascript"></script><script src="/Scripts/RemoteDataSource.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { var Name: <input type="text" name="CustomerName" /></div>
$([customers]).dataSource({ serviceUrl: serviceUrl, queryName: "GetCustomers", bufferChanges: true, refresh: render}).refresh();
<input type="button" value="Update Customer" id="submit" />
$("#submit").click(function () { $([customers]).dataSource().commitChanges();});
We will be publishing more details about this new jQuery client for WCF RIA Services. You can also find more information and the BigShelf sample application at.
Wednesday, April 13, 2011 2:42 PM
Very cool stuff, thanks. Maybe some use of jQuery templates with EntityObject mappings or embedded HTML Bridge functions would be nice. Overall though, this API will be invaluable.
when adding RiaServices.jQuery package using the latest ASP.NET MVC tools you getConflict occurred. 'jQuery 1.5.1' referenced but requested 'jQuery 1.4.4'. 'jQuery.vsdoc 1.5.1' depends on 'jQuery 1.5.1'.Reccomendations??
@Jarrod - Yes, this stuff works great with jQuery templates. Check out the BigShelf application for some uses like that: - The BigShelf app is included in the Samples within that MSI.@dob - Sorry for the trouble on this. If you can uninstall the existing jQuery package and then install the RIAServices.jQuery package, it should work. We will work soon to get RIA/JS working against jQuery 1.5+ to avoid this conflict.
Will this work with silverlight business application template??Thanks
@william simons,Yes, you can use the jQuery client over a Web application created from the BAT. However, the jQuery client requires Services Pack 2 Preview.
Hi Jeff Handley..when i use var serviceUrl = "/CustomerApp-CustomerService.svc"; var customers = [];but i have CustomerService.cs from where we are calling CustomerService.svc..i have to create a wcf service for it..
@vikas,The client is meant to be used over top of a WCF RIA Services DomainService. RIA Services allows you to create a class such as CustomerService.cs, deriving from DomainService, and we generate the appropriate WCF Service (.SVC file) for you at runtime.For more information on how RIA Services does this, you can read this post by Saurabh:blogs.msdn.com/...If you are using the walkthrough above, the CustomerService.cs file will produce the WCF service you need at runtime, and the Url to the service is /[Namespace]-[ClassName].svc as you see in this sample. Essentially, wherever there's a dot in the fully-qualified type name to the DomainService class, you replace it with a dash.I hope this helps,Jeff Handley
I installed WcfJQuery.msi but could not find the BigShelf sample. Can you please let me know where the BigShelf sample is installed? or where to get it? TIA
Great that the whishlist is still being read!I love ria and sl but I'm pretty tired of the simple application demo. I want a real world example with multiple many to many relations and lookups. And this must work declaratively. This is the 21st century!
Hey, this looks very cool!How do you authenticate via an domain auth service before calling the domain service's methods?
Hi,Update oeration is stuck at - var self = this; $.ajax({ url: this._serviceUrl + "/JSON/SubmitChanges", contentType: "application/json", type: "POST", data: JSON.stringify({ changeSet: operations }), success: function (data) {Script fails saying can't find JSON..I don't recall this folder being asked to create...Any guidance will be really helpful.Thanks,Mahesh.
I am having trouble getting this example to work. The Domain Service is working fine and in Fiddler I can see it returning the expected results. In the debugger DomainServiceProxy calls successCallback but in DataContext the queryResult.metaData is undefined.Any clues on where to look would be greatly appreciated.Don Rule
There are two Microsoft.ServiceModel.DomainServices.Hosting assemblies included in the Toolkit download. Be sure to reference the one under the "SP2" folder. The other one was left in place because it is backwards compatible with SP1, but it doesn't include the metadata.The other option is to use the RiaServices.jQuery NuGet package to get your references added for you.Hope this helps,Jeff Handley
Jeff,I'm having the same problem Don was having. I followed the walk-through and made sure I referenced Microsoft.ServiceModel.DomainServices.Hosting.dll under the SP2 folder. But the queryResult.Metadata is still empty. What else could be missing?
Jeff,I think I got it. I need to set transmitMedatadata to true in the Web.Config for the JSON endpoint. " />
I much prefer straight WCF over RIA Services, we have more control, although we do generate RIA services as well out of the box.Here is an example of a pure HTML page using EntitySpaces + Knockout (MVVM for Javascript) with full change tracking of row state and dirty columns....
I am trying to get this running but I'm not sure if I'm just having issues since this article is few months old and things have changed? I installed this using the latest nuget package however...jquery.array.jsjQuery Data LinkjQuery TemplatesjQuery ValidateAll were not found in my solution so I hunted each of them down individually. After then I added them all in the order the article says. When I run the app it seems to crash inside DataSource.js line 185 - $.observable.extend(this._clientEntities, {$.observable is null. Really not sure what could be causing this.
1. Unfortunaly it doesn't work with JsonP :(.2. How does it work with Guid parameters in where clauses? I tried to add filter with guid parameter but server return error. In URL I see my guid as string. But it's wrong...
Was having trouble loading an entity with multiple keys. I was getting the correct number of records but each was identical.Then had a look at line 2479 in ria.js where an entity ID is returned and noticed it was using only the first key in the array ...return entity[metadataForType.key[0]];if I replace with something like this ...var stringKey;$.each(metadataForType.key, function(key) { stringKey += entity[key];}); return stringKey;it works fine.Is this by design?
Hi Darryl,Yes, this is a limitation in the current preview. We will support multipart keys in a later release.Thanks,Jeff
Jeff,I was hoping to keep entity collection filtering on the client but it appears filtering a datasource results in a web service call.For example, using the BigShelf app, would it be possible to load all books and then filter (linq style) that datasource client side?
Yes, this should be/become possible. The idea is to use a Local Data Source over top of a Remote Data Source, where the remote data source loads all data, and then the local data source filters what's loaded locally.
Not sure if this is the best place to ask questions and, if not, please point me in the right direction.I've been able to build some interesting stuff on my local box but I'm struggling trying to get things up and running on a remote server.I was getting the dreaded 'EndpointNotFoundException' and 'The service '/WebSite/*-*-*.svc' does not exist' errors. I just couldn't get the service to spin up at runtime until I removed the 'PrecompiledApp.config' file from the root of the website.Viola, the service was created and I could navigate to it manually.Problem is when I remove this file my website doesn't run.Do you have any idea why 'PrecompiledApp.config' would interfere with RIA services?
I am getting the following Error.Uncaught TypeError: Cannot read property 'length' of undefinedIt successfully invoke the Doaminservice method.Also want to have more control over the Calllike, success,Error,before send etc
Jeff,Any closer to supporting multipart keys?Thanks,Darry
|
http://jeffhandley.com/archive/2011/04/13/RIAJS-jQuery-client-for-WCF-RIA-Services.aspx
|
CC-MAIN-2017-13
|
refinedweb
| 1,635
| 61.02
|
After yesterday, I am down to two items on my TODO list for 1.1 of couch_docs:
I spend a lot of time on the
!jsonmacro tonight, making decent progress on it, before deciding to abandon it.
It was hard to give up because of the time invested in it. At first I tried class level methods to locate the source file and to replace the
!jsonmacro in source code with the contents of that source file. Those seemed like "class level" operations at first. After BDD'ing for a bit, I realized that I was passing around the root directory (specified when instantiating a
DesignDirectoryobject) too much. I eventually converted to instance methods which made for much cleaner implementation.
I was actually pretty happy with the code at this point—all the more so for having fought my way through an initial poor choice. I ultimately decided to abandon the code after a Pomodoro 5 break. Pomodoro 5 minute breaks (after 25 minutes of intense coding) are great for taking a step back. My mind got so wrapped up doing the implementation that I had not stepped back to ask if I should.
Part of the reason I should not support
!json(at least in couch_docs 1.1) is that it is going to be hard to implement. I can locate the source file based on the macro, but that is only half of the problem. I would still need to quote escape the contents of the file so that they could be assigned to a Javascript variable. That is not too hard, but it is still work. To fully support CouchApp's
!json, I would also need to map dot notation in the macro into directory structure on the file system and then back to Javascript objects. To illustrate, this macro:
// !json foo.barwould expect a file
bar.js(or any file with a basename of "bar" in the foo sub-directory). The resulting code to be uploaded would then need to look like:
var foo = {"bar": "contents of bar.js here"};Again, do-able, but not trivial.
Ultimately though, I am not shying away from effort here. It is a simple matter that I do not need the
!jsonmacro. That macro makes a lot of sense in CouchApp where it is often used to hold HTML templates. I have no intention of reimplementing CouchApp in Ruby. I am really only interested in keeping my Javascript views DRY. If I need common configuration, I can define a configuration function. Both of those things can be accomplished with the
!codemacro.
Even better, the
!codemacro is simple. Consider this:
// !code foo/bar.jsBefore pushing this to to CouchDB, that macro should be replaced with the contents of the
foo/bar.jsfile. Easy peasy.
With heavy heart, I revert my
!jsonwork to date and write two RSpec
examples for the
!codemacro:
it "should replace !code macros with the contents of the referenced file in lib" doThe first example describes at a high level what should happen in the presence of the
@it.stub!(:read_from_lib).and_return("awesome javascript")
@it.
process_code_macro(" // !code foo/bar.js ").
should == "awesome javascript"
end
it "should not affect normal lines when processing macros" do
@it.
process_code_macro(" var foo = 'bar'; ").
should == " var foo = 'bar'; "
end
!codemacro. The second example states that processing code macros on normal lines should have no effect. Both of these examples fail because I have not defined the
process_code_macromethod:
1)I define the method, give it the right arity and then make the second example pass by returning the input back:
NoMethodError in 'CouchDocs::DesignDirectory a valid directory should replace !code macros with the contents of the referenced file in lib'
undefined method `process_code_macro' for #<CouchDocs::DesignDirectory:0xb74b97c4>
./spec/couch_docs_spec.rb:309:
def process_code_macro(line)Finally, I can make the first example pass by reading the contents of the specified file from the library directory:
line
end
def process_code_macro(line)What the library directory is or where it resides I will decide tomorrow along with the rest of
if line =~ %r{\s*//\s*!code\s*(\S+)\s*}
read_from_lib($1)
else
line
end
end
read_from_lib. For now I have reached a happy stopping point. I have less code than I did 30 minutes ago, but that is almost always a good thing.
Day #33
|
https://japhr.blogspot.com/2010/03/my-chain-next-after-yesterday-i-am-down.html
|
CC-MAIN-2018-05
|
refinedweb
| 718
| 74.9
|
> at91rm9200_test.rar > inflate.h
#define DEBG(x) #define DEBG1(x) /* inflate.c -- Not copyrighted 1992 by Mark Adler version c10p1, 10 January 1993 */ /* * Adapted for booting Linux by Hannu Savolainen 1993 * based on gzip-1.0.3 */ /* Inflate deflated (PKZIP's method 8 compressed) data. The compression method searches for as much of the current string of bytes (up to a length of 258) in the previous 32K bytes. If it doesn't find any matches (of at least length 3), it codes the next byte. Otherwise, it codes the length of the matched string and its distance backwards from the current position. There is a single Huffman code that codes both single bytes (called "literals") and match lengths. A second Huffman code codes the distance information, which follows a length code. Each length or distance code actually represents a base value and a number of "extra" (sometimes zero) bits to get to add to the base value. At the end of each deflated block is a special end-of-block (EOB) literal/ length code. The decoding process is basically: get a literal/length code; if EOB then done; if a literal, emit the decoded byte; if a length then get the distance and emit the referred-to bytes from the sliding window of previously emitted data. There are (currently) three kinds of inflate blocks: stored, fixed, and dynamic. The compressor deals with some chunk of data at a time, and decides which method to use on a chunk-by-chunk basis. A chunk might typically be 32K or 64K. If the chunk is uncompressible, then the "stored" method is used. In this case, the bytes are simply stored as is, eight bits per byte, with none of the above coding. The bytes are preceded by a count, since there is no longer an EOB code. If the data is compressible, then either the fixed or dynamic methods are used. In the dynamic method, the compressed data is preceded by an encoding of the literal/length and distance Huffman codes that are to be used to decode this block. The representation is itself Huffman coded, and so is preceded by a description of that code. These code descriptions take up a little space, and so for small blocks, there is a predefined set of codes, called the fixed codes. The fixed method is used if the block codes up smaller that way (usually for quite small chunks), otherwise the dynamic method is used. In the latter case, the codes are customized to the probabilities in the current block, and so can code it much better than the pre-determined fixed codes. The Huffman codes themselves are decoded using a multi-level table lookup, in order to maximize the speed of decoding plus the speed of building the decoding tables. See the comments below that precede the lbits and dbits tuning parameters. */ /* Notes beyond the 1.93a appnote.txt: 1. Distance pointers never point before the beginning of the output stream. 2. Distance pointers can point back across blocks, up to 32k away. 3. There is an implied maximum of 7 bits for the bit length table and 15 bits for the actual data. 4. If only one code exists, then it is encoded using one bit. (Zero would be more efficient, but perhaps a little confusing.) If two codes exist, they are coded using one bit each (0 and 1). 5. There is no way of sending zero distance codes--a dummy must be sent if there are none. (History: a pre 2.0 version of PKZIP would store blocks with no distance codes, but this was discovered to be too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one code of zero bits in length. 6. There are up to 286 literal/length codes. Code 256 represents the end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits defined for them. Similarly, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be complete (see #4). 8. The five bits following the block type is really the number of literal codes sent minus 257. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits (1+6+6). Therefore, to output three times the length, you output three codes (1+1+1), whereas to output four times the same length, you only need two codes (1+3). Hmm. 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(i) is not zero. (Pretty obvious.) 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) 12. Note: length code 284 can represent 227-258, but length code 285 really is 258. The last length deserves its own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the min match length) is 255. 13. The literal/length and distance code bit lengths are read as a single stream of lengths. It is possible (and advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths. */ #ifdef RCSID static char rcsid[] = "#Id: inflate.c,v 0.14 1993/06/10 13:27:04 jloup Exp #"; #endif #ifndef STATIC #if defined(STDC_HEADERS) || defined(HAVE_STDLIB_H) # include
# include #endif #include "gzip.h" #define STATIC #endif /* !STATIC */ #define slide window /* Huffman code lookup table entry--this entry is four bytes for machines that have 16-bit pointers (e.g. PC's in the small or medium model). Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16 means that v is a literal, 16 < e < 32 means that v is a pointer to the next table, which codes e - 16 bits, and lastly e == 99 indicates an unused code. If a code with e == 99 is looked up, this implies an error in the data. */ struct huft { uch e; /* number of extra bits or operation */ uch b; /* number of bits in this code or subcode */ union { ush n; /* literal, length base, or distance base */ struct huft *t; /* pointer to next level of table */ } v; }; /* Function prototypes */ STATIC int huft_build OF((unsigned *, unsigned, unsigned, ush *, ush *, struct huft **, int *)); STATIC int huft_free OF((struct huft *)); STATIC int inflate_codes OF((struct huft *, struct huft *, int, int)); STATIC int inflate_stored OF((void)); STATIC int inflate_fixed OF((void)); STATIC int inflate_dynamic OF((void)); STATIC int inflate_block OF((int *)); STATIC int inflate OF((void)); /* The inflate algorithm uses a sliding 32K byte window on the uncompressed stream to find repeated byte strings. This is implemented here as a circular buffer. The index is updated simply by incrementing and then and'ing with 0x7fff (32K-1). */ /* It is left to other modules to supply the 32K area. It is assumed to be usable as if it were declared "uch slide[32768];" or as just "uch *slide;" and then malloc'ed in the latter case. The definition must be in unzip.h, included above. */ /* unsigned wp; current position in slide */ #define wp outcnt #define flush_output(w) (wp=(w),flush_window()) /* Tables for deflate from PKZIP's appnote.txt. */ static unsigned border[] = { /* Order of the bit length code lengths */ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static ush cplens[] = { /* Copy lengths for literal codes 257..285 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; /* note: see note #13 above about the 258 in this list. */ static ush cplext[] = { /* Extra bits for literal codes 257..285 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */ static ush cpdist[] = { /* Copy offsets for distance codes 0..29 */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static ush cpdext[] = { /* Extra bits for distance codes */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; /* Macros for inflate() bit peeking and grabbing. The usage is: NEEDBITS(j) x = b & mask_bits[j]; DUMPBITS(j) where NEEDBITS makes sure that b has at least j bits in it, and DUMPBITS removes the bits from b. The macros use the variable k for the number of bits in b. Normally, b and k are register variables for speed, and are initialized at the beginning of a routine that uses these macros from a global bit buffer and count. If we assume that EOB will be the longest code, then we will never ask for bits with NEEDBITS that are beyond the end of the stream. So, NEEDBITS should not read any more bytes than are needed to meet the request. Then no bytes need to be "returned" to the buffer at the end of the last block. However, this assumption is not true for fixed blocks--the EOB code is 7 bits, but the other literal/length codes can be 8 or 9 bits. (The EOB code is shorter than other codes because fixed blocks are generally short. So, while a block always has an EOB, many other literal/length codes have a significantly lower probability of showing up at all.) However, by making the first table have a lookup of seven bits, the EOB code will be found in that first lookup, and so will not require that too many bits be pulled from the stream. */ STATIC ulg bb; /* bit buffer */ STATIC unsigned bk; /* bits in bit buffer */ STATIC ush mask_bits[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; #define NEXTBYTE() (uch)get_byte() #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())< >=(n);k-=(n);} /* Huffman code decoding is performed using a multi-level table lookup. The fastest way to decode is to simply build a lookup table whose size is determined by the longest code. However, the time it takes to build this table can also be a factor if the data being decoded is not very long. The most common codes are necessarily the shortest codes, so those codes dominate the decoding time, and hence the speed. The idea is you can have a shorter table that decodes the shorter, more probable codes, and then point to subsidiary tables for the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. This results of this trade are in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to those sizes. These values may be adjusted either when all of the codes are shorter than that, in which case the longest code length in bits is used, or when the shortest code is *longer* than the requested table size, in which case the length of the shortest code in bits is used. There are two different values for the two tables, since they code a different number of possibilities each. The literal/length table codes 286 possible values, or in a flat code, a little over eight bits. The distance table codes 30 possible values, or a little less than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and possibly even between compilers. Your mileage may vary. */ STATIC int lbits = 9; /* bits in base literal/length lookup table */ STATIC int dbits = 6; /* bits in base distance lookup table */ /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */ #define BMAX 16 /* maximum bit length of any code (16 for explode) */ #define N_MAX 288 /* maximum number of codes in any set */ STATIC unsigned hufts; /* track memory usage */ STATIC int huft_build(b, n, s, d, e, t, m) unsigned *b; /* code lengths in bits (all assumed <= BMAX) */ unsigned n; /* number of codes (assumed <= N_MAX) */ unsigned s; /* number of simple-valued codes (0..s-1) */ ush *d; /* list of base values for non-simple codes */ ush *e; /* list of extra bits for non-simple codes */ struct huft **t; /* result: starting table */ int *m; /* maximum lookup bits, returns actual */ /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. */ { unsigned a; /* counter for codes of length k */ unsigned c[BMAX+1]; /* bit length count table */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int h; /* table level */ register unsigned i; /* counter, current code */ register unsigned j; /* counter */ register int k; /* number of bits in current code */ int l; /* bits per table (returned in m) */ register unsigned *p; /* pointer into c[], b[], or v[] */ register struct huft *q; /* points to current table */ struct huft r; /* table entry for structure assignment */ struct huft *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ register int w; /* bits before this table == (l * h) */ unsigned x[BMAX+1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ DEBG("huft1 "); /* Generate counts for each bit length */ memzero(c, sizeof(c)); p = b; i = n; do { Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? "%c %d\n" : "0x%x %d\n"), n-i, *p)); c[*p]++; /* assume all entries <= BMAX */ p++; /* Can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) /* null input--all zero length codes */ { *t = (struct huft *)NULL; *m = 0; return 0; } DEBG("huft2 "); /* Find minimum and maximum length, bound *m by those */ l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; /* minimum code length */ if ((unsigned)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; /* maximum code length */ if ((unsigned)l > i) l = i; *m = l; DEBG("huft3 "); /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */ if ((y -= c[i]) < 0) return 2; c[i] += y; DEBG("huft4 "); /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ *xp++ = (j += *p++); } DEBG("huft5 "); /* Make a table of values in order of bit lengths */ p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); DEBG("h6 "); /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ h = -1; /* no tables yet--level -1 */ w = -l; /* bits decoded == (l * h) */ u[0] = (struct huft *)NULL; /* just to keep compilers happy */ q = (struct huft *)NULL; /* ditto */ z = 0; /* ditto */ DEBG("h6a "); /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { DEBG("h6b "); a = c[k]; while (a--) { DEBG("h6b1 "); /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > w + l) { DEBG1("1 "); h++; w += l; /* previous table always l bits */ /* compute minimum size table less than or equal to l bits */ z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ { /* too few codes for k-w bit table */ DEBG1("2 "); f -= a + 1; /* deduct codes from patterns left */ xp = c + k; while (++j < z) /* try smaller tables up to z bits */ { if ((f <<= 1) <= *++xp) break; /* enough codes to use up j bits */ f -= *xp; /* else deduct codes from patterns */ } } DEBG1("3 "); z = 1 << j; /* table entries for j-bit table */ /* allocate and link in new table */ if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == (struct huft *)NULL) { if (h) huft_free(u[0]); return 3; /* not enough memory */ } DEBG1("4 "); hufts += z + 1; /* track memory usage */ *t = q + 1; /* link to list for huft_free() */ *(t = &(q->v.t)) = (struct huft *)NULL; u[h] = ++q; /* table starts after link */ DEBG1("5 "); /* connect to last table, if there is one */ if (h) { x[h] = i; /* save pattern for backing up */ r.b = (uch)l; /* bits to dump before this table */ r.e = (uch)(16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = i >> (w - l); /* (get around Turbo C bug) */ u[h-1][j] = r; /* connect to last table */ } DEBG1("6 "); } DEBG("h6c "); /* set up table entry in r */ r.b = (uch)(k - w); if (p >= v + n) r.e = 99; /* out of values--invalid code */ else if (*p < s) { r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ r.v.n = (ush)(*p); /* simple code is just the value */ p++; /* one compiler does not like *p++ */ } else { r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } DEBG("h6d "); /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[h]) { h--; /* don't need to update q */ w -= l; } DEBG("h6e "); } DEBG("h6f "); } DEBG("huft7 "); /* Return true (1) if we were given an incomplete table */ return y != 0 && g != 1; } STATIC int huft_free(t) struct huft *t; /* table to free */ /* Free the malloc'ed tables built by huft_build(), which makes a linked list of the tables it made, with the links in a dummy first entry of each table. */ { register struct huft *p, *q; /* Go through linked list, freeing from the malloced (t[-1]) address. */ p = t; while (p != (struct huft *)NULL) { q = (--p)->v.t; free((char*)p); p = q; } return 0; } STATIC int inflate_codes(tl, td, bl, bd) struct huft *tl, *td; /* literal/length and distance decoder tables */ int bl, bd; /* number of bits decoded by tl[] and td[] */ /* inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. */ { register unsigned e; /* table entry flag/number of extra bits */ unsigned n, d; /* length and index for copy */ unsigned w; /* current window position */ struct huft *t; /* pointer to table entry */ unsigned ml, md; /* masks for bl and bd bits */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local copies of globals */ b = bb; /* initialize bit buffer */ k = bk; w = wp; /* initialize window position */ /* inflate the coded data */ ml = mask_bits[bl]; /* precompute masks for speed */ md = mask_bits[bd]; for (;;) /* do until end of block */ { NEEDBITS((unsigned)bl) if ((e = (t = tl + ((unsigned)b & ml))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) if (e == 16) /* then it's a literal */ { slide[w++] = (uch)t->v.n; Tracevv((stderr, "%c", slide[w-1])); if (w == WSIZE) { flush_output(w); w = 0; } } else /* it's an EOB or a length */ { /* exit if end of block */ if (e == 15) break; /* get length of block to copy */ NEEDBITS(e) n = t->v.n + ((unsigned)b & mask_bits[e]); DUMPBITS(e); /* decode distance of block to copy */ NEEDBITS((unsigned)bd) if ((e = (t = td + ((unsigned)b & md))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) NEEDBITS(e) d = w - t->v.n - ((unsigned)b & mask_bits[e]); DUMPBITS(e) Tracevv((stderr,"\\[%d,%d]", w-d, n)); /* do the copy */ do { n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e); #if !defined(NOMEMCPY) && !defined(DEBUG) if (w - d >= e) /* (this test assumes unsigned comparison) */ { memcpy(slide + w, slide + d, e); w += e; d += e; } else /* do it slow to avoid memcpy() overlap */ #endif /* !NOMEMCPY */ do { slide[w++] = slide[d++]; Tracevv((stderr, "%c", slide[w-1])); } while (--e); if (w == WSIZE) { flush_output(w); w = 0; } } while (n); } } /* restore the globals from the locals */ wp = w; /* restore global window pointer */ bb = b; /* restore global bit buffer */ bk = k; /* done */ return 0; } STATIC int inflate_stored() /* "decompress" an inflated type 0 (stored) block. */ { unsigned n; /* number of bytes in block */ unsigned w; /* current window position */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ DEBG(" "); return 0; } STATIC int inflate_fixed() /* decompress an inflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. */ { int i; /* temporary variable */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned l[288]; /* length list for huft_build */ DEBG(" 1) { huft_free(tl); DEBG(">"); return i; } /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; /* free the decoding tables, return */ huft_free(tl); huft_free(td); return 0; } STATIC int inflate_dynamic() /* decompress an inflated type 2 (dynamic Huffman codes) block. */ { int i; /* temporary variables */ unsigned j; unsigned l; /* last length */ unsigned m; /* mask for bit lengths table */ unsigned n; /* number of lengths to get */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned nb; /* number of bit length codes */ unsigned nl; /* number of literal/length codes */ unsigned nd; /* number of distance codes */ #ifdef PKZIP_BUG_WORKAROUND unsigned ll[288+32]; /* literal/length and distance code lengths */ #else unsigned ll[286+30]; /* literal/length and distance code lengths */ #endif register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ DEBG(" 288 || nd > 32) #else if (nl > 286 || nd > 30) #endif return 1; /* bad lengths */ DEBG("dyn1 "); /* read in bit-length-code lengths */ for (j = 0; j < nb; j++) { NEEDBITS(3) ll[border[j]] = (unsigned)b & 7; DUMPBITS(3) } for (; j < 19; j++) ll[border[j]] = 0; DEBG("dyn2 "); /* build decoding table for trees--single level, 7 bit lookup */ bl = 7; if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) { if (i == 1) huft_free(tl); return i; /* incomplete code set */ } DEBG("dyn3 "); /* read in literal and distance code lengths */ n = nl + nd; m = mask_bits[bl]; i = l = 0; while ((unsigned)i < n) { NEEDBITS((unsigned)bl) j = (td = tl + ((unsigned)b & m))->b; DUMPBITS(j) j = td->v.n; if (j < 16) /* length of code in bits (0..15) */ ll[i++] = l = j; /* save last length in l */ else if (j == 16) /* repeat last length 3 to 6 times */ { NEEDBITS(2) j = 3 + ((unsigned)b & 3); DUMPBITS(2) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = l; } else if (j == 17) /* 3 to 10 zero length codes */ { NEEDBITS(3) j = 3 + ((unsigned)b & 7); DUMPBITS(3) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } else /* j == 18: 11 to 138 zero length codes */ { NEEDBITS(7) j = 11 + ((unsigned)b & 0x7f); DUMPBITS(7) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } } DEBG("dyn4 "); /* free decoding table for trees */ huft_free(tl); DEBG("dyn5 "); /* restore the global bit buffer */ bb = b; bk = k; DEBG("dyn5a "); /* build the decoding tables for literal/length and distance codes */ bl = lbits; if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) { DEBG("dyn5b "); if (i == 1) { error(" incomplete literal tree\n"); huft_free(tl); } return i; /* incomplete code set */ } DEBG("dyn5c "); bd = dbits; if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) { DEBG("dyn5d "); if (i == 1) { error(" incomplete distance tree\n"); #ifdef PKZIP_BUG_WORKAROUND i = 0; } #else huft_free(td); } huft_free(tl); return i; /* incomplete code set */ #endif } DEBG("dyn6 "); /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; DEBG("dyn7 "); /* free the decoding tables, return */ huft_free(tl); huft_free(td); DEBG(">"); return 0; } STATIC int inflate_block(e) int *e; /* last block flag */ /* decompress an inflated block */ { unsigned t; /* block type */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ DEBG(" "); /* bad block type */ return 2; } STATIC int inflate() /* decompress an inflated entry */ { int e; /* last block flag */ int r; /* result code */ unsigned h; /* maximum struct huft's malloc'ed */ void *ptr; /* initialize window, bit buffer */ wp = 0; bk = 0; bb = 0; /* decompress until the last block */ h = 0; do { hufts = 0; gzip_mark(&ptr); if ((r = inflate_block(&e)) != 0) { gzip_release(&ptr); return r; } gzip_release(&ptr); if (hufts > h) h = hufts; } while (!e); /* Undo too much lookahead. The next read will be byte aligned so we * can discard unused bits in the last meaningful byte. */ while (bk >= 8) { bk -= 8; inptr--; } /* flush out slide */ flush_output(wp); /* return success */ #ifdef DEBUG fprintf(stderr, "<%u> ", h); #endif /* DEBUG */ return 0; } /********************************************************************** * * The following are support routines for inflate.c * **********************************************************************/ static ulg crc_32_tab[256]; static ulg crc = (ulg)0xffffffffL; /* shift register contents */ #define CRC_VALUE (crc ^ 0xffffffffL) /* * Code to compute the CRC-32 table. Borrowed from * gzip-1.0.3/makecrc.c. */ static void makecrc(void) { /* Not copyrighted 1990 Mark Adler */ */ e = 0; for (i = 0; i < sizeof(p)/sizeof(int); i++) e |= 1L << (31 - p[i]); crc_32_tab[0] = 0; for (i = 1; i < 256; i++) { c = 0; for (k = i | 256; k != 1; k >>= 1) { c = c & 1 ? (c >> 1) ^ e : c >> 1; if (k & 1) c ^= e; } crc_32_tab[i] = c; } } /* gzip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */ #define RESERVED 0xC0 /* bit 6,7: reserved */ /* * Do the uncompression! */ static int gunzip(void) { uch flags; unsigned char magic[2]; /* magic header */ char method; ulg orig_crc = 0; /* original crc */ ulg orig_len = 0; /* original uncompressed length */ int res; magic[0] = (unsigned char)get_byte(); magic[1] = (unsigned char)get_byte(); method = (unsigned char)get_byte(); if (magic[0] != 037 || ((magic[1] != 0213) && (magic[1] != 0236))) { error("bad gzip magic numbers"); return -1; } /* We only support method #8, DEFLATED */ if (method != 8) { error("internal error, invalid method"); return -1; } flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { error("Input is encrypted\n"); return -1; } if ((flags & CONTINUATION) != 0) { error("Multi part input\n"); return -1; } if ((flags & RESERVED) != 0) { error("Input has invalid flags\n"); return -1; } (ulg)get_byte(); /* Get timestamp */ ((ulg)get_byte()) << 8; ((ulg)get_byte()) << 16; ((ulg)get_byte()) << 24; (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { /* Discard the old name */ while (get_byte() != 0) /* null */ ; } /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_byte() != 0) /* null */ ; } /* Decompress */ if ((res = inflate())) { switch (res) { case 0: break; case 1: error("invalid compressed format (err=1)"); break; case 2: error("invalid compressed format (err=2)"); break; case 3: error("out of memory"); break; default: error("invalid compressed format (other)"); } return -1; } /* Get the crc and original length */ /* crc32 (see algorithm.doc) * uncompressed input size modulo 2^32 */ orig_crc = (ulg) get_byte(); orig_crc |= (ulg) get_byte() << 8; orig_crc |= (ulg) get_byte() << 16; orig_crc |= (ulg) get_byte() << 24; orig_len = (ulg) get_byte(); orig_len |= (ulg) get_byte() << 8; orig_len |= (ulg) get_byte() << 16; orig_len |= (ulg) get_byte() << 24; /* Validate decompression */ if (orig_crc != CRC_VALUE) { error("crc error"); return -1; } if (orig_len != bytes_out) { error("length error"); return -1; } return 0; }
|
http://read.pudn.com/downloads100/sourcecode/embed/409826/at91rm9200_test/inc/inflate.h__.htm
|
crawl-002
|
refinedweb
| 4,866
| 61.9
|
I'm just trying to support the save_and_sleep() support into u-boot
for an au1100 based board.
Into u-boot I added the following code:
Index: cpu/mips/start.S
===================================================================
RCS file: /home/develop/cvs_private/uboot-mips-exadron/cpu/mips/start.S,v
retrieving revision 1.2
diff -u -r1.2 start.S
--- cpu/mips/start.S 12 Oct 2005 12:55:54 -0000 1.2
+++ cpu/mips/start.S 16 Dec 2005 15:29:22 -0000
@@ -26,6 +26,7 @@
#include <config.h>
#include <version.h>
#include <asm/regdef.h>
+#include <asm/au1x00.h>
#include <asm/mipsregs.h>
@@ -273,6 +274,33 @@
li t0, CONF_CM_CACHABLE_NONCOHERENT
mtc0 t0, CP0_CONFIG
+ /* Now check the wakeup cause
+ */
+ li t0, SYS_WAKESRC
+ lw t1, 0(t0)
+ andi t1, t1, 0x00000002 /* check the SW bit */
+ beq zero, t1, 1f
+ nop
+
+ li t0, SYS_SCRATCH0
+ lw t1, 0(t0)
+ move sp, t1
+ li t0, SYS_SCRATCH1
+ lw t1, 0(t0)
+ j t1 /* this cause a jump into already
+ nop frozen Linux (brr! :) */
+
+ /* If we reach this point we come from a normal system power up,
+ so just clear the wakeup cause registers
+ */
+
+1: li t0, SYS_WAKEMSK
+ li t1, 0x00000000
+ sw t1, 0(t0)
+
+ li t0, SYS_WAKESRC
+ li t1, 0x00000000
+ sw t1, 0(t0)
/* Set up temporary stack.
*/
in order to restore the scratch registers contents as descibed into
file "linux/arch/mips/au1000/common/sleeper.S":
/* Now set up the scratch registers so the boot rom will
* return to this point upon wakeup.
*/
la k0, 1f
lui k1, 0xb190
ori k1, 0x18
sw sp, 0(k1)
ori k1, 0x1c
sw k0, 0(k1)
However it seems something is wrong since the system at the end of
save_and_sleep() does not correctly continue its execution...
Unlikely my JTAG do not allow me to follow the code after the
save_and_sleep()'s return (I definitely have to buy a better one),
however I noticed that when the system tryes to resume the register 29
(the sp) doing:
lw $29, PT_R29(sp)
something goes wrong!
Suggestions? :)
Thanks in advance,
Rodolfo
--
GNU/Linux Solutions e-mail: giometti@enneenne.com
Linux Device Driver giometti@gnudd.com
Embedded Systems giometti@linux.it
UNIX programming phone: +39 349 2432127
|
https://www.linux-mips.org/archives/linux-mips/2005-12/msg00107.html
|
CC-MAIN-2017-04
|
refinedweb
| 361
| 74.08
|
I think the answer crucially depends on what you mean by the word "function".
It could be a Python or Cython function, either defined in an interactive session or in a module. It could be a symbolic expression, or perhaps could be a polynomial, which are sometimes mistaken for a function.
Symbolic function is easy to pickle:
sage: f(x) = x^2 sage: type(f) <type 'sage.symbolic.expression.Expression'> sage: tmp = tmp_filename() sage: save(f,tmp) sage: load(tmp) x^2
Similarly, a polynomial is easy to pickle:
sage: P.<x> = QQ[] sage: p = x^2 sage: type(p) <type 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint'> sage: save(p,tmp) sage: load(tmp) x^2
However, if you are really talking about a Python function (e.g., a lambda function), then there is a general problem: You can't easily pickle Python functions defined in an interactive session. And Python is Sage's programming language.
sage: def f(x): ....: return x ....: sage: save(f,tmp) --------------------------------------------------------------------------- PicklingError Traceback (most recent call last) /home/simon/SAGE/sage-5.0.beta7/devel/sage-main/<ipython console> in <module>() /home/simon/SAGE/sage-5.0.beta7/local/lib/python2.7/site-packages/sage/structure/sage_object.so in sage.structure.sage_object.save (sage/structure/sage_object.c:8647)() PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
However, if you define the same function in some Python module, then pickling would work.
And what do you mean by the "contents" of a function?
Do you mean, you have a Python function and want to see its code?
Then again, if it is defined in a module, then it works easily: If you have any object
X (function or anything else) in Sage, then you can try to see its code by appending two question marks and hitting return (or shift-return in the Sage notebook). And with
edit(X,'vim') (inserting another editor name if you don't like vim), then you could actually edit the code.
But if the function is only defined in an interactive session, then Python can not find the code.
|
https://ask.sagemath.org/answers/13356/revisions/
|
CC-MAIN-2019-39
|
refinedweb
| 351
| 56.96
|
The Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, tweet, or email.
Steps to integrate with goo.gl :
Step #1 : Register App with Google
Register your App with Google through the API Console. When you create your application, you register it with Google. Google then provides information you’ll need later, such as a client ID and a client secret , Api key etc .
Step #2: Authorizing requests and identifying your application
Requests to the Google URL Shortener API for non-public user data must be authorized by an authenticated user.Every request your application sends to the Google URL Shortener API needs to identify your application to Google. Your App would be recognized by Google through API Key in the API Access pane.
Step #3: Activate the Google URL Shortener API
Activate the Google URL Shortener API in the Services pane of the Google APIs Console.
Step #4: Acquiring and using an API key
Requests to the Google URL Shortener API for public data must be accompanied by an identifier, which can be an API key or an auth token. Go to the API Access pane. The API key is near the bottom of that pane, in the section titled “Simple API Access.”
After you have an API key, your application can append the query parameter
key=yourAPIKey to all request URLs.
The API key is safe for embedding in URLs; it doesn’t need any encoding.
Step #5: Code in Play2.0 to Shorten a long URL
import play.libs.WS import play.api.Play def generateTinyUrl(longUrl: String): String = { val apiKey = "GOOGLE_API_KEY" val jpromise = WS.url("") .setHeader("Content-Type", "application/json") .setQueryParameter("key", apiKey) .post("""{"longUrl": """" + longUrl + """"}""") val shortUrlJson = jpromise.get().asJson shortUrlJson.get("id").toString }
OutPut: eg LongUrl=
TinyUrl would be :
Entire code can be found here:
This is the perfect blog for anyone who would like to find out about this topic.
You know so much its almost hard to argue with you (not that I personally would want to…HaHa).
You definitely put a brand new spin on a topic which has been written about for
decades. Wonderful stuff, just excellent!
|
https://blog.knoldus.com/2013/02/02/how-to-use-goo-gl-api-to-generate-tiny-url-in-play-framework/
|
CC-MAIN-2017-43
|
refinedweb
| 376
| 65.12
|
Python Programming, news on the Voidspace Python Projects and all things techie.
Gentoo
Note
I've had a very pleasant email from the gentleman who added this package to gentoo portage.
It's now updated to the current version.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-16 11:52:44 | |
On the Sillyness of Sourceforge Statistics
Sorry to bang on about ConfigObj - but the Sourceforge Statistics for it illustrate the Sillyness of Sourceforge Statistics - specifically the Activity Percentile.
For ConfigObj the activity percentile is shown as : (last week): 98.51
Presumably this means that ConfigObj is within the top 2% of active projects - yet if you look at the statistics page you will see that ConfigObj is ranked about position 2000 [1].
Most projects on sourceforge are dormant (numerically speaking anyway) - these are good ideas that died, or were still born and never produced any (or much) code. This means they skew the 'activity percentile' statistics horribly and that figure is useless. Now if they excluded the dormant projects - it might be an interesting figure......
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-14 10:06:56 | |
Categories: General Programming
Patching CGIHTTPServer
I've been playing with CGIHTTPServer.py again. It's basically a toy server - but very handy for local testing. This is especially true because sub-classing it to implement customer behaviour is joyously easy.
I've created my own sub-class that does some SSI processing, can serve from two folders [1], and runs in proxy mode [2]. You can see the current state over at CGIHTTPServerWithSSI.
Unfortunately I have a problem sigh. Actually I have lots of problems - but this one is specific
. Under Python 2.4 [3] the CGI environment variables aren't getting passed to CGI scripts that it runs using os.popen3 (under Windoze).
See the following code (from line 242 in the version shipped with Python 2.3) :
# but they aren't passed to the subprocess
files = popenx(cmdline, 'b')
fi = files[0]
fo = files[1]
if self.have_popen3:
fe = files[2]
The truly weird thing is that when I do my own test script calling the same command line - environment variables are passed on. Odd and frustrating. Further investigation needed.
In the process I've also edited CGIHTTPServer to allow two things (although my tests were on the un-fiddled-with version) :
- Paths with spaces in.
- CGI scripts from sub-directories of cgi-bin.
Note
These fixes are specific to the windoze code in CGIHTTPServer. They aren't going to get touched by a Lunix computer which uses fork in another branch of the code.
First, line 234 (again, the Python 2.3 version) changes from :
to :
Secondly, lines 86-90 change from :
i = len(x)
if path[:i] == x and (not path[i:] or path[i] == '/'):
self.cgi_info = path[:i], path[i+1:]
return True
to :
i = len(x)
# FIXME: What if this is -1 ?
j = path.rfind('/')
if path[:i] == x:
self.cgi_info = path[:j], path[j+1:]
return True
I wonder if there is an issue with 'PATH_INFO' and this second 'fix' ?.... hmmm...
Anyway - simple stuff, but it's helped me.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-14 09:35:01 | |
Rolling, Rolling, Rolling
The response to pythonutils was very good. Especially the odict module (ordered dictionary) - it's had over one hundred and fifty downloads already. Thanks to some useful user feedback, Nicola has updated and improved it.
More embarassingly I've done a bugfix release of ConfigObj - now up to beta 5.
All this is my way of saying that odict 0.1.2, pythonutils 0.2.2, and ConfigObj beta 5, are all available from the Voidspace Modules page.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-13 16:16:41 | |
Login and On
One of my 'projects' that has languished a bit is logintools.
logintools is a CGI authentication and user account management system. I created it for Jalopy [1]. Unfortunately, the project that Jalopy was for got shelved (much to my annoyance).
Thankfully I'm now in the progress of a simple CGI CRM system that will use logintools. I've just converted it over to use the new pythonutils stuff [2].
I was again struck by how easy protecting a CGI application with logintools is
. It was just a case of adding add a few lines to the start of the application - and authentication/account management is fully handled :
userdir = 'users/'
def main(theform, userdir):
# this function displays login and exits if it fails, otherwise it prints
# the new/updated cookie.
action, userconfig = login(theform, userdir)
username = userconfig['realname']
loginname = userconfig['username']
# rest of application from here
if __name__ == '__main__':
theform = cgi.FieldStorage()
main(theform, userdir)
The CRM probably won't be open source [3] - but logintools should get some work at last.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-13 09:23:14 | |
Aaaargh (again)
I've been porting all my apps and tools to use the new version of ConfigObj. In the process I've uncovered two more moderately serious bugs.
We weren't unquoting keys and a comma in an inline comment could be wrongly recognised as a list (a failing in the regular expression we used).
These are now both in SVN, along with an update to odict.py. These include a barrage of improvements suggested by a gentleman called Tim Wegener (although it was pretty good in the first place).
This means I'll be doing a ConfigObj Beta 5 release, along with a Pythonutils 0.2.2 very soon. sigh
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2005-09-13 08:38:23 | |
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter...
|
http://www.voidspace.org.uk/python/weblog/arch_d7_2005_09_10.shtml
|
CC-MAIN-2016-50
|
refinedweb
| 1,004
| 67.04
|
IWP54 | Windows Phone Data Binding and the Magic of XAML
- Posted: May 02, 2013 at 1:37 PM
- 32,586 Views
- 2 Comments
![if gt IE 8]> <![endif]>
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Download the sample project seen in this video.
Data binding is one of the fundamental concepts for good Windows Phone application design but can be difficult to grasp for newcomers. The core concept is this: No one wants to manually update the user interface elements. I want my UI to automatically reflect the state of my application and you see in this video and post, there are some really great "fringe" benefits in terms of interaction and design that we get along with the core benefits.
So let's build our first data binding. By a happy coincidence, this can also be our first ViewModel from scratch.
I use Visual Studio snippets in the video and in "real life" because it's substantially faster and I have a very poor memory. You can download the notify property snippets I used here. Just extract them into your "Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets" folder and you should be ready to go.
As a "first steps" post, we're going to go through how to build a data binding step by step. To see this model in action, just open up a new
My First Data Binding
In our app, lets create a new ViewModel. I right-clicked in the ViewModel folder and went to "App -> Class..." and created just an empty Class file named "SampleViewModel.cs". This class now looks like this:
class SampleViewModel { }
We update it to implement the INotifyPropertyChanged event by declaring that interface and using the "notifyInterface" snippet. Hit Alt-Shift-F10 to resolve any refrerences (specifically the System.ComponentModel) and our code should now look like this:
public class SampleViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }
Now we can just start creating properties we want to see reflected in our UI. Using our "notifyProp" snippet, we can quickly create a property like the string SampleUserName.
private string _sampleUserName = ""; public string SampleUserName { get { return _sampleUserName; } set { _sampleUserName = value; NotifyPropertyChanged("SampleUserName"); } }
Now our property is ready to be bound to our XAML.
Define Your Data Context
This part can be skipped for brevity, but I wanted to add it to make sure that there is a complete and comprehensive solution here.
Before our XAML can bind to this property, we need to make the ViewModel visible to our XAML. So we will declare our ViewModel as a static object in our App.xaml.cs
private static SampleViewModel _sampleVM { get; set; } public static SampleViewModel SampleVM { get{ if (_sampleVM == null) _sampleVM = new SampleViewModel(); return _sampleVM; } }
Then we can set the data context when our XAML view initializes. In the MyView.xaml.cs (also called the "code behind), we can add to the constructor:
public MyView() { InitializeComponent(); this.DataContext = App.SampleVM; }
This way we could have the same ViewModel driving multiple Views. This is particularly valuable for a Master-Detail scenario in which we have one View dedicated to showing a list of items and another View for editing or looking at an item detail. With this method, we can maintain a single ViewModel and simply update which item has been selected.
XAML Binding
With our viewmodel defined and our notify properties set up, all we need to do is bind to our XAML UI control. Then any updates we make to our property back in the ViewModel will automatically update in the XAML UI.
<TextBox Text="{Binding SampleUserName}" />
And if we wanted changes to the UI to be updated back in our ViewModel, we just set our binding to "TwoWay"
<TextBox Text="{Binding SampleUserName, Mode=TwoWay}" />
Binding, Sample Data, and Design
In addition to helping us build manageable code with a simple model for XAML UI updates, binding allows us to build our app interfaces in a way that is fast and powerful. Instead of run-view-tweak, run-view-tweak, we can explore design options and do most of our design right inside our tooling without running the application. In fact, if you follow the steps here, you can actually build much of the interaction and XAML of an application up before you start building the logic. The result is the opportunity for a workflow that supports design-driven user-focused application creation.
For this, we're going to move away from our SimpleViewModel with its single property and into a real-world example that
focuses on binding with real-world data. To follow along in this example, download this slightly modified version of the LongListSelector Infinite Scroll example for Windows Phone.
Because we're working with sample data, we want to open the project in Blend.
You'll get a dialog box that allows you to name your data source and select a class from which Blend will generate the data.
Blend will do a "best guess" on what data is in there based on the data types. String will default to lorem ipsum sample text, and int will generate a number, an ObservableCollection will result in a generated list of sample objects. All this data will be saved as a XAML resource file in the SampleData folder. To create bindings for these objects, all we would have to do is drag the object from our Data tab to an control in our "Objects and Timeline" tab.
We could go into this file and edit the data to be something that is a little more realistic for our application. In fact, this is exactly what I've done. For this Twitter app, I added some actual tweets from my timeline as sample data. To see this click on the eye icon next to the "resultListBox".
And now we can see the sample data and how it will look in the application.
Here is where it gets really fun: Right-click on the resultListBox and select "Edit Additional Templates -> Edit ItemTemplate -> Edit Current".
This will take you to a XAML DataTemplate where we can define, in real time and against real data, how we want our items to be displayed. We could give our tweet text a height limit and tell it to use ellipses and see that reflected instantly in our design.
<TextBlock Text="{Binding Tweet}" MaxHeight="40" TextTrimming="WordEllipsis" />
As you can see, this is an incredibly powerful way to design and build applications for Windows Phone and it is all made possible by DataB people implement INotifyPropertyChnaged in a viewmodel that only declares observable collections of user-defined classes.
Look at this page - what have you done ...I ove you!
Remove this comment
Remove this threadclose
|
https://channel9.msdn.com/Shows/Inside+Windows+Phone/IWP54--Windows-Phone-Data-Binding-and-the-Magic-of-XAML?format=auto
|
CC-MAIN-2015-32
|
refinedweb
| 1,156
| 51.38
|
In the blog, Redacting Personal Data from Connected Cars Using Amazon Rekognition, we demonstrated how you can redact personal data such as human faces using Amazon Rekognition. Traversing the video, frame by frame, and identifying personal information in each frame takes time. This solution is great for small video clips, where you do not need a near real-time response. However, in some use cases like object detection, real time traffic monitoring, you may need to process this information in near real-time and keep up with the input video stream.
In this blog post, we introduce how to leverage “multiprocessing” to speed up the redaction process and provide a response in near real time. We also compare the process run times using a variety of Amazon SageMaker instances to give users various options to process video using Amazon Rekognition.
For example, the ml.c5.4xlarge instance has 16 vCPUs, so we could theoretically have 16 processes, working in parallel, to process the video stream, which will significantly reduce the processing time. Our test against the sample video shows that we reduce the process run time by a factor of 11x, using the ml.c5.4xlarge instance.
Architecture Overview
Walkthrough: 6 Steps.
3. Additionally an AWS Identity and Access Management (IAM) role created with appropriate permissions is leveraged to provide temporary security credentials required for this program.. We write a function multi_process_video to blur the detected face for each frame and distribute the processing job equally among all available CPUs in the SageMaker instance
6. We run the multi_process function for the input video and write the output video to S3 bucket for further analysis.
Detailed Steps
For the.
Step 2: In this block, we will create a SageMaker notebook.
Notebook instance:
- Notebook instance name: VideoRedaction
Notebook instance class: choose “ml.t3.large” from drop down
Elastic inference: None
Permissions:
- IAM role: Select Create a new role from the drop-down menu. This will open a new screen, click next and the new role will be created. The role name will start with AmazonSageMaker-ExecutionRole-xxxxxxxx.
- Root access: Select Enable
- Assume defaults for the rest, and select 3: Next, we need to provide additional permissions to the new role that you created in Step 2.
- Select the VideoRedaction notebook.
This will open a new screen. Scroll down to the 3 block – “Permissions and encryption” and click on the IAM role ARN link.
This will open a screen where you can attach additional policies. It will already be populated with “AmazonSageMakerFullAccess”
- Select select the blue Create Policy button at the bottom.
Step 3a: Navigate to SageMaker in the console:
- Select “Notebook instances” in the menu on left. This will show your VideoRedaction notebook.
- Select Open Jupyter blue link under Actions. This will open a new tab titled, Jupyter.
Step 3b: In the upper right corner, click on drop down arrow next to “New” and choose conda_tensorflow_p36 as the kernel for your notebook.
Your screen will look at follows:
Install ffmpeg
First, we need to install ffmpeg for multiprocessing video. It’s a free and open-source software project consisting of a large suite of libraries and programs for handling video, audio, and other multimedia files and streams. We use it to concatenate all the subset videos processed by each vCPU and generate the final output.
Install ffmpeg using the following command:
!conda install x264=='1!152.20180717' ffmpeg=4.0.2 -c conda-forge --yes
Import libraries – We import additional libraries to help with multi-processing capability.
import cv2 import os from PIL import ImageFilter import boto3 import io from PIL import Image, ImageDraw, ExifTags, ImageColor import numpy as np from os.path import isfile, join import time import sys import time import subprocess as sp import multiprocessing as mp from os import remove
Step 4: Identify personal. We also show how you can expand the bounding boxes returned by Amazon Rekognition, if required, to blur an enlarged portion of the for faceDetail in response['FaceDetails']: box = faceDetail['BoundingBox'] left = imgWidth * box['Left'] top = imgHeight * box['Top'] width = imgWidth * box['Width'] height = imgHeight * box['Height'] #blur faces inside the enlarged bounding boxes #you can also keep the original bounding boxes x1=left-0.1*width y1=top-0.1*height x2=left+width+0.1*width y2=top+height+0.1*height mask = Image.new('L', image.size, 0) draw = ImageDraw.Draw(mask) draw.rectangle([ (x1,y1), (x2,y2) ], fill=255) blurred = image.filter(ImageFilter.GaussianBlur(blurriness)) image.paste(blurred, mask=mask) image.save return image
Step 5: Redact the face bounding box and distribute the processing among all CPUs
By passing the group_number of the multi_process_video function, you can distribute the video processing job among all available CPUs of the instance equally and therefore largely reduce the process time.
def multi_process_video(group_number): cap = cv2.VideoCapture(input_file) cap.set(cv2.CAP_PROP_POS_FRAMES, frame_jump_unit * group_number) proc_frames = 0 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) out = cv2.VideoWriter( "{}.{}".format(group_number, 'mp4'), cv2.VideoWriter_fourcc(*'MP4V'), fps, (width, height), ) while proc_frames < frame_jump_unit: ret, frame = cap.read() if ret == False: break f=str(group_number)+'_'+str(proc_frames)+'.jpg' cv2.imwrite(f,frame) #Define the blurriness blurriness=20 blurred_img=detect_blur_face_local_file(f,blurriness) blurred_frame=cv2.cvtColor(np.array(blurred_img), cv2.COLOR_BGR2RGB) out.write(blurred_frame) proc_frames += 1 else: print('Group '+str(group_number)+' finished processing!') cap.release() cap.release() out.release() return None
Step 6: Run multi-processing video function and write the redacted video to the output bucket
- Then we multi-process the video and generate the output using multiprocessing function and ffmpeg in python.
- We take a record of each video processed by a CPU in the format of ‘1.mp4’, ‘2.mp4’ … in a file called multiproc_files and then use subprocess to call ffmpeg to concatenate these videos based on these videos’ order in multiproc_files.
- After the final video is generated, we remove all the intermediate results and upload the face-blurred result to a S3 bucket.
start_time = time.time() # Connect to S3 s3_client = boto3.client('s3') # Download S3 video to local. Enter your bucketname and file name below bucket='yourbucketname' file='face1.mp4' s3_client.download_file(bucket, file, './'+file) input_file='face1.mp4' num_processes = mp.cpu_count() cap = cv2.VideoCapture(input_file) frame_jump_unit = cap.get(cv2.CAP_PROP_FRAME_COUNT) // num_processes # Multiprocessing video across all vCPUs p = mp.Pool(num_processes) p.map(multi_process_video, range(num_processes)) # Generate multiproc_files to record the subset videos in the right order multiproc_files = ["{}.{}".format(i, 'mp4') for i in range(num_processes)] with open("multiproc_files.txt", "w") as f: for t in multiproc_files: f.write("file {} \n".format(t)) # Use ffmpeg to concatenate all the subset videos according to multiproc_files local_filename='blurface_multiproc_827.mp4' ffmpeg_command="ffmpeg -f concat -safe 0 -i multiproc_files.txt -c copy " ffmpeg_command += local_filename cmd = sp.Popen(ffmpeg_command, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) cmd.communicate() # Remove all the intermediate results for f in multiproc_files: remove(f) remove("multiproc_files.txt") mydir=os.getcwd() filelist = [ f for f in os.listdir(mydir) if f.endswith(".jpg") ] for f in filelist: os.remove(os.path.join(mydir, f)) # Upload face-blurred video to s3 s3_filename='blurface_multiproc_827.mp4' response = s3_client.upload_file(local_filename, bucket, s3_filename) finish_time = time.time() print( "Total Process Time:",finish_time-start_time,'s')
Output:
Group 13 finished processing!
Group 15 finished processing!
Group 14 finished processing!
Group 12 finished processing!
Group 11 finished processing!
Group 9 finished processing!
Group 10 finished processing!
Group 1 finished processing!
Group 3 finished processing!
Group 4 finished processing!
Group 8 finished processing!
Group 5 finished processing!
Group 2 finished processing!
Group 7 finished processing!
Group 6 finished processing!
Group 0 finished processing!
Total Process Time: 15.709482431411743 s
Using the same instance, we reduce the process time from 168s to 15.7s. As we mentioned, ml.c5.4xlarge has 16 vCPUs and you can even further reduce the process time if you have an instance that has 32 or 64 CPUs.
Note: Choosing the right instance will depend on your requirement for process time and cost. As this result demonstrates, multiprocessing video using Amazon Rekognition is an efficient way to leverage the benefits of Amazon Rekognition state-of-the-art ML model and powerful multi-core Amazon SageMaker instances.
Comparison of Amazon SageMaker Instances in Terms of Process Time and Cost
Here is the comparison table generated when processing a 6.5 seconds video with multiple faces on different SageMaker instances. Following is a video screenshot:
Based on the following table, you learn that instances with 16 vCPU (4xlarge) are better options in terms of faster processing capability, while optimized for cost.
Depending on the size of your input video file and the requirements for real-time processing, you can break the input video file into smaller chunks and then scale instances to process those chunks in parallel. While this example is focused on blurring faces, you can also use AWS Rekognition for other use cases like someone wielding a gun, smoking a cigarette, suggestive content and the like. These and many other moderation activities are all supported by Rekognition content moderation APIs.
Conclusion
In this blog post, we showed how you can leverage multiple cores in large machine learning instances, along with Amazon Rekognition. Doing this can significantly speed up the process of redacting personally identifiable information from videos collected by connected vehicles. The ability to provide near-real-time information unlocks additional value from the video that is ingested. For example, in smart cities, information is collected about the environment, such as road traffic and weather. This data can be visualized in near-real-time to help city management make decisions that can optimize traffic and improve residents’ quality of life.
|
https://awsfeed.com/whats-new/architecture/field-notes-speed-up-redaction-of-connected-car-data-by-multiprocessing-video-footage-with-amazon-rekognition
|
CC-MAIN-2021-17
|
refinedweb
| 1,610
| 50.23
|
Context View
The context node is valid only for XSLT debugging sessions and is a source node corresponding to the XSL expression that is evaluated. It is also called the context of execution. The context node implicitly changes as the processor hits various steps (at the point where XPath expressions are evaluated). This node has the same value as evaluating '.' (dot) XPath expression in XWatch view. The value of the context node is presented as a tree in the Context view. If the view is not displayed, it can be opened by selecting it from the menu.
Figure: Context node view
The context nodes are presented in a tree-like fashion. Nodes from a defined namespace bound to a prefix are displayed using the qualified name. If the namespace is not bound to a prefix, the namespace URI is presented before the node name. The value of the selected attribute or node is displayed in the right side panel. The Context view also presents the current mode of the XSLT processor if this mode differs from the default one.
|
http://www.oxygenxml.com/doc/versions/19.1/ug-editorEclipse/topics/debug-context-node-view.html
|
CC-MAIN-2018-05
|
refinedweb
| 179
| 73.37
|
Steven D'Aprano wrote: > I defined a nested function: > > def foo(): > def bar(): > return "bar" > return "foo " + bar() > > which works. Knowing how Python loves namespaces, I thought I could do > this: > >>>> foo.bar() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > AttributeError: 'function' object has no attribute 'bar' > > but it doesn't work as I expected. > > where do nested functions live? in the local variable of an executing function, just like the variable "bar" in the following function: def foo(): bar = "who am I? where do I live?" (yes, an inner function is *created* every time you execute the outer function. but it's created from prefabricated parts, so that's not a very expensive process). </F>
|
https://mail.python.org/pipermail/python-list/2006-October/397968.html
|
CC-MAIN-2016-36
|
refinedweb
| 119
| 75.5
|
#include <qgsattributeform.h>
Definition at line 32 of file qgsattributeform.h.
Form modes.
Definition at line 39 of file qgsattributeform.h.
Definition at line 48 of file qgsattributeform.cpp.
Definition at line 80 of file qgsattributeform.cpp.
Definition at line 187 of file qgsattributeform.h.
Takes ownership.
Definition at line 108 of file qgsattributeform.cpp.
Notifies about changes of attributes.
Will be emitted before the feature is saved.
Use this signal to perform sanity checks. You can set the parameter ok to false to notify the form that you don't want it to be saved. If you want the form to be saved, leave the parameter untouched.
Call this to change the content of a given attribute.
Will update the editor(s) related to this field.
Definition at line 188 of file qgsattributeform.cpp.
Disconnects the button box (Ok/Cancel) from the accept/resetValues slots If this method is called, you have to create these connections from outside.
Definition at line 102 of file qgsattributeform.cpp.
Returns if the form is currently in editable mode.
Definition at line 113 of file qgsattributeform.cpp.
Intercepts keypress on custom form (escape should not close it)
Reimplemented from QObject.
Definition at line 1159 of file qgsattributeform.cpp.
Definition at line 51 of file qgsattributeform.h.
Is emitted, when a feature is changed or added.
Hides the button box (Ok/Cancel) and enables auto-commit.
Definition at line 86 of file qgsattributeform.cpp.
Returns the layer for which this form is shown.
Definition at line 80 of file qgsattributeform.h.
Returns the current mode of the form.
Definition at line 93 of file qgsattributeform.h.
reload current feature
Definition at line 580 of file qgsattributeform.cpp.
Alias for resetValues()
Definition at line 194 of file qgsattributeform.h.
Sets all values to the values of the current feature.
Definition at line 460 of file qgsattributeform.cpp.
Save all the values from the editors to the layer.
Definition at line 428 of file qgsattributeform.cpp.
Sets the edit command message (Undo) that will be used when the dialog is accepted.
Definition at line 117 of file qgsattributeform.h.
Update all editors to correspond to a different feature.
Definition at line 200 181 of file qgsattributeform.cpp.
Sets the current mode of the form.
Definition at line 118 of file qgsattributeform.cpp.
Sets all feature IDs which are to be edited if the form is in multiedit mode.
Definition at line 1229 of file qgsattributeform.cpp.
Shows the button box (Ok/Cancel) and disables auto-commit.
Definition at line 95 of file qgsattributeform.cpp.
Definition at line 294 of file qgsattributeform.h.
|
http://qgis.org/api/classQgsAttributeForm.html
|
CC-MAIN-2016-18
|
refinedweb
| 436
| 62.34
|
Marshmallow schema basics
In this post we’re going to cover the basics of working with Marshmallow.
Marshmallow is a Python library which enables us to easily sanitize and validate content according to a schema.
Schemas are useful when we want to sift through user provided data en-masse as opposed to dealing with each item individually.
from marshmallow import Schema, fields class _Schema(Schema): class Meta: dateformat = "%Y-%m-%d"
Here we extend the default
Schema class with our own which will output a custom date format.
The
Meta subclass supports plenty of methods to customize our schema,
such as excluding some of the fields or explictly including them.
More can be read in the manual:
help(marshmallow.Schema.Meta).
class Slug(fields.Field): def _serialize(self, value, attr, obj): if value: return str(value).lower().replace(' ', '-')
Above we define a custom field which will serialize its value using the provided function. And we use this field below in our crude blog schema.
class CommentSchema(_Schema): author = fields.Str() body = fields.Str() class PostSchema(_Schema): slug = Slug(required=True) date = fields.DateTime(required=True) title = fields.Str(required=True) body = fields.Str(required=True) tags = fields.List(fields.Str()) comments = fields.List(fields.Nested(CommentSchema()))
The last two are compound fields, with
as it is a list of comment schemas. When referring to another schema instead of a field type
we need to use the
Nested method.
And in a nutshell there we have it. Now all that’s left is to use it to sanitize our blog post through the schema:
schema = PostSchema() post = schema.dump(raw_post).data
Validation was left out from here and we will cover it in another blog post.
|
http://wooptoo.com/blog/marshmallow-schema/
|
CC-MAIN-2018-47
|
refinedweb
| 285
| 68.06
|
(From a novice's point of view)
The other day I was thinking about how a typical "passwd" command works in a LINUX OS. For example, when we type in "passwd", a prompt appears letting us type in our password, and then it saves that password wrapping up with cryptographic algorithms and then saves in /etc/shadow. So I came with a "Password/login emulation" of my own. Initially it saves the username along with their password in a file named mango.txt in the form of "username::password", and next time the same user tries to log in, it asks for the username and password. So I came up with these two scripts.
Script 1: Prompts for a user-name and a password and saves it in a file a called mango.txt.
# Title: username.sh #!/bin/bash # What I'm planning to do here is that, #create a username script which allows a #user to add themselves by puting in #their #names # and their password at the time of #login, it will save itself to a file #with #the username and password. # If username already exists, tells the #user that a user with the same name #exits, else add the new user. # along with a password. The password is # saved in a md5 hash form. exec 2>/dev/null touch mango.txt echo -n "Enter username: " read usame if [ "$usame" == "" ]; then echo -e "Username can not be blank\n" ./username.sh else grep -q $usame mango.txt if [ "$?" == 0 ]; then echo -e "A username with the same name already exists\n" ./username.sh else echo -n "Password: " read -s -p "Password: " passwd while true; do if [ "$passwd" == "" ]; then echo -e "Password can not be blank\n" else echo $usame::$(echo $passwd | md5sum) >> mango.txt echo -e "\nUser $usame added\n" break fi done fi fi
Script 2: If this could be added in "bash.bashrc", then it would run at each terminal startup, and ask for the username and password. If username and password chinkies with that in mango.txt, then it lets the user login, else terminal exits (; Plain passwords are compared in like md5sum form with the mango.txt file passwords.
#Title: login.sh # A simple login bash script #trap interrupts your keyboard if you #press ctrl+z or ctrl+c trap '' INT TSTP read -p "Enter username: " usname grep -q $usname mango.txt if [ "$?" -gt 0 ]; then echo "Username not found" sleep 1 pkill -9 bash #That's a bit too much I guess, but oh well else read -s -p "Password: " password if [ "$password" == "" ]; then echo "Password can not be blank" ./login.sh else #saves the password in md5sum format in tmp.txt echo $password | md5sum > tmp.txt tmp="$(cat tmp.txt)" #if the md5 hashes match, then allow login saying yo cat mango.txt | grep -q $usname::$tmp if [ "$?" == 0 ]; then echo -e "\nyo" #else print login failed else echo -e "\nLogin failed" sleep 1 pkill -9 bash fi fi fi rm tmp.txt # Deletes the tmp file afterwards
I'm pretty sure it's nowhere near how that exactly works in a LINUX system(not to mention the cryptographies like ccrypt and scrypt and different salting mechanisms), but it's as best as I could come up with..perhaps a little nudge to the right direction as to how that actually works would be great from the experts. (:
#endif /* USE_BCRYPT */instead of
#endif /* USE_SHA_CRYPT */:) – Hagen von Eitzen Feb 14 at 23:14
|
https://superuser.com/questions/1525533/how-does-a-passwd-and-adduser-command-actually-work-on-a-linux-os
|
CC-MAIN-2020-16
|
refinedweb
| 580
| 79.8
|
Common issues when running Dapr
I don’t see the Dapr sidecar injected to my pod
There could be several reasons to why a sidecar will not be injected into a pod. First, check your deployment or pod YAML file, and check that you have the following annotations in the right place:
annotations: dapr.io/enabled: "true" dapr.io/app-id: "nodeapp" dapr.io/app-port: "3000"
Sample deployment:
apiVersion: apps/v1 kind: Deployment metadata: name: nodeapp namespace: default labels: app: node spec: replicas: 1 selector: matchLabels: app: node template: metadata: labels: app: node annotations: dapr.io/enabled: "true" dapr.io/app-id: "nodeapp" dapr.io/app-port: "3000" spec: containers: - name: node image: dapriosamples/hello-k8s-node ports: - containerPort: 3000 imagePullPolicy: Always
If your pod spec template is annotated correctly and you still don’t see the sidecar injected, make sure Dapr was deployed to the cluster before your deployment or pod were deployed.
If this is the case, restarting the pods will fix the issue.
If you are deploying Dapr on a private GKE cluster, sidecar injection does not work without extra steps. See Setup a Google Kubernetes Engine cluster.
In order to further diagnose any issue, check the logs of the Dapr sidecar injector:
kubectl logs -l app=dapr-sidecar-injector -n dapr-system
Note: If you installed Dapr to a different namespace, replace dapr-system above with the desired namespace
My pod is in CrashLoopBackoff or another failed state due to the daprd sidecar
If the Dapr sidecar (
daprd) is taking too long to initialize, this might be surfaced as a failing health check by Kubernetes.
If your pod is in a failed state you should check this:
kubectl describe pod <name-of-pod>
You might see a table like the following at the end of the command output:
Normal Created 7m41s (x2 over 8m2s) kubelet, aks-agentpool-12499885-vmss000000 Created container daprd Normal Started 7m41s (x2 over 8m2s) kubelet, aks-agentpool-12499885-vmss000000 Started container daprd Warning Unhealthy 7m28s (x5 over 7m58s) kubelet, aks-agentpool-12499885-vmss000000 Readiness probe failed: Get: dial tcp 10.244.1.10:3500: connect: connection refused Warning Unhealthy 7m25s (x6 over 7m55s) kubelet, aks-agentpool-12499885-vmss000000 Liveness probe failed: Get: dial tcp 10.244.1.10:3500: connect: connection refused Normal Killing 7m25s (x2 over 7m43s) kubelet, aks-agentpool-12499885-vmss000000 Container daprd failed liveness probe, will be restarted Warning BackOff 3m2s (x18 over 6m48s) kubelet, aks-agentpool-12499885-vmss000000 Back-off restarting failed container
The message
Container daprd failed liveness probe, will be restarted indicates at the Dapr sidecar has failed its health checks and will be restarted. The messages
Readiness probe failed: Get: dial tcp 10.244.1.10:3500: connect: connection refused and
Liveness probe failed: Get: dial tcp 10.244.1.10:3500: connect: connection refused show that the health check failed because no connection could be made to the sidecar.
The most common cause of this failure is that a component (such as a state store) is misconfigured and is causing initialization to take too long. When initialization takes a long time, it’s possible that the health check could terminate the sidecar before anything useful is logged by the sidecar.
To diagnose the root cause:
- Significantly increase the liveness probe delay - link
- Set the log level of the sidecar to debug - link
- Watch the logs for meaningful information - link
Remember to configure the liveness check delay and log level back to your desired values after solving the problem.
I am unable to save state or get state
Have you installed an Dapr State store in your cluster?
To check, use kubectl get a list of components:
kubectl get components
If there isn’t a state store component, it means you need to set one up. Visit here for more details.
If everything’s set up correctly, make sure you got the credentials right. Search the Dapr runtime logs and look for any state store errors:
kubectl logs <name-of-pod> daprd
I am unable to publish and receive events
Have you installed an Dapr Message Bus in your cluster?
To check, use kubectl get a list of components:
kubectl get components
If there isn’t a pub/sub component, it means you need to set one up. Visit here for more details.
If everything is set up correctly, make sure you got the credentials right. Search the Dapr runtime logs and look for any pub/sub errors:
kubectl logs <name-of-pod> daprd
The Dapr Operator pod keeps crashing
Check that there’s only one installation of the Dapr Operator in your cluster. Find out by running
kubectl get pods -l app=dapr-operator --all-namespaces
If two pods appear, delete the redundant Dapr installation.
I’m getting 500 Error responses when calling Dapr
This means there are some internal issue inside the Dapr runtime. To diagnose, view the logs of the sidecar:
kubectl logs <name-of-pod> daprd
I’m getting 404 Not Found responses when calling Dapr
This means you’re trying to call an Dapr API endpoint that either doesn’t exist or the URL is malformed. Look at the Dapr API reference here and make sure you’re calling the right endpoint.
I don’t see any incoming events or calls from other services
Have you specified the port your app is listening on?
In Kubernetes, make sure the
dapr.io/app-port annotation is specified:
annotations: dapr.io/enabled: "true" dapr.io/app-id: "nodeapp" dapr.io/app-port: "3000"
If using Dapr Standalone and the Dapr CLI, make sure you pass the
--app-port flag to the
dapr run command.
My Dapr-enabled app isn’t behaving correctly
The first thing to do is inspect the HTTP error code returned from the Dapr API, if any.
If you still can’t find the issue, try enabling
debug log levels for the Dapr runtime. See here how to do so.
You might also want to look at error logs from your own process. If running on Kubernetes, find the pod containing your app, and execute the following:
kubectl logs <pod-name> <name-of-your-container>
If running in Standalone mode, you should see the stderr and stdout outputs from your app displayed in the main console session.
I’m getting timeout/connection errors when running Actors locally
Each Dapr instance reports it’s host address to the placement service. The placement service then distributes a table of nodes and their addresses to all Dapr instances. If that host address is unreachable, you are likely to encounter socket timeout errors or other variants of failing request errors.
Unless the host name has been specified by setting an environment variable named
DAPR_HOST_IP to a reachable, pingable address, Dapr will loop over the network interfaces and select the first non-loopback address it finds.
As described above, in order to tell Dapr what the host name should be used, simply set an environment variable with the name of
DAPR_HOST_IP.
The following example shows how to set the Host IP env var to
127.0.0.1:
Note: for versions <= 0.4.0 use
HOST_IP
export DAPR_HOST_IP=127.0.0.1
None of my components are getting loaded when my application starts. I keep getting “Error component X cannot be found”
This is usually due to one of the following issues
- You may have defined the
NAMESPACEenvironment variable locally or deployed your components into a different namespace in Kubernetes. Check which namespace your app and the components are deployed to. Read scoping components to one or more applications for more information.
- You may have not provided a
--components-pathwith the Dapr
runcommands or not placed your components into the default components folder for your OS. Read define a component for more information.
- You may have a syntax issue in component YAML file. Check your component YAML with the component YAML samples.
Service invocation is failing and my Dapr service is missing an appId (macOS)
Some organizations will implement software that filters out all UPD traffic, which is what mDNS is based on. Mostly commonly, on MacOS,
Microsoft Content Filter is the culprit.
In order for mDNS to function properly, ensure
Micorosft Content Filter is inactive.
- Open a terminal shell.
- Type
mdatp system-extension network-filter disableand hit enter.
- Enter your account password.
Microsoft Content Filter is disabled when the output is “Success”.
Some organizations will re-enable the filter from time to time. If you repeatedly encounter app-id values missing, first check to see if the filter has been re-enabled before doing more extensive troubleshooting.
Admission webhook denied the request
You may encounter an error similar to the one below due to admission webhook having an allowlist for service accounts to create or modify resources.
root:[dapr]$ kubectl run -i --tty --rm debug --image=busybox --restart=Never -- sh Error from server: admission webhook "sidecar-injector.dapr.io" denied the request: service account 'user-xdd5l' not on the list of allowed controller accounts
To resolve this error, you should create a
clusterrolebind for the current user:
kubectl create clusterrolebinding dapr-<name-of-user> --clusterrole=dapr-operator-admin --user <name-of-user>
You can run the below command to get all users in your cluster:
kubectl config get-users
You may learn more about webhooks here.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.
|
https://docs.dapr.io/operations/troubleshooting/common_issues/
|
CC-MAIN-2022-05
|
refinedweb
| 1,581
| 61.16
|
Created on 2018-06-21 16:00 by zezollo, last changed 2018-06-25 10:50 by ncoghlan.
Expected behaviour:
When unset, the locale in use is `C` (as stated in python documentation) and `locale.getlocale()` returns `(None, None)` on Linux with python2.7 or on Windows with python2.7 and python 3.6 (at least):
$ python2
Python 2.7.15 (default, May 1 2018, 20:16:04)
[GCC 7.3.1 20180406] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getlocale()
(None, None)
>>>
Issue:
But when using python3.4+ on Linux, instead of `(None, None)`, `locale.getlocale()` returns the same value as `locale.getdefaultlocale()`:
$ python
Python 3.6.3 (default, Oct 24 2017, 14:48:20)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>>': []}
>>> locale.str(2.5)
'2.5'
Though the locale actually in use is still `C` (as shown above by the output of `locale.localeconv()` and confirmed by the result of `locale.str(2.5)`, which shows a dot as decimal point and not a comma (as expected with `fr_FR.UTF-8`)).
I could observe this confusing behaviour on Linux with python3.4, 3.5, 3.6 and 3.7 (rc1). (Also on FreeBSD with python3.6.1).
A problematic consequence of this behaviour is that it becomes impossible to detect whether the locale has already been set by the user, or not.
I could not find any other similar issue and hope this is not a duplicate.
Can you say on which Linux platform/release you see this behavior and with which Python 3.6.3, i.e. from the platform distributor or built yourself? If I understand your concern correctly, I cannot reproduce that behavior on a current Debian test system using either the Debian-supplied 3.6.6rc1 or with a 3.6.3 built from source. With either LANG unset or set to C (and with no LC* env vars set), I see:
$ unset LC_ALL LC_CTYPE LANG LANGUAGE
$ ./python
Python 3.6.3 (tags/v3.6.3:2c5fed86e0, Jun 22 2018, 16:08:11)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getlocale()
(None, None)
>>> locale.getdefaultlocale()
(None, None)
Note that, as documented, the locale.getdefaultlocale() checks several env vars 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE'. Are you certain that all of those env vars are unset when you run this test?
Sorry, I did not realize that using the word "unset" was completely misleading: I only meant "before any use of locale.setlocale() in python". So I'll rephrase this all, and add details about the python versions and platforms in this message.
So, first, I do not unset the environment variables from the shell before running python.
The only steps required to reproduce this behaviour are: open a terminal and run python3:
Python 3.6.5 (default, May 11 2018, 04:00:52)
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getlocale()
('fr_FR', 'UTF-8') # Wrong: the C locale is actually in use, so (None, None) is expected
Explanation: when python starts, it runs using the C locale, on any platform (Windows, Linux, BSD), any python version (2, 3...), until locale.setlocale() is used to set another locale. This is expected (the doc says so in the getdefaultlocale() paragraph that you mentioned) and can be confirmed by the outputs of locale.localeconv() and locale.str().
So, before any use of locale.setlocale(), locale.getlocale() should return (None, None) (as this value matches the C locale).
This is the case on Windows, python2 and 3, and on Linux and FreeBSD python2.
But on Linux and FreeBSD, python>=3.4 (could not test 3.0<=python<=3.3), locale.getlocale() returns the value deduced from the environment variables instead, like locale.getdefaultlocale() already does, e.g. ('fr_FR', 'UTF-8').
All python versions I tested are from the platform distributors (3.7 only is compiled, but it's an automatic build from an AUR). Here is a more detailed list of the python versions and Linux and BSD platforms where I could observe this behaviour:
- Python 3.4.8, 3.5.5, 3.6.5 and 3.7.0rc1 on an up to date Manjaro (with "LTS" kernel): Linux 4.14.48-2-MANJARO #1 SMP PREEMPT Fri Jun 8 20:41:40 UTC 2018 x86_64 GNU/Linux
- Python 3.6.5 on Xubuntu 18.04 (as virtual box guest) Linux 4.15.0-23-generic #25-Ubuntu SMP Wed May 23 18:02:16 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
- Python 3.4.6 on openSUSE Leap 42.3 (as virtual box guest) Linux 4.4.76-1-default #1 SMP Fri Jul 14 08:48:13 UTC 2017 (9a2885c) x86_64 x86_64 x86_64 GNU/Linux
- Python 3.4.8 and 3.6.1 on FreeBSD 10.4-RELEASE-p8 FreeBSD 10.4-RELEASE-p8 #0: Tue Apr 3 18:40:50 UTC 2018 root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC amd64
Problem of this behaviour on Linux and FreeBSD python>=3.4 is first, of course, that it's not consistent throughout all platforms, and second, that it makes it impossible for a python library to guess, from locale.getlocale() if the user (a python app) has set the locale or not (and is actually still using the C locale). (It is still possible to rely on locale.localeconv() to get correct elements).
Hope this message made things clear now :-)
Thanks for the more detailed explanation. I think you are right that the behavior does not match the documentation but which is to be preferred does not necessarily have an easy answer. Also, this whole area has been undergoing revision, for example, with new features in 3.7. Nick and/or Victor, can you address Nicolas's query?
This statement is no longer correct: "when python starts, it runs using the C locale, on any platform (Windows, Linux, BSD), any python version (2, 3...), until locale.setlocale() is used to set another locale."
The Python 3 text model doesn't work properly in the legacy C locale due to the assumption of ASCII as the preferred text encoding, so we run setlocale(LC_ALL, "") early in the startup sequence in order to switch to something more sensible. In Python 3.7+, we're even more opinionated about that, and explicitly coerce the C locale to a UTF-8 based one if there's one available.
If our docs are still saying otherwise anywhere, then our docs are outdated, and need to be fixed.
I understand that the statement "when python starts, it runs using the C locale..." should not be correct anymore (and the doc should then be updated), but in fact this statement is still true on the systems I tested; only, the output of locale.getlocale() at start is in contradiction with the locale really set in fact.
It looks like the setting done by setlocale(LC_ALL, "") at an early stage is lost at some point (only locale.getlocale() seems to "remember" it).
For instance, my box locale is 'fr_FR.UTF-8', so the decimal point is a comma, but when starting python 3.7:
>>> import locale
>>> locale.str(2.4)
'2.4' # Wrong: if the locale in use is 'fr_FR.UTF-8', then '2,4' is expected instead
>>>': []}
>>>
Note that the output of localeconv() does match C locale, not 'fr_FR.UTF-8'.
Compare this with the outputs of locale.str() and locale.localeconv() when the locale is explicitly set at start:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'LC_CTYPE=fr_FR.utf8;LC_NUMERIC=fr_FR.UTF-8;LC_TIME=fr_FR.UTF-8;LC_COLLATE=fr_FR.utf8;LC_MONETARY=fr_FR.UTF-8;LC_MESSAGES=fr_FR.utf8;LC_PAPER=fr_FR.UTF-8;LC_NAME=fr_FR.UTF-8;LC_ADDRESS=fr_FR.UTF-8;LC_TELEPHONE=fr_FR.UTF-8;LC_MEASUREMENT=fr_FR.UTF-8;LC_IDENTIFICATION=fr_FR.UTF-8'
>>> locale.str(2.4)
'2,4' # Correct!
>>> locale.localeconv() # Output of localeconv() does match 'fr_FR.UTF-8' locale
{'int_curr_symbol': 'EUR ', 'currency_symbol': '€', 'mon_decimal_point': ',', 'mon_thousands_sep': '\u202f', 'mon_grouping': [3, 0], 'positive_sign': '', 'negative_sign': '-', 'int_frac_digits': 2, 'frac_digits': 2, 'p_cs_precedes': 0, 'p_sep_by_space': 1, 'n_cs_precedes': 0, 'n_sep_by_space': 1, 'p_sign_posn': 1, 'n_sign_posn': 1, 'decimal_point': ',', 'thousands_sep': '\u202f', 'grouping': [3, 0]}
>>>
Maybe the title of this issue should be turned to "at start, the C locale is in use in spite of locale.getlocale()'s output (python3 on linux)"?
As to the behaviour on Windows, I guess this is another topic (locales belonging to another world on Windows)... but it may be interesting to note that it complies with the current documentation: at start python 3.6 also uses the C locale, and the output of locale.getlocale() is consistent with that. Here is a test on Windows 10:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
>>> import locale
>>> locale.getlocale()
(None, None)
>>> locale.localeconv()
{'decimal_point': '.', 'thousands_sep': '', 'grouping': [], }
>>> locale.str(2.4)
'2.4'
>>> locale.getdefaultlocale()
('fr_FR', 'cp1252')
When testing this issue, I found a bug in Python :-(
I opened bpo-33954: float.__format__('n') fails with _PyUnicode_CheckConsistency assertion error.
Ah, part of the confusion is that I misremembered the command we run implicitly during startup - it's only `setlocale(LC_CTYPE, "")`, not `setlocale(LC_ALL, "")`.
However, the default category for `locale.getlocale()` is `LC_CTYPE`, so it reports the text encoding locale configured during startup, not the C level default.
The difference on Windows is expected - the startup code that implicitly runs `setlocale(LC_CTYPE, "")` doesn't get compiled in there.
So I think we have a few different potential ways of viewing this bug report:
1. As a docs issue, where we advise users to run `locale.getlocale(locale.LC_MESSAGES)` to find out whether or not a specific locale really has been configured (vs the interpreter's default text encoding change that runs implicitly on startup)
2. As a defaults change for 3.8+, where we switch `locale.getlocale()` over to checking `locale.LC_MESSAGES` instead of `locale.LC_CTYPES`, since the interpreter always sets the latter on startup, so it doesn't convey much useful information.
3. As (1) for maintenance releases, and as (2) for 3.8+
|
https://bugs.python.org/issue33934
|
CC-MAIN-2022-05
|
refinedweb
| 1,710
| 60.21
|
Interest rates can be thought of as the price of borrowing to purchase capital (financial resources). It follows, then, that firms should be able to use this price of capital to determine whether a particular project is worth pursuing. The logic is simple: a project is worth pursuing if it provides a higher return (gains on an investment) than simply putting money in the bank. (This is a slight oversimplification but is helpful to consider.) The present value formula provides exactly this information, even when payments and costs are at different points in the future. Present value (PV) is the value from today's perspective of a sequence of future costs and payments.First, note that if money is saved, it earns interest and is worth more in the future. Therefore, present value (PV, the value today) and future value (FV, the value periods in the future) are related.
As the formula shows, present values decrease when interest rates increase, and vice versa. If interest rates are high, a saver would have to put aside less to make the same amount of money as when the interest rates are low. This makes sense because, if the return on saving is higher, then alternative projects look less attractive from today's perspective. The present value formula also explains why the demand for loanable funds slopes downward: at higher interest rates, fewer investment projects look attractive from a present value standpoint, so the quantity of loanable funds demanded is lower.
|
https://www.coursehero.com/sg/microeconomics/the-present-value-formula/
|
CC-MAIN-2021-21
|
refinedweb
| 248
| 59.23
|
On Tue, Aug 14, 2012 at 3:13 PM, Charles R Harris <charlesr.harris at gmail.com> wrote: > > > On Tue, Aug 14, 2012 at 7:47 AM, Aron Ahmadia <aron at ahmadia.net> wrote: >> >> Hi all, >> >> Installing numpy 1.6.2 against a Python interpreter built with the >> --without threads currently fails due to missing references to >> PyGILState_Ensure and PyGILState_Release. The references appear to be >> coming from the following code in nditer.c.src: >> >> NPY_NO_EXPORT void >> NpyIter_DebugPrint(NpyIter *iter) >> { >> // <snip> >> PyGILState_STATE gilstate = PyGILState_Ensure(); >> // <snip> >> PyGILState_Release(gilstate); >> } >> >> Since this is debugging code, I'm guessing it doesn't get called very >> frequently, and I could probably just #ifdef it out or use the NPY macros >> for grabbing the GIL for a non-threaded build: (NPY_ALLOW_C_API and >> NPY_DISABLE_C_API), but I don't understand why it's grabbing the GIL in the >> first place. Where is it calling into the interpreter? Does it need the >> GIL for something else? I'm hesitant to touch this code and issue a pull >> request until I understand what it's trying to do. >> >> Heading on over to the master branch at numpy/numpy, I'm starting to >> notice more unprotected PyGILState references creeping into the development >> code. Even the Python developers seem to think that nobody is using >> --without-threaded, so I'm not going to make a strong case for being more >> careful, but I do want to point it out in case you want to keep the numpy >> sources correct for this case. >> > > Some. > > #ifdef WITH_THREAD > PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void); > #endif > > Could you give that a shot? TIA, The NPY_*_THREADS macros appear to already check for WITH_THREAD automatically. I think we'd be happy to apply a patch that cleans up numpy's direct PyGIL_* calls to use the NPY_*_THREADS macros instead. -n
|
https://mail.python.org/pipermail/numpy-discussion/2012-August/063631.html
|
CC-MAIN-2021-39
|
refinedweb
| 301
| 69.92
|
Code Patterns & Style Guides
Living Style Guide documentation on the web is a difficult problem, gaining a lot of attention in the last few years. Let’s take an in-depth look at one way to store patterns directly in Sass, and generate documentation automatically.
I’ve often been asked how we sell style guides to our clients. The short answer is: we don’t. Our clients want to put usable features in front of real users on a tight schedule. Style guides aren’t the product, they’re part of the process.
Style guides are necessary, but keeping them alive can be difficult and time-consuming. We have to find ways to integrate documentation into the daily workflow, or it will get lost in the scramble for bigger and better features.
As Carl likes to say: un-tested code is legacy code – even if you wrote it an hour ago.
As I like to say: if you don’t document something, it doesn’t exist.
We’ve been struggling with these problems for a long time, and slowly developing a set of tools to help us manage our patterns in code, and document the results as we go. We’re not done, but we’ve learned a lot, and I’d like to show you what we have so far.
Starting Abstract
The first style patterns we add to any new project (including this OddSite design) are color palettes, fonts, and a typographic scale. These are what I call “abstract” patterns – conceptual rules that exist before any element is ever styled on the page.
My first goal is to make these patterns tangible in our code, so they “exist” somehow outside our own imaginations. Our living style guide (which will include colors, fonts, and sizes) must be based on real and meaningful code, or it’s nothing but theory.
Grouping Variables into Maps
Lucky for us, CSS pre-processors like Sass and Less were invented to solve this problem. It’s common to store abstract patterns in Sass variables. Here are some example variables from Bootstrap-Sass, where they define nearly 400 variables in a single file:
// brand colors: $brand-primary: darken(#428bca, 6.5%) !default; // #337ab7 $brand-success: #5cb85c !default; $brand-info: #5bc0de !default; $brand-warning: #f0ad4e !default; $brand-danger: #d9534f !default; // applied colors: $link-color: $brand-primary !default; $link-hover-color: darken($link-color, 15%) !default; // font stacks: $font-family-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif !default; $font-family-serif: Georgia, "Times New Roman", Times, serif !default; // font sizes: $font-size-base: 14px !default; $font-size-large: ceil(($font-size-base * 1.25)) !default; // ~18px $font-size-small: ceil(($font-size-base * 0.85)) !default; // ~12px // spacing sizes: $padding-base-vertical: 6px !default; $padding-base-horizontal: 12px !default;
There’s nothing wrong about that approach, and it’s certainly not unique to Bootstrap. This is what variables are designed for, and patterns defined this way are easy to access without any help from a toolkit.
What’s missing is an explicit sense
of the patterns developing here:
brand-colors, link-colors, fonts, etc.
Variables are only related in implicit ways,
by giving them similar names.
We assume that
$brand-primary,
$brand-success, and
$brand-info
are part of the same pattern
because they look similar –
but that implicit relationship
relies on naming conventions,
code proximity,
and human interpretation.
Sass has no way of understanding
these relationships,
or automating style guides from them.
To address those issues,
we group all our common settings
into a few map variables.
If you haven’t used Sass Maps,
they are a variable type
similar to arrays, dictionaries, or objects
in other languages –
a set of
key: value pairs
contained in a single variable.
Converting the brand-colors above might look something like this:
$brand-colors: ( 'primary': darken(#428bca, 6.5%), 'success': #5cb85c, 'info': #5bc0de, 'warning': #f0ad4e, 'danger': #d9534f, ) !default;
Now the brand-colors are grouped explicitly, clear to both humans and compilers, with less clutter in the global namespace.
Other Map Advantages
Maps provide other advantages over variables, especially when you want to make programmatic adjustments. In fact, maps were added to Sass to replace variable-name interpolation. New variables can’t be generated in Sass, but new map keys can. The following code attempts to create and save lighter and darker versions of our primary brand color. This won’t work, using variables:
@for each $adjustment in ('lighten', 'darken') { $new-color: call($adjustment, $brand-primary, 10%); // There is no Sass syntax for this… $brand-primary-#{$adjustment}: $new-color; }
But it does work, using map keys:
@for each $adjustment in ('lighten', 'darken') { $new-color: call($adjustment, $brand-primary, 10%); $new-color-map: ('primary-#{$adjustment}': $new-color); $brand-colors: map-merge($brand-colors, $new-color-map); }
The same is true with accessing variable names and map keys programmatically. Using variables, it fails:
@for each $header in ('h1', 'h2', 'h3') { #{$header} { @if variable-exists('font-size-#{$header}') { // There is no Sass syntax for this… font-size: $font-size-#{$header}; } } }
Again, it works great with a map key:
@for each $header in ('h1', 'h2', 'h3') { #{$header} { @if map-has-key($text-sizes, $header) { font-size: map-get($text-sizes, $header); } } }
That may not be a common use-case, but it can come in handy for automating repetitive patterns. More important to OddBird’s daily use, we can also automate some basic style guides with very little effort – looping through the maps to get all the data we need. We’ll get to that later.
The Map Problem
Of course, no solution is perfect, and maps come with their own problems. Some are simple text-editor issues, like the ability for most language-helpers to autocomplete variable names, but not map keys. That’s a minor frustration, but there’s another map issue that can really ruin your entire day:
Sass variables can easily reference other variables –
e.g
$blue-gray: desaturate($blue, 20%); –
but map values cannot reference other values in the same map.
$colors: ( 'blue': #339, 'blue-gray': desaturate(map-get($colors, blue), 20%), ); // SASS ERROR: Undefined variable: "$colors".
That’s ugly, and it doesn’t work. At the point where we are calling the map, it hasn’t yet been defined. Technically, we could only reference values from previously-defined maps, and build our patterns that way – but that gets even uglier:
$colors: ( 'blue': #339, ); $colors: map-merge($colors, ( 'blue-gray': desaturate(map-get($colors, blue), 20%), ));
What’s the point of grouping all your values in a single variable, if you have to define it over and over, one small piece at a time?
Lucky for you, there’s nothing I love more than over-engineering Sass tools…
A Functional Solution
Clearly we have to make some changes to our map. Instead of referencing and manipulating values directly, we use an invented syntax to define what references and manipulations should happen:
// Define first… $colors: ( 'blue': #339, 'blue-gray': 'blue' ('desaturate': 20%), );
Our syntax has two parts: a base color – which can be any color-value, or another key in the map – and an optional map of adjustments, including function names, and additional arguments:
$color: ( <name>: <base-color> (<function>: <arguments...>, …), 'blue-gray': 'blue' ('desaturate': 20%, 'lighten': 15%), );
That’s hopefully human-readable, and loosely based on functional programming standards, but it will require processing in order to work. We need some functions that know how to parse our syntax, and return CSS-ready results.
At OddBird we have three abstract
“Sass Accoutrement” toolkits
(color, scale, and type)
each containing a core function
to compile our maps.
In the color module,
that function is simply called
color(),
and works like this:
// Calculate on-the-fly… $result: color('blue-gray');
While
'blue' ('desaturate': 20%)
doesn’t mean anything special to Sass,
the
color() function understands
how to parse that syntax,
and make the necessary conversions.
First it has to look up the reference color
(
#339 above),
and then call the adjustment function mentioned
(
desaturate),
passing in the base color
and the given argument (
20%).
You can play with it yourself in this CodePen demo:
See the Pen Accoutrement Color Example by Miriam Suzanne (@mirisuzanne) on CodePen.
As you can see,
that demo
also generates a rough style guide
on-the-fly,
with nothing but Sass
and empty
div elements –
a pretty good proof-of-concept
for the more robust
style guide generator
we’ll develop later.
The Theming Option
There’s an interesting side effect of our solution that I’ve never really dug into before now. While variable relationships are static, calculated at the point they are defined, our relationships remain dynamic until they are called.
Let’s start with a few colors defined as variables, with one color based on the other color:
$brand: #339; $brand-light: lighten($brand, 10%); // #4040bf
If I override the value of
$brand
later in the document,
that will have no effect
on the value of
$brand-light:
$brand: #339; $brand-light: lighten($brand, 10%); // #4040bf $brand: #933; .static-variables { background: $brand-light; // #4040bf – still the same… }
The lighten-10% relationship is lost, unless we re-define both colors at once. If we do the same thing using Sass maps, we get a different result:
$colors: ( 'brand': #339, 'brand-light': 'brand' ('lighten': 10%), // #4040bf ); $colors: map-merge($colors, ('brand': #933)); .dynamic-values { background: color('brand-light'); // #bf4040 – it changed! }
Keeping that relationship dynamic could allow us to handle theming in new ways. Change the base color on-the-fly, and watch the results trickle down.
Trade-Offs
We use the same approach for colors, sizes, and fonts – with additional helpers to manage contrast-ratios, modular-scales (when needed), robust webfont importing, and (most importantly) automated style guides.
Since the abstract site configuration is stored in a meaningful way, we can export all that data to JSON and pass it along to a tool like SassDoc for display. We’re working on a SassDoc theme of our own, called Herman, which knows how to display color-palettes, type scales, and font specimens.
You can look at our
OddSite config files on Github,
and see the generated docs live.
Herman is far from complete,
but it’s already been useful
in generating docs as we go –
with little extra effort.
Any time a new color is added to the map,
it is automatically available to our
color() function,
and simultaneously appears in the style guide.
The pattern is documented directly in the code.
That meaningful structure provides a lot of power, but comes with trade-offs. We have to invent our own syntax, which raises the learning curve for new developers, and eliminates some text-editor autocomplete gains. We’ve added dependencies to the project, making it also more difficult to test ideas in sandbox systems like Codepen and Sassmeister.
Are those trade-offs worth it? That depends on your needs, and the needs of the project. No solution is one-size fits all. We hope some of these issues can be resolved in our toolkit – like adding a hosted sandbox to our style guides – but your milage will almost certainly vary.
How have you handled site configuration and documentation in your projects? How would you improve on our map solution? We’d love to hear your thoughts on Twitter, on our public Slack channel, or through our handy contact form. Happy coding!
>
|
https://www.oddbird.net/2017/03/07/pattern-making/
|
CC-MAIN-2020-10
|
refinedweb
| 1,896
| 52.8
|
Anyone familiar with C++ knows at least one way of generating pseudo-random numbers and that is srand( time(0) ) coupled with one or more consecutive calls to rand() % someValue. In this tutorial, however, you will see a newer way to deal with pseudo-random numbers in C++11.
Things You Need To Know Before Starting
- What pseudo-random numbers are.
- General familiarity with STL.
- C++11 uniform initialization.
Also, don't forget to add the C++11 flag for compiler.
The Old Way
To generate a sequence of random numbers, the one method that everybody knows about is to use srand(unsigned int seed) and then rand(). srand is used to initialize the pseudo-random number generator with a seed value. After that, each call to rand() returns the next pseudo-random number. Lets try it out:
#include <iostream> #include <vector> #include <cstdlib> //for rand() and srand() using namespace std; int main() { cout<<"*** Testing Random Number Generation - The Old Way ***"<<endl<<endl; cout<<"Seeding the number generator... "; srand(5); //seed the random number generator with 5 cout<<"Done!"<<endl; cout<<"Generating 10 random integers in the range [0, 10)... "; vector<int> randVector; //to store the random numbers for(int i=0; i<10; ++i) { randVector.push_back( rand()%10 ); } cout<<"Done!"<<endl; cout<<"Here are the numbers: "; for(const int& number: randVector) { cout<<" "<<number; } cout<<endl; return 0; }
It's a pretty expressive program. Compile and run it to see what the output is.
The important part of the code is:
srand(5); //seed the random number generator with 5 randVector.push_back( rand()%10 );
srand(5) initializes the pseudo-random number generator's formula with a seed value, and rand() retrieves the next random number in the sequence. The generated number by rand() is between 0 and RAND_MAX which is implementation-dependent but guaranteed to be at least 32767. (reference).
Try to re-run the program a few times. Don't get surprised by the results! No matter how many times you run the program, the generated numbers are going to be the same sequence. Not much random, right?
The reason behind such behavior is in the call to srand and the argument you pass to it as seed. Because the number I have passed to it is constant, the generated sequence of numbers is going to be same every time the program is run.
In order to fix this issue, the seed passed to srand should be different each time the program is run. The seed value can be generated based on different conditions. One of the easiest ways to generate a seed is to use the current time:
srand( time(nullptr) ); //requires the <ctime> header randVector.push_back( rand()%10 );
Basically, time(nullptr) returns the number of seconds passed since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp).
After this modification, each time the program is run, the seed value changes and therefore, the generated random number sequence is going to be different. Although, problems would arise if you call your program from another executable to generate some output and each run only takes a fraction of a second. In such case, at least a few runs of the program could generate the same sequence due to the same seed value. For such rare cases, you could use milliseconds instead of seconds.
For a reference on the time function, check here.
One drawback when using the remainder operator is that it doesn't generate a uniform distribution due to lower numbers being more likely to be generated.
The Newer Way
Some people argue that the srand and rand approach is evil. I believe the result can be good enough if you are not using it for cryptography or other cases that require a top quality pseudo-random number generation. However, with the new tools available in the <random> header, there is no good reason for using srand and rand anymore.
In order to generate pseudo-random numbers using the facilities in the <random> header, you need to use the following tools:
- Seed generator - to generate seeds for feeding the generator engine. std::random_device is provided which is actually an integer random number generator itself but it is generally used to seed a generator and should not be used on it's own for generating numbers. For more information, check here.
- Random number generator - generates pseudo-random numbers. There are different engines and generators available such as std::mt19937, std::mt19937_64 (both of which use the mersenne_twister_engine with different parameters). There is also a std::default_random_engine which is implementation defined.
- Random number distribution - processes the generator's output to fit different statistical probability functions. If you are not into statistical distributions much, chances are that you will be using std::uniform_int_distribution<> and std::uniform_real_distribution<> most of the time.
For more information on the available engines or distributions, check here.
Don't get confused by all the new classes and different distributions. Let's see them in action:
#include <iostream> #include <vector> #include <random> using namespace std; int main() { cout<<"*** Testing Random Number Generation - The New Way ***"<<endl<<endl; cout<<"Generating 10 random integers in the range [0, 10)... "; vector<int> randVector; //to store the random numbers random_device rd; //seed generator mt19937_64 generator{rd()}; //generator initialized with seed from rd uniform_int_distribution<> dist{0, 9}; //the range is inclusive, so this produces numbers in range [0, 10), same as before for(int i=0; i<10; ++i) { randVector.push_back( dist(generator) ); } cout<<"Done!"<<endl; cout<<"Here are the numbers: "; for(const int& number: randVector) { cout<<" "<<number; } cout<<endl; return 0; }
Instead of calling rand(), dist(generator) is called and by doing so, the distribution object calls generator.operator() to generate the next number according to the distribution.
Conclusion
The addition of different generators and distributions to the standard library is a big improvement. If you consider the quality of generated pseudo-random numbers in a small test application, you may not see a significant difference between the two approaches. The problem with rand() and srand( time(nullptr) )(aside from the popular use of %) is not that they are evil. The thing is, when (better) new tools are available, there is no reason to use deprecated alternatives.
|
http://cdn.dreamincode.net/forums/topic/379290-generating-random-numbers-the-c-way/
|
CC-MAIN-2018-05
|
refinedweb
| 1,039
| 54.63
|
A simple example of JNI
By Ye Julia Li on Nov 28, 2007
Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the JVM into native applications. Simply, it is a Java technology with which a Java application can call a method written with such as C, C++ and assembly.
Adopting JNI is very simple. You need two components -- a Java program, and a native library. The native library is written in other languages and compiled on corresonding platforms.
A function defined in the native library should be declared in Java code as a 'native' function. And the native library needs to be load in Java code with the System.loadLibrary method. The natvie function could be referced by other regular functions in the Java code.
Following is an example of the Java Code.
JNIFoo.java
===========
public class JNIFoo {
public native String nativeFoo();
static {
System.loadLibrary("foo");
}
public void print () {
String str = nativeFoo();
System.out.println(str);
}
public static void main(String[] args) {
(new JNIFoo()).print();
return;
}
}
# javac JNIFoo.java
# javah -jni JNIFoo
A file named as JNIFoo.h is created by running the above two commands. A function of 'JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo (JNIEnv \*, jobject)' is in the JNIFoo.h file. The function must be implemented in a source code file (e.g. a C file), and it is the actually entry to do what the funtion of natvieFoo() in Java code do.
foo.c
======
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jni.h>
#include "JNIFoo.h"
JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo (JNIEnv \*env, jobject obj)
{
int i;
int ds_ret;
char\* newstring;
jstring ret = 0;
newstring = (char\*)malloc(30);
if(newstring == NULL)
{
return ret;
}
memset(newstring, 0, 30);
newstring = "foo: Test program of JNI.\\n";
ret = (\*env)->NewStringUTF(env, newstring);
free(newstring);
return ret;
}
JNI libraries are named with the library name used in the System.loadLibrary method of your Java code with a prefix and a suffix. On different OS, the prefix and suffix might be different.
On Solaris OS, it is prefixed by 'lib' and suffixed with '.so'
# cc -Kpic -G -o libfoo.so -I/usr/java/include -I/usr/java/include/solaris foo.c -z text
On Linux OS, it is prefixed by 'lib' and suffixed with '.so'.
# gcc -shared -fpic -o libfoo.so -I/usr/java/include -I/usr/java/include/linux foo.c
On Windows OS, it is prefixed by nothing and suffixed with '.dll'.
It could be compiled with Visual Studio automatically and create a file named as foo.dll.
On Mac OS, it is prefixed by 'lib' and suffixed with '.jnilib'.
# gcc -dynamiclib -o libfoo.jnilib -I/System/Library/Frameworks/JavaVM.framework/Headers foo.c -framework JavaVM
To run the JNI program locally, the following command is fine:
# java -Djava.library.path=<path_of_native_lib> JNIFoo
|
https://blogs.oracle.com/moonocean/tags/junior
|
CC-MAIN-2016-22
|
refinedweb
| 471
| 60.41
|
Up to [cvs.NetBSD.org] / pkgsrc / www / davical
Request diff between arbitrary revisions
Default branch: MAIN
Revision 1.36 / (download) - annotate - [select for diffs], Fri May 10 12:25:04 2019 UTC (9 days, 1 hour ago) by hauke
Branch: MAIN
CVS Tags: HEAD
Changes since 1.35: +7 -7 lines
Diff to previous 1.35 (colored) to selected 1.4 (colored)
Update www/davical to v1.1.8 Minor changes and bug fixes - upstream's changelog is a bit unorganized. Update the upgrade information in MESSAGES Work in pkglint recommendations
Revision 1.35 / (download) - annotate - [select for diffs], Wed Aug 22 09:47:24 2018 UTC (8
Changes since 1.34: +2 -1 lines
Diff to previous 1.34 (colored) to selected 1.4 (colored)
Recursive bump for perl5-5.28.0) to selected 1.4
Revision 1.33 / (download) - annotate - [select for diffs], Thu Dec 7 13:00:33 2017 UTC (17 months, 1 week ago) by hauke
Branch: MAIN
CVS Tags: pkgsrc-2018Q1-base, pkgsrc-2018Q1, pkgsrc-2017Q4-base, pkgsrc-2017Q4
Changes since 1.32: +3 -3 lines
Diff to previous 1.32 (colored) to selected 1.4 (colored)
www/davical update to 1.1.6 From upstream's changelog: >From the Release Notes ():) Database Upgrade ================ * Run dba/upgrade-davical-database to get Postgresql-10-compatible functions Upgrades of Other Software ========================== * AWL 0.58 is required for best PHP7 compatibility
Revision 1.32 / (download) - annotate - [select for diffs], Sun Sep 3 08:53:16 2017 UTC (20 months, 2 weeks ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2017Q3-base, pkgsrc-2017Q3, pkgsrc-
Changes since 1.31: +2 -3 lines
Diff to previous 1.31 (colored) to selected 1.4 (colored)
Follow some redirects.
Revision 1.31 / (download) - annotate - [select for diffs], Sun Jun 18 15:27:24 2017 UTC (23 months ago) by taca
Branch: MAIN
CVS Tags: pkgsrc-2017Q2-base, pkgsrc-2017Q2
Changes since 1.30: +12 -10 lines
Diff to previous 1.30 (colored) to selected 1.4 (colored)
Update davical to 1.1.5. Changes are too many to write here, please refer ChangeLog.
Revision 1.30 / (download) - annotate - [select for diffs], Sun Mar 12 07:20:51 2017 UTC (2 years, 2 months ago) by maya
Branch: MAIN
CVS Tags: pkgsrc-2017Q1-base, pkgsrc-2017Q1
Changes since 1.29: +2 -2 lines
Diff to previous 1.29 (colored) to selected 1.4 (colored)
pkgrevision bump for changed apache default. bumping any package depending on a pkg with APACHE_PKG_PREFIX but without APACHE_PKG_PREFIX in its PKGNAME.
Revision 1.29 / (download) - annotate - [select for diffs], Sun Oct 9 21:42:03 2016 UTC (2 years, 7 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2016Q4-base, pkgsrc-2016Q4
Changes since 1.28: +2 -2 lines
Diff to previous 1.28 (colored) to selected 1.4 (colored)
Recursive bump for all users of pgsql now that the default is 95.
Revision 1.28 / (download) - annotate - [select for diffs], Sat Jul 9 06:39:11 2016 UTC (2 years, 10 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2016Q3-base, pkgsrc-2016Q3
Changes since 1.27: +2 -2 lines
Diff to previous 1.27 (colored) to selected 1.4 (colored)
Bump PKGREVISION for perl-5.24.0 for everything mentioning perl.
Revision 1.27 / (download) - annotate - [select for diffs], Mon Jun 6 14:26:01 2016 UTC (2 years, 11 months ago) by hauke
Branch: MAIN
CVS Tags: pkgsrc-2016Q2-base, pkgsrc-2016Q2
Changes since 1.26: +3 -3 lines
Diff to previous 1.26 (colored) to selected 1.4 (colored)
Update dependency to require a newer version of devel/php-libawl. This fixes PR pkg/51252.
Revision 1.26 / (download) - annotate - [select for diffs], Fri Nov 20 12:48:36 2015 UTC (3 years, 5 months ago) by hauke
Branch: MAIN
CVS Tags: pkgsrc-2016Q1-base, pkgsrc-2016Q1, pkgsrc-2015Q4-base, pkgsrc-2015Q4
Changes since 1.25: +4 -2 lines
Diff to previous 1.25 (colored) to selected 1.4 (colored)
The dba/update-davical-database script needs two more perl modules.
Revision 1.25 / (download) - annotate - [select for diffs], Mon Nov 16 13:22:47 2015 UTC (3 years, 6 months ago) by jperkin
Branch: MAIN
Changes since 1.24: +1 -3 lines
Diff to previous 1.24 (colored) to selected 1.4 (colored)
Remove FETCH_USING completely, it is not a package-settable variable.
Revision 1.24 / (download) - annotate - [select for diffs], Mon Nov 16 13:13:30 2015 UTC (3 years, 6 months ago) by hauke
Branch: MAIN
Changes since 1.23: +2 -3 lines
Diff to previous 1.23 (colored) to selected 1.4 (colored)
mk/fetch/fetch.mk sports --no-check-certificate in _FETCH_BEFORE_ARGS.wget, already.
Revision 1.23 / (download) - annotate - [select for diffs], Fri Nov 13 12:13:13 2015 UTC (3 years, 6 months ago) by hauke
Branch: MAIN
Changes since 1.22: +12 -5 lines
Diff to previous 1.22 (colored) to selected 1.4 (colored)
Updating davical to 1.1.3.1 Updating MASTER_SITES From the ChangeLog: 2013-03-25 Christoph Anton Mitterer <mail@christoph.anton.mitterer.name> * In places where the CGI variable REMOTE_USER is read, support alternatively REDIRECT_REMOTE_USER, which is used by the Apache HTTPD Server instead, when a redirect was used. * Removed debian/README.Debian which did not contain any useful information. 2013-03-23 Christoph Anton Mitterer <mail@christoph.anton.mitterer.name> * Handle the content of the CGI AUTH_TYPE variable case-insensitively as defined by RFC 3875 Section 4.1.1. 2013-03-21 Christoph Anton Mitterer <mail@christoph.anton.mitterer.name> * Changed the pathnames of the debug files to be a bit more FHS compliant. 2013-03-20 Christoph Anton Mitterer <mail@christoph.anton.mitterer.name> * Changed the end-of-line encodings of all non-Windows-related and non-autogenerated text files to use UNIX LF (lots of them had mixed LF/CRLF). * HTML escape the remotely retrieved version string printed to the HTML in order to prevent and attacks (if this would have been possible at all in 12 characters). * Updated all addresses of the canonical git upstream repository and the issue tracker to the new ones. 2013-03-06 Andrew McMillan <andrew@morphoss.com> * Fix capitalisation of 'plpgsql' & 'sql' for Postgres 9.2. (debbug #702403) 2013-02-16 Andrew McMillan <andrew@morphoss.com> * Content-Type header should be 'charset' not 'encoding'. 2012-09-20 Andrew McMillan <andrew@morphoss.com> * When we get here it is a Bad Request, not a Server Error. * Quick workaround for iOS6 supported-calendar-component-set issue. Adds a $c->default_calendar_components array of (VEVENT,VTODO,...) * Workaround client software with imperfect add-member implementations. 2012-09-10 Andrew McMillan <andrew@morphoss.com> * Fix unassigned variable. * Avoid unassigned variable warning. * Fix UID handling. * Fix debugging to error log. 2012-08-09 Andrew McMillan <andrew@morphoss.com> * Ensure test responses are displayed in their unprocessed form. * Some debugging messages. 2012-07-31 Andrew McMillan <andrew@morphoss.com> * Replace deprecated split() with explode() 2012-05-28 Andrew McMillan <andrew@morphoss.com> * First cut at iMIP implementation. Still working on this. 2012-07-30 Andrew McMillan <andrew@morphoss.com> * Fix SQL fieldname. 2012-07-29 Andrew McMillan <andrew@morphoss.com> * Sometimes we want to retrieve the sync-token as a result of a change we just made. This allows a (default true) flag to indicate whether it's OK to use a previously cached value. * On Apple devices these can sometimes appear in the Apple namespace. Odd. * Let the VCalendar class handle how to get the UID from the calendar. 2012-07-25 Andrew McMillan <andrew@morphoss.com> * Remove old redundant constructor. 2012-07-13 Andrew McMillan <andrew@morphoss.com> * Add workaround for Apple's POST add-member trainwreck. * We might not have a $request calling this so use the object's path instead. * Testing for dead property XML which is a set of prop. * supported-calendar-component-set uses dead properties too... * Don't just return the first element in a dead property - there might be multiple!
Revision 1.22 / (download) - annotate - [select for diffs], Fri Jun 12 10:51:49 2015 UTC (3 years, 11 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2015Q3-base, pkgsrc-2015Q3, pkgsrc-2015Q2-base, pkgsrc-2015Q2
Changes since 1.21: +2 -2 lines
Diff to previous 1.21 (colored) to selected 1.4 (colored)
Recursive PKGREVISION bump for all packages mentioning 'perl', having a PKGNAME of p5-*, or depending such a package, for perl-5.22.0.
Revision 1.21 / (download) - annotate - [select for diffs], Tue Jun 10 14:21:37 2014 UTC (4 years, 11 months ago) by joerg.20: +2 -2 lines
Diff to previous 1.20 (colored) to selected 1.4 (colored)
Bump PostgreSQL default version to 9.3.
Revision 1.20 / (download) - annotate - [select for diffs], Thu May 29 23:37:57 2014 UTC (4 years, 11 months ago) by wiz
Branch: MAIN
Changes since 1.19: +2 -2 lines
Diff to previous 1.19 (colored) to selected 1.19 / (download) - annotate - [select for diffs], Fri May 31 12:42:32 2013 UTC (5 years, 11.18: +2 -2 lines
Diff to previous 1.18 (colored) to selected 1.4 (colored)
Bump all packages for perl-5.18, that a) refer 'perl' in their Makefile, or b) have a directory name of p5-*, or c) have any dependency on any p5-* package Like last time, where this caused no complaints.
Revision 1.18 / (download) - annotate - [select for diffs], Sat Mar 16 07:21:23 2013 UTC (6 years, 2 months ago) by obache
Branch: MAIN
CVS Tags: pkgsrc-2013Q1-base, pkgsrc-2013Q1
Changes since 1.17: +2 -2 lines
Diff to previous 1.17 (colored) to selected 1.4 (colored)
Bump PKGREVISION from default PHP version change to 5.4.
Revision 1.17 / (download) - annotate - [select for diffs], Thu Nov 22 10:59:09 2012 UTC (6 years, 5 months ago) by hauke
Branch: MAIN
CVS Tags: pkgsrc-2012Q4-base, pkgsrc-2012Q4
Changes since 1.16: +4 -2 lines
Diff to previous 1.16 (colored) to selected 1.4 (colored)
Add the php-calendar and php-curl dependencies that davical is complaining about.
Revision 1.16 / (download) - annotate - [select for diffs], Sun Oct 28 06:30:13 2012 UTC (6 years, 6 months ago) by asau
Branch: MAIN
Changes since 1.15: +1 -3 lines
Diff to previous 1.15 (colored) to selected 1.4 (colored)
Drop superfluous PKG_DESTDIR_SUPPORT, "user-destdir" is default these days.
Revision 1.15 / (download) - annotate - [select for diffs], Wed Oct 3 21:58:29 2012 UTC (6 years, 7 months ago) by wiz
Branch: MAIN
Changes since 1.14: +2 -1 lines
Diff to previous 1.14 (colored) to selected 1.4 (colored)
Bump all packages that use perl, or depend on a p5-* package, or are called p5-*. I hope that's all of them.
Revision 1.14 / (download) - annotate - [select for diffs], Wed Aug 15 20:23:08 2012 UTC (6 years, 9 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2012Q3-base, pkgsrc-2012Q3
Changes since 1.13: +7 -6 lines
Diff to previous 1.13 (colored) to selected 1.4 (colored))
Revision 1.13 / (download) - annotate - [select for diffs], Sun Aug 5 10:02:14 2012 UTC (6 years, 9 months ago) by obache
Branch: MAIN
Changes since 1.12: +2 -1 lines
Diff to previous 1.12 (colored) to selected 1.4 (colored)
Bump PKGREVISION for change of PostgreSQL default version to 9.1.
Revision 1.12 / (download) - annotate - [select for diffs], Sat Jan 28 15:50:01 2012 UTC (7 years, 3 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2012Q2-base, pkgsrc-2012Q2, pkgsrc-2012Q1-base, pkgsrc-2012Q1
Changes since 1.11: +3 -5 lines
Diff to previous 1.11 (colored) to selected 1.4 (colored)
Update to 1.0.2: 1.0.2:. 1.0.1: Bug Fixes Fix missing braces the /tools.php script. Other Changes Update translations to current transifex translations. 1.0.0:
Revision 1.11 / (download) - annotate - [select for diffs], Tue Oct 25 07:33:54 2011 UTC (7 years, 6 months ago) by wiz
Branch: MAIN
CVS Tags: pkgsrc-2011Q4-base, pkgsrc-2011Q4
Changes since 1.10: +5 -6 lines
Diff to previous 1.10 (colored) to selected 1.4 (colored)
Update to 0.9.9.7. Supposedly improves iOS support and:. Depend on libawl-0.49. Remove legacy pgsql dependencies, I think they're not needed since 0.9.9.4.
Revision 1.10 / (download) - annotate - [select for diffs], Thu Oct 13 16:37:03 2011 UTC (7 years, 7 months ago) by wiz
Branch: MAIN
Changes since 1.9: +2 -1 lines
Diff to previous 1.9 (colored) to selected 1.4 (colored)
Fix build-always.sh -- added too many single quotes. Bump PKGREVISION.
Revision 1.9 / (download) - annotate - [select for diffs], Thu Oct 13 15:57:03 2011 UTC (7 years, 7 months ago) by wiz
Branch: MAIN
Changes since 1.8: +8 -7 lines
Diff to previous 1.8 (colored) to selected 1.4 (colored)
Revision 1.8 / (download) - annotate - [select for diffs], Fri Sep 16 05:46:26 2011 UTC (7 years, 8 months ago) by obache
Branch: MAIN
CVS Tags: pkgsrc-2011Q3-base, pkgsrc-2011Q3
Changes since 1.7: +2 -1 lines
Diff to previous 1.7 (colored) to selected 1.4 (colored)
Bump PKGREVISION from PHP_VERSION_DEFAULT changes.
Revision 1.7 / (download) - annotate - [select for diffs], Thu Sep 8 20:58:58 2011 UTC (7 years, 8 months ago) by wiz
Branch: MAIN
Changes since 1.6: +3 -2 lines
Diff to previous 1.6 (colored) to selected 1.4 (colored)
Update to 0.9.9.4: 2010-12-28 Andrew McMillan <andrew@morphoss.com> * Release 0.9.9.4 2010-12-27 Andrew McMillan <andrew@morphoss.com> * Refactor PUT functions to set modified/created dates more correctly. 2010-12-27 Leho Kraav <leho@kraav.com> * add et_EE to support locales 2010-12-26 Andrew McMillan <andrew@morphoss.com> * Fix errors in po files pointed out by Transifex uploading. * A new AtomFeed class for building an Atom feed. * Switch to creating an atom feed, which is a better feed standard. 2010-12-26 Leho Kraav <leho@kraav.com> * A new URL to provide an RSS feed of a calendar's changes. 2010-12-26 Andrew McMillan <andrew@morphoss.com> * Refactored RRule to add support for initialisation from a vProperty. 2010-12-25 Andrew McMillan <andrew@morphoss.com> * Remove all reference to PgQuery * Extensive refactoring of principal-edit, plus support for creating tickets. * Add support for writing scheduling resources on PUT. * Improve support for handling floating time. * Add cil for internal issue tracking. 2010-12-08 Andrew McMillan <andrew@morphoss.com> * Cut access with invalid/expired tickets out immediately. 2010-12-07 Andrew McMillan <andrew@morphoss.com> * Handle empty PROPFIND, don't blow up on invalid XML. 2010-11-30 Andrew McMillan <andrew@morphoss.com> * /.well-known/* now returns a 301 redirect, per spec. * Use text/vcard for content type in advance of ratification of spec. * Properly handle addressbooks in multiget. * Hide authorization headers in logging. * Update sync-collection REPORT to match -04 of draft. * Replace index.php with caldav.php when we find it in our path. 2010-11-27 Andrew McMillan <andrew@morphoss.com> * Be pedantic about checking user is active before we let them in. * Specify the SRV record examples with leading _ as they should be. 2010-11-21 Andrew McMillan <andrew@morphoss.com> * Fix SQL for group handling from Michael Braun. * Add principal-collection-set to standard responses for DAVResource. * Correct typo in POST handling. 2010-11-20 Andrew McMillan <andrew@morphoss.com> * Also update displayname if fullname is changed. 2010-10-02 Daniel Aleksandersen <daniel@> * remove old screenshots * updated iPhone client configuration with new screenshots 2010-11-19 Andrew McMillan <andrew@morphoss.com> * Handle stuff like DTSTART;TZID=America/New_York:20101119T231307 2010-11-14 Andrew McMillan <andrew@morphoss.com> * Script to refresh calendar_alarms with next instance time. 2010-11-09 Andrew McMillan <andrew@morphoss.com> * Don't let auth functions create duplicate home calendars. 2010-11-06 Andrew McMillan <andrew@morphoss.com> * Patch for caldav sync from Pierre-Arnaud Poudret. * Add ACL to the supported methods. * Change regression runner to look for sample data with tests. * Correct version number typo. * Always grant 'DAV::read' privilege from principal to group members. 2010-11-05 Andrew McMillan <andrew@morphoss.com> * Use expanded time specifiers in format since %Y doesn't work on Windows. * Support recursive REPORT query if configured to allow it. 2010-11-04 Andrew McMillan <andrew@morphoss.com> * Add a new WritableCollection object which we will use for PUT. * Use text/vcard rather than older text/x-vcard. * Support event properties in changed part of sync-response. * Rename variable to work around Pg 9.0 reserved name. 2010-11-01 Andrew McMillan <andrew@morphoss.com> * Switch from regular expression which may not work in old/odd PHP. 2010-10-31 Andrew McMillan <andrew@morphoss.com> * Support getlastmodified property in REPORT requests. 2010-10-16 Andrew McMillan <andrew@morphoss.com> * Fix typo in iTIP CANCEL handling. 2010-10-15 Andrew McMillan <andrew@morphoss.com> * Turn on calendar-auto-schedule header if $c->enable_auto_schedule * Add various additional checks into /setup.php * Add knowledge of desired parallel AWL version to setup. 2010-10-10 Andrew McMillan <andrew@morphoss.com> * Fix various minor CardDAV bugs. * Omit the <response> for event outside the time range - when expanded. * Fix privilege_to_bits function to set 'all' correctly & work with recent postgres 2010-10-08 Andrew McMillan <andrew@morphoss.com> * Don't supply freebusy for 0-duration events. * Another regression test for free/busy catching many events. * Add an event with a thoroughly bogus tzid to ensure we cope. * Check for some supported stuff very early so we can show it is missing. * Better display of bindings. * Add postgreSQL 9.0 as a possibility. * Fix warning when using basic authentication fallback. * Fix handling of iCalendar durations containing negative elements. * Handle events which don't have either DTEND *or* DURATION. * Rewrite __construct() method of RepeatRuleDateTimeZone to be more robust.
Revision 1.6 / (download) - annotate - [select for diffs], Sun Jul 3 11:08:29 2011 UTC (7 years, 10 months ago) by jym
Branch: MAIN
CVS Tags: pkgsrc-2011Q2-base, pkgsrc-2011Q2
Changes since 1.5: +2 -2 lines
Diff to previous 1.5 (colored) to selected 1.4 (colored)
check-interpreter fix for leaf package www/davical. Build and install cleanly now. Not updated due to freeze.
Revision 1.5 / (download) - annotate - [select for diffs], Tue Jan 18 22:26:28 2011 UTC (8 years, 4 months ago) by jym
Branch: MAIN
CVS Tags: pkgsrc-2011Q1-base, pkgsrc-2011Q1
Changes since 1.4: +2 -5 lines
Diff to previous 1.4 (colored)
Use REPLACE_PERL instead of REPLACE_INTERPRETER. No functional change.
Revision 1.4 / (download) - annotate - [selected], Sat Nov 13 00:27:24 2010 UTC (8 years, 6 months ago) by jym
Branch: MAIN
CVS Tags: pkgsrc-2010Q4-base, pkgsrc-2010Q4
Changes since 1.3: +2 -2 lines
Diff to previous 1.3 (colored)
As noted by wiz@ (and missed by me in TODO...), 0.9.9.3 was already out. Update to 0.9.9.3. Nothing much changed between .2 and .3, update is straightforward. While here, make MESSAGE more helpful in case of package upgrade. Changelog: 0.9.9.2 => 0.9.9.3.
Revision 1.3 / (download) - annotate - [select for diffs], Fri Nov 12 19:13:53 2010 UTC (8 years, 6 months ago) by jym
Branch: MAIN
Changes since 1.2: +4 -6 lines
Diff to previous 1.2 (colored) to selected 1.4 (colored)).
Revision 1.2 / (download) - annotate - [select for diffs], Wed Jun 2 23:27:56 2010 UTC (8 years, 11 months ago) by jym
Branch: MAIN
CVS Tags: pkgsrc-2010Q3-base, pkgsrc-2010Q3, pkgsrc-2010Q2-base, pkgsrc-2010Q2
Changes since 1.1: +10 -8 lines
Diff to previous 1.1 (colored) to selected 1.4 (colored)
Change the wording in MESSAGE; DAViCal could be installed on a host different from the one where the database server is running. Change the configuration files permissions. administration.yml is really for davical_dba, config.php is for davical_app (web application). While here, fix the Apache example. No revision bump; package content is the same.
Revision 1.1.1.1 / (download) - annotate - [select for diffs] (vendor branch), Sun May 23 21:36:30 2010 UTC (8 years, 11 months ago) by jym
Branch: TNF
CVS Tags: pkgsrc-base
Changes since 1.1: +0 -0 lines
Diff to previous 1.1 (colored) to selected 1.4 (colored)
Add davical..
Revision 1.1 / (download) - annotate - [select for diffs], Sun May 23 21:36:30 2010 UTC (8 years, 11 months ago) by j.
|
http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/www/davical/Makefile?r1=1.4
|
CC-MAIN-2019-22
|
refinedweb
| 3,468
| 70.29
|
It atomically sets the flag to true and returns its previous value.
Following is the declaration for std::atomic_flag_test_and_set.
bool atomic_flag_test_and_set( std::atomic_flag* p );
bool atomic_flag_test_and_set( volatile std::atomic_flag* p );
Following is the declaration for std::atomic_flag_test_and_set_explicit.
bool atomic_flag_test_and_set_explicit( volatile std::atomic_flag* p, std::memory_order order );
bool atomic_flag_test_and_set_explicit( std::atomic_flag* p, std::memory_order order );
p − It is used in pointer to std::atomic_flag to access.
order − It is used to synchronise the memory ordering for this operation.
It returns the value previously held by the flag pointed to by p.
No-noexcept − this member function never throws exceptions.
In below example for std::atomic_flag_test_and_set_explicit.
#include <thread> #include <vector> #include <iostream> #include <atomic> std::atomic_flag lock = ATOMIC_FLAG_INIT; void f(int n) { for (int cnt = 0; cnt < 100; ++cnt) { while(std::atomic_flag_test_and_set_explicit(&lock, std::memory_order_acquire)) ; std::cout << "Output from thread " << n << '\n'; std::atomic_flag_clear_explicit(&lock, std::memory_order_release); } } int main() { std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(f, n); } for (auto& t : v) { t.join(); } }
The sample output should be like this −
Output from thread 0 Output from thread 1 Output from thread 0 Output from thread 0 Output from thread 1 Output from thread 1 Output from thread 0 Output from thread 0 Output from thread 1 Output from thread 0 ....................
|
https://www.tutorialspoint.com/cpp_standard_library/cpp_atomic_flag_test_and_set.htm
|
CC-MAIN-2020-10
|
refinedweb
| 216
| 54.02
|
This program identifies 'priority' e-mails in a dataset of e-mails. E-mail $i$ is a priority e-mail if Rank($i$) $\ge$ threshold, where Rank($i$) is the product of 5 weighting factors. So, if:
$\prod_{k=1}^{5}\omega_k(i) \ge \textrm{threshold}$
then e-mail $i$ is a priority message. The weighting functions $\omega_k(i)$ and the
threshold are calculated from a training dataset (
train_df).
The five weights functions are:
The program is broken into sections of functionality:
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
import os import re import math import random import numpy as np import datetime as dt import dateutil.parser as dtp import matplotlib.pyplot as plt import textmining as txtm import string from pandas import * import sys from statsmodels.nonparametric import KDE from tdm_df import tdm_df # Term-document matrix builder from CH3
# Define paths to the data. We'll be prioritizing e-mails in the "Easy Ham" folder data_path = os.path.abspath(os.path.join('..','ch3', 'data')) easyham_path = os.path.abspath(os.path.join(data_path, 'easy_ham'))
def parse_email_list(file_list): ''' Create a generator that iterates through the e-mails in a folder, and parses them as the generator is called. ''' for f in file_list: yield parse_email(os.path.join(easyham_path, f)) def parse_email(path): ''' Get important elements of an e-mail file (date, sender's e-mail address, subject, and message contents. ''' filename = os.path.split(path)[-1] header, message = get_header_and_message(path) date = get_date(header) sender = get_sender(header) subj = get_subject(header) return date, sender, subj, message, filename def get_header_and_message(path): ''' Split e-mail's header and its message into two separate strings. ''' with open(path, 'rU') as con: email = con.readlines() first_blank_index = email.index('\n') header = email[:first_blank_index] message = ''.join(email[(first_blank_index + 1): ]) return header, message # Regex pattern that finds the date line # (it's a line that starts with 'Date') date_pattern = re.compile('^Date') def get_date(header): ''' Find the date line of the e-mail's header, and parse the date into a datetime object. ''' # Get the first line that matches the date-line # regex pattern dateline = [l for l in header if re.search(date_pattern, l) != None][0] # Grab the text after 'Date: ' (6 chars) dateline = dateline[6:].strip() # Return the date as parsed by dateutil.parser.parse() return dtp.parse(dateline) # Characters that may separate words in the From line splitfrom_pattern = re.compile('[\"\:<> ]') def get_sender(header): ''' Find the 'From:' line in the e-mail's header data, and extract the sender's e-mail address from it. ''' # Find line in header that contains 'From: ' sender = filter(lambda s: s.find('From: ') != -1, header)[0] # Get 'words' in From line sender = re.split(splitfrom_pattern, sender) sender = filter(lambda s: s != ' ' and s != '', sender) # Find the first word that is an e-mail address (contains @) sender = filter(lambda s: '@' in s, sender)[0] sender = re.sub('\\[a-z]', '', sender) return sender.lower().rstrip() def get_subject(header): ''' Find the subject line of the e-mail's header, and extract the subject text. ''' subject = filter(lambda s: s.find('Subject: ') != -1, header) if len(subject) > 0: subject_start = subject[0].find('Subject: ') + 9 subject = subject[0][subject_start:] return subject.lower() else: return ''
This function will using the parse_email_list function to iterate through the e-mail generator and collect the e-mails' date, sender, subject, message (and the name of the file containing the e-mail) into a dictionary of lists. The dictionary is then converted to a DataFrame.
def make_email_df(email_dir): ''' Parse each e-mail in a directory and return a dataframe of each e-mail's date, sender, subject, and message ''' email_dict = {'date' : [], 'sender' : [], 'subject' : [], 'message' : [], 'filename' : []} # Get a list of e-mails to parse file_list = os.listdir(email_dir) file_list = [f for f in file_list if f != 'cmds'] # A generator that that returns the parsed components # of each subsequent e-mail as called parsed_emails = parse_email_list(file_list) # Fill up the dictionary with the generator for pe in parsed_emails: date, sender, subject, message, filename = pe email_dict['date'].append(date) email_dict['sender'].append(sender) email_dict['subject'].append(subject) email_dict['message'].append(message) email_dict['filename'].append(filename) # Make the dictionary a data frame. email_df = DataFrame(email_dict, columns = ['date', 'sender', 'subject', 'message', 'filename']) return email_df
# Make a dataframe of information in the # 'Easy Ham' emails email_df = make_email_df(easyham_path)
The first half of the e-mails will be used as the 'training' set. From this set we'll extract features that we'll use to classify the second half of e-mails. Typically, we might shuffle the data before splitting the set, so that we get a representative view of features. But, since we're classifying e-mails, it's more appropriate to take the earlier e-mails as the training set, and see how well they identify 'priority' e-mails amongst subsequently-recieved e-mails. = arange(train_df.shape[0]) test_df.index = arange(test_df.shape[0]) return train_df, test_df
Some dates lack time-zone info, making them impossible to sort We'll sort ignoring timezone, knowing that it's buggy, but for comparison with the book. The R code in ML4H ignores timezones, and this leads to some errors. See note at the end.
email_df['sort_date'] = email_df['date'].map(lambda d: dt.datetime(d.year, d.month, d.day, d.hour, d.minute, d.second)) email_df = email_df.sort('sort_date') train_df, test_df = train_test_split(email_df, shuffle = False, preserve_index = False, seed = 224)
# Each sender address get's a weight equal to the log of # 1 + the number of e-mails from that address. def get_sender_weights(email_df): freq = email_df['sender'].value_counts() freq.sort() sender_weights = DataFrame({'freq' : freq, 'weight' : np.log(1.0 + freq)}) sender_weights = sender_weights.sort('weight', ascending = False) return sender_weights
Plot sender frequencies of the top 30 senders in the training set. Get the frequencies of these same addresses from the test set, and plot for comparisons. This will give us some idea of senders we'll end up flagging in the test set.
sender_weights = get_sender_weights(train_df) sender_weights_test = get_sender_weights(test_df) nshow = 30 top_emails = sender_weights[:nshow].index plt.figure(figsize = (6, 14)) plt.barh(np.arange(nshow), sender_weights['freq'][top_emails], align = 'center', label = 'Training') plt.barh(np.arange(nshow), sender_weights_test['freq'][top_emails], align = 'center', left = sender_weights['freq'][top_emails].fillna(0), fc = 'orange', alpha = .8, label = 'Test') plt.ylim((0 - .5, nshow - .5)) plt.title('Frequency of top %i sender addresses' % nshow) plt.yticks(np.arange(nshow), top_emails) plt.legend(frameon = False)
<matplotlib.legend.Legend at 0x1070c7190>
We want to identify threads amongst the e-mails and exctract information from them separately. We'll find threads that have been replied-to or forwarded, and collect all e-mails with the same subject (after stripping reply and forward tags out) into the same thread.
For example:
will all be in the same thread. This differs slightly from how the book identifies thread messages. They only flag messages with 'Re:' prefixes, so they would miss messages [1] and [4]. (TODO: Check how they would flag [5])
After flagging them, we'll collect info about these threads# into a separate DataFrame.
Regex patterns indicating a thread. Looking for reply and forward markers. Note that some mail services use 'Re:Re:Re:'-type prexifes to mark multiple replies (or forwards), while other use 'Re[3]:'.
reply_pattern = '(re:|re\[\d\]:)' fwd_pattern = '(fw:|fw[\d]:)'
def thread_flag(s): ''' Returns True if string s matches the thread patterns. If s is a pandas Series, returns a Series of booleans. ''' if isinstance(s, basestring): return re.search(reply_pattern, s) is not None else: return s.str.contains(reply_pattern, re.I) def clean_subject(s): ''' Removes all the reply and forward labeling from a string (an e-mail subject) s. If s is a pandas Series, returns a Series of cleaned strings. This will help find the initial message in the thread (which won't have any of the reply/forward labeling. ''' if isinstance(s, basestring): s_clean = re.sub(reply_pattern, '', s, re.I) s_clean = re.sub(fwd_pattern, '', s_clean, re.I) s_clean = s_clean.strip() else: s_clean = s.str.replace(reply_pattern, '', re.I) s_clean = s_clean.str.replace(fwd_pattern, '', re.I) s_clean = s_clean.str.strip() return s_clean def get_thread_df(email_df): ''' Identify threads in an e-mail DataFrame, and extract them into a new DataFrame. ''' # Find threads by e-mails with reply patterns in their subjects. # Then get a set of thread subjects. is_thread = thread_flag(email_df['subject']) thread_subj = email_df['subject'][is_thread] # Clean up the subjects by removing reply and forward labels thread_subj = clean_subject(thread_subj) thread_subj = thread_subj.unique() # Search for these thread subjects in the original # e-mail DataFrame (so we pick up the original e-mail in the # thread (which won't have a reply pattern in its subject) # Prepare the DataFrame for searching by cleaning up the # subjects. search_df = email_df[['date', 'sender', 'subject']] search_df['subject'] = clean_subject(search_df['subject']) # Find subject matches thread_matches = [subj in thread_subj for subj in search_df['subject']] match_df = search_df.ix[thread_matches, :] return match_df
# Get a DataFrame of threads in the training e-mails; # compute sender weights within this subset of threads. # To do the latter, we can use the same function we # used on the whole DataFrame above. thread_df = get_thread_df(train_df) thread_sender_weights = get_sender_weights(thread_df)
def get_thread_activity(thread_df): ''' Compute 'activity' statistics on threads in a DataFrame: frequency: Number of e-mails observed in the thread span: Time before the first and last e-mail observed (seconds) weight: Number e-mails-per-second in the thread (log-scale) ''' clean_times = thread_df['date'].map(lambda t: t.tzinfo is not None) thread_df_clean = thread_df.ix[clean_times, :] freq_by_thread = thread_df['subject'].value_counts() # NB: I'm not sure if total_seconds() is daylight-savings aware # so this may be mildly buggy. seconds_span = lambda x: ( (np.max(x) - np.min(x)).total_seconds()) span_by_thread = thread_df_clean.groupby('subject') span_by_thread = span_by_thread['date'].aggregate(seconds_span) activity = DataFrame({'freq' : freq_by_thread, 'span' : span_by_thread, 'weight' : 10 + np.log10(freq_by_thread/span_by_thread)}) # Restricting to threads with more than 2 e-mails may be unecessary, but we # could get 1-e-mail threads for a couple of reasons: misclassification (it's # not really a thread), and left-censored threads -- where we found the last # reply in the thread, but the earlier messages were recieved before the data # was collected. activity = activity[activity['freq'] >= 2] activity = activity[notnull(activity['weight'])] return activity
thread_activity_df = get_thread_activity(thread_df)
Check against table on p. 116
Since book ignores time-zone info., spans in book are often wrong (see, e.g., 'please help newbie compile mplayer :-)')
threads_to_check = ['please help a newbie compile mplayer :-)', 'prob. w/ install/uninstall', ''] print thread_activity_df.ix[threads_to_check, :]
freq span weight please help a newbie compile mplayer :-) 4 13509 6.471437 prob. w/ install/uninstall 4 12114 6.518772 10 265303 5.576258
We create term-document-matrices for the e-mails subjects and messages. (E.g., each subject is a document, or each message is a document). Then we make two different sets of term weighting functions.
# Stopwords from R. NLTK has a set of stopwords we could use as # well, but this minimizes discrepancies with the book. rsw = read_csv('../ch3/r_stopwords.csv')['x'].values.tolist() def get_thread_subject_term_weights(thread_activity_df): ''' Creates a term->weight map based on a DataFrame containing thread subjects and their activity weights ''' thread_subjects = thread_activity_df.index thread_tdm = tdm_df(thread_subjects, remove_punctuation = False, remove_digits = False, stopwords = rsw) def calc_term_weight(term): threads_with_term = np.where(thread_tdm[term] > 0.0) weight_vec = thread_activity_df['weight'].ix[threads_with_term] return weight_vec.mean() term_weights = Series({t: calc_term_weight(t) for t in thread_tdm}) return term_weights
thread_subject_terms_weights = \ get_thread_subject_term_weights(thread_activity_df)
# Example term weights print thread_subject_terms_weights.head(10)
aa 5.759571 adam 5.975084 adhesion 4.814012 adsl 6.397131 advice 4.915926 alsa 5.817899 angry 6.028029 announces 6.093981 anolther 5.317371 app 5.699035
def get_message_term_weights(email_df): ''' Creates a term->weight map for terms in the messages of the training e-mail DataFrame ''' messages = email_df['message'] term_freq = tdm_df(messages, stopwords = rsw).sum() term_weight_df = DataFrame({'freq' : term_freq, 'weight' : np.log10(term_freq)}) return term_weight_df
message_terms_weights = get_message_term_weights(train_df)
The following function comprises the two term-weighting functions. It computes either a message's subject-term-weight or message-term-weight, depending on what arguments we pass to it.
def get_weight_from_terms(term_list, weight_df, subject = False): ''' Given a term-list from an e-mail's message, and a term->weights map contained in a DataFrame, calculate the e-mail's message or subject term-weight. (default is message) ''' if isinstance(term_list, basestring): term_list = [term_list] if subject: weights = weight_df else: weights = weight_df['weight'] term_list_weight = weights[term_list].mean() if np.isnan(term_list_weight): term_list_weight = 1.0 return term_list_weight
def rank_email(email_df, row): ''' Ranks an e-mail (as contained in the row of a DataFrame) by computing and combining its five weights. ''' email = email_df.ix[row, :] date = email['date'] sender = email['sender'] subject = email['subject'] message = email['message'] # 1. Get sender weights (all messages) sender_weight = (sender_weights['weight'] .get(sender) or 1.0) # 2. Get sender weights (threads) thread_sender_weight = (thread_sender_weights['weight'] .get(sender) or 1.0) # 3. Get thread activity weight is_thread = thread_flag(subject) subject = clean_subject(subject) if is_thread: activity_weight = (thread_activity_df['weight'] .get(subject) or 1.0) else: activity_weight = 1.0 # 4. Get subject line weight via thread-subject term weights subj_terms = tdm_df(subject, remove_punctuation = False, remove_digits = False, stopwords = rsw).columns subj_term_weight = get_weight_from_terms(subj_terms, thread_subject_terms_weights, subject = True) # 5. Message term weight message_terms = tdm_df(message, stopwords = rsw).columns message_term_weight = get_weight_from_terms(message_terms, message_terms_weights) weights = [sender_weight, thread_sender_weight, activity_weight, subj_term_weight, message_term_weight] # The e-mail's final rank is just the product of the weights. rank = np.array(weights).prod() return rank
def make_rank_df(email_df): ''' Rank each e-mail in a DataFrame. ''' n_emails = email_df.shape[0] sender_weight_results = [] thread_sender_weight_results = [] activity_weight_results = [] subj_term_weight_results = [] message_term_weight_results = [] rank_results = [] rank_df = email_df.copy() for e in xrange(n_emails): weights_rank = rank_email(email_df, e) rank_results.append(weights_rank) rank_df['rank'] = rank_results return rank_df
Rank the e-mails in the training set.
train_ranks = make_rank_df(train_df)
Calculate the threshold for flagging a 'priority' message. New messages that have a rank greater than the threshold get flagged as priority.
threshold = train_ranks['rank'].median()
Rank the e-mails in the test set.
test_ranks = make_rank_df(test_df)
train_kde = KDE(train_ranks['rank']) train_kde.fit() test_kde = KDE(test_ranks['rank']) test_kde.fit() plt.figure(figsize(8, 6)) plt.fill(train_kde.support, train_kde.density, color = 'steelblue', alpha = .7, label = 'Train') plt.fill(test_kde.support, test_kde.density, color = 'red', alpha = .7, label = 'Test') plt.xlim(0, 400) plt.ylim(0, np.max(test_kde.density)) plt.axvline(threshold, linestyle = '--', label = 'Priority threshold') plt.xlabel('Rank') plt.ylabel('Density') plt.title('Distribution of ranks for training and test e-mails') plt.legend(frameon = False)
<matplotlib.legend.Legend at 0x10f450f90>
(test_ranks['rank'] > threshold).sum()
65
What sender addresses get flagged in the test set? We should see some familiar addresses from the graph above.
test_ranks[test_ranks['rank'] > threshold]['sender'].unique()
array([]], dtype=object)
Which training set e-mail is ranked highest?
maxrank_email = train_ranks.ix[train_ranks['rank'].idxmax(), :] print 'Maximum rank in training set: ', train_ranks['rank'].max()
Maximum rank in training set: 1020.94633354
This turns out to be a lot higher than the largest found by the authors' R program. Let's check it out.
It turns out this e-mail's thread activity weight is substantially higher than found in the R code. As shown next, this is the result of a time-zone bug in the R code.
thread_activity_df.ix[clean_subject(maxrank_email['subject']), :]
freq 2.00000 span 4.00000 weight 9.69897 Name: [sadev] [bug 840] spam_level_char option change/removal
There are two messages in this thread (in the training set).
thread_df[thread_df['subject'].str.contains('spam_level_char')]['date']
734 2002-09-06 10:56:23-07:00 763 2002-09-06 13:56:19-04:00 Name: date
E-mail 734 come 4 seconds after 763. But if we mistakenly ignore the time-zone (like in the R code) 734 comes 2:59:56 before 763.
All else equal, this will reduce the rank of this e-mail by 35%.
correct_weight = 10 + np.log10(2 / 4.) incorrect_weight = 10 + np.log10(2 / (2* 3600 + 59 * 60 + 56.)) print 'Activity weight correct time-zone: ', correct_weight print 'Activity weight incorrect time-zone: ', incorrect_weight print 'Rank difference: ' , '{:2.1%}'.format(1 - incorrect_weight / correct_weight)
Activity weight correct time-zone: 9.69897000434 Activity weight incorrect time-zone: 6.26776711978 Rank difference: 35.4%
|
http://nbviewer.jupyter.org/github/carljv/Will_it_Python/blob/master/MLFH/ch4/ch4.ipynb
|
CC-MAIN-2018-51
|
refinedweb
| 2,680
| 52.26
|
Ambiguity
I believe nearly every developer eventually creates their own metaphor for programming. Some are rather tame, such as building bridges between users and systems. Others can be quite aggressive. One of my coworkers will often say hes spent his day mangling bits when things have not gone particularly well. As for me, I frequently picture myself with a large sledgehammer, squashing ambiguities. The gap between users and their systems isnt so much bridged, as it is filled with the remains of ambiguities laid to rest.
Like a lot of programmers, I work hard to resolve misunderstandings between what is desired and what is delivered. In my opinion, its the hardest part of the job. At the same time, Im thankful for the standard practices and idioms commonly found throughout the Java community. I wish I could say that the wonderful source level comments we write one another dispel all questions about intent, but the reality is that the idioms are sometimes our only guide to what the code was meant to do. This is especially true in terms of the public interface of a class or component. Even the best JavaDocs in the world will not solve the problems associated with a sloppy and contrary mix of common patterns and practices in a public interface. Ambiguities between developer and user are bad enough. It becomes extremely frustrating when they exist between programmers.
For instance, I recently came across a class that I couldnt decide if it was a bean gone bad, or a singleton with an split-personality. Ive changed the actual implementation to shield the guilty, but the sample below retains much of original class' flavor.
public class Foobar {
public static String attribute1;
public String attribute2;
public String attribute3;
private static Fooobar instance;
private Foobar() {
}
public static getInstance() {
if (instance == null) {
instance = new Foobar();
}
return instance;
}
public static String getAttribute1() {
return attribute1;
}
public static void setAttribute1(String attribute) {
attribute1 = attribute;
notifyObservers();
}
public static viod setAttribute1NoNotify(String attribute) {
attribute1 = attribute1;
}
public String getAttribute2() {
return this.attribute2;
}
public void setAttribute2(String attribute) {
this.attribute2 = attribute2;
}
public String getAttribute3() {
return this.attribute3;
}
}
Now, I'm not about to critique the entire class, but even a quick glance shows there's something not quite right with it. The class begins by looking like a singleton with a private constructor and a
getInstancemethod to control the single instance of the class. However, nearly all the other methods of the class are marked public static which makes the
getInstancemethod unnecessary. Furthermore, the
public staticmethods are mostly getters and setters for publicly available attributes which can be accessed from outside the getters and setters. Then, there is the problem of mixing bean-like behaviour with public getters and setters within the singleton. There may be a need for a singleton bean, but then you wouldn't mark the attributes public, nor would you make them instance rather than class variables. Even the experienced developers that I asked to review the code were hard-pressed to know what to make of the class. Is it a bean, a singleton, a bean-gleton? Finally, when you consider the class in the context of a large application, and the fact that the original is both much larger and more complex that the sample shown, you begin to realize that you have just meet the boss ambiguity for this level of the development game.
Standard practices, idioms, and programming conventions are important in that they help to minimize the number of ambiguities that exist between developers. Although we can argue endlessly what the conventions should be, our lives as programmers would be a lot tougher without them.
- Login or register to post comments
- Printer-friendly version
- castelaz's blog
- 956 reads
|
https://weblogs.java.net/blog/castelaz/archive/2004/08/ambiguity.html
|
CC-MAIN-2015-22
|
refinedweb
| 622
| 51.58
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.