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
Tooling Tuesday is a new series of short, to the point blog posts that highlight a fun and useful tool for developers, coders, makers, hackers and of course system administrators. For the first in the series of Tueday Tooling blog posts, I have chosen to highlight a rather fun and useful Python library that can provide meaningful and expressive interaction to the user. So tell me more Spinners, no not those fidget spinners, but a way in which a process or application can show you that it is working on something. Created by Manraj Singh, Halo is nothing to do with Master Chief, and more about giving the user useful output while a script is running. Halo? Requirements - A *nix system, Halo doesn't work with Windows...yet. - It will work on a Raspberry Pi, and a big powerful *nix server I rather like Halo it is really easy to install. How do I install it? From a terminal type... sudo pip3 install halo And it can be dropped into your Python script rather easily. from halo import Halo spinner = Halo(text='Loading', spinner='dots') spinner.start() # Run time consuming work here # You can also change properties for spinner as and when you want spinner.stop() Each "spinner" can be configured to deliver a set message and this is set by adding text='something'. The spinner animation can then be selected from a rather long JSON file of options, try monkey its fun but a bit useless. The spinner is then started, and it runs while your Python sequence is running. Then all you need to do is stop the spinner when you are ready. Lets take it for a spin. I wanted to test how Halo could be used so I wrote a quick project that can be run from the terminal. It is really a wrapper for ping used to check if a site or IP address is up. The project just shows how Halo can be used to pep up a project. The code can be run from the terminal, and from there you can pass an IP address of URL as an argument. This is then used to run a ping test on the URL/IP address and a result is displayed. The running project looks like this. And as you can see the project runs and shows a quick "progress bar" that illustrates the application is loading, then the project advises the user on the status of a URL/IP using a green tick for an active site, and a red cross if the site is down. Simple things but handy for fast confirmnation. Here is all of the code for the project. #!/usr/bin/env python3 from halo import Halo from time import sleep import os import sys spinner = Halo(text='Starting the ping application', spinner='growHorizontal') spinner.start() sleep(2) spinner.stop() spinner.succeed("Pinger initialisation complete") response = os.system("ping -c 1 " + sys.argv[1]) if response == 0: print("============") spinner.succeed(sys.argv[1]+" is up") print("============") else: print("============") spinner.fail(sys.argv[1]+" is down") print("============") Conclusion Halo is a great tool for sysadmins needing a quick and easy method to create informative and appealing outputs to the user. It is also a fun way to provide visual flair to your code, and could be used for a visual debugging tool in your next Python project. Code for this project All of the code that I have written for this post can be found on my GitHub page.
http://bigl.es/tuesday-tooling-custom-python-spinners/
CC-MAIN-2018-09
refinedweb
587
71.85
Chatlog 2010-04-29 Data Catalog Vocabulary From W3C eGovernment Wiki See CommonScribe Control Panel, original RRSAgent log and preview nicely formatted version. Please justify/explain all edits to this page, in your "edit summary" text. <sandro> Guest: Bobbin Teegarden, <sandro> Guest: William (ww) Waites <sandro> Guest: Paul (PaulZH) Hermans <sandro> Present: Brand_Niemann, David_James, Ed_Summers, Fadi_Maali, George_Thomas, Jon_Phipps, Li_Ding, Luigi_Montanez, Martín_Álvarez, Michael_Hausenblas, Richard_Cyganiak, Vassilios Peristeras 15:01:16 <RRSAgent> RRSAgent has joined #egov 15:01:16 <RRSAgent> logging to 15:01:18 <trackbot> RRSAgent, make logs public 15:01:20 <trackbot> Zakim, this will be EGOV 15:01:20 <Zakim> ok, trackbot, I see T&S_EGOV(LD TECH)10:00AM already started 15:01:21 <trackbot> Meeting: eGovernment Interest Group Teleconference 15:01:21 <trackbot> Date: 29 April 2010 15:01:30 <cygri> nice. thanks mhausenblas! 15:01:54 <cygri> agenda: 15:02:06 <edsu> Zakim, LC is edsu 15:02:06 <Zakim> +edsu; got it 15:02:10 <mhausenblas> RRSAgent, draft minutes 15:02:10 <RRSAgent> I have made the request to generate mhausenblas 15:02:12 <Zakim> +??P7 15:02:25 <cygri> Chair: cygri 15:02:31 <cygri> Scribe: edsu 15:02:52 <cygri> zakim, who is here? 15:02:52 <Zakim> On the phone I see ??P3, +1.202.955.aaaa, martin, George, +03539149aabb (muted), edsu, ??P7 15:02:54 <Zakim> On IRC I see RRSAgent, Zakim, LuigiMontanez, PaulZH, george, jonphipps, martin, fadi, cygri, n8fr8__, mhausenblas, hughb, ww, edsu, sandro, trackbot 15:03:10 <Zakim> +jonphipps 15:03:29 <lindstream> lindstream has joined #egov 15:03:32 <Zakim> +??P8 15:03:57 <n8fr8__> n8fr8__ has left #egov 15:04:03 <Zakim> - +03539149aabb 15:04:09 <vassilios> vassilios has joined #egov 15:04:12 <DavidJames> DavidJames has joined #egov 15:04:46 <edsu> that's dc area 15:04:54 <Zakim> + +1.425.378.aacc 15:05:23 <Zakim> + +03539149aadd 15:06:00 <edsu> ww: are you on the call? 15:06:09 <PaulZH> I'm also calling IP 15:06:56 <bobbin> bobbin has joined #egov 15:06:57 <cygri> zakim, who is talking? 15:07:08 <Zakim> cygri, listening for 10 seconds I heard sound from the following: ??P3 (9%), ??P8 (9%) 15:07:18 <fadi> zakim, aabb is fadi 15:07:18 <Zakim> sorry, fadi, I do not recognize a party named 'aabb' 15:07:29 <cygri> zakim, who is on the phone? 15:07:29 <Zakim> On the phone I see ??P3, +1.202.955.aaaa, martin, George, edsu, ??P7, jonphipps, ??P8, +1.425.378.aacc (muted), +03539149aadd (muted) 15:07:46 <cygri> zakim, aadd is fadi 15:07:46 <Zakim> +fadi; got it 15:08:09 <vassilios> vassilios also on IP phone 15:09:08 <cygri> zakim, aaaa is LuigiMontanez 15:09:08 <Zakim> +LuigiMontanez; got it 15:09:16 <cygri> zakim, who is here? 15:09:16 <Zakim> On the phone I see ??P3, LuigiMontanez, martin, George, edsu, ??P7, jonphipps, ??P8, +1.425.378.aacc (muted), fadi (muted) 15:09:18 <Zakim> On IRC I see bobbin, DavidJames, vassilios, lindstream, RRSAgent, Zakim, LuigiMontanez, PaulZH, george, jonphipps, martin, fadi, cygri, mhausenblas, hughb, ww, edsu, sandro, 15:09:20 <Zakim> ... trackbot 15:09:58 <edsu> Topic: Admin 15:10:21 <edsu> cygri: agenda 15:10:51 <edsu> ... we'll have a presentation from martin of ctic, and hopefully one from li ding of rpi 15:11:23 <edsu> ... time permitting i'd like to talk about the scope and deliverables of the group 15:11:34 <edsu> ... and hopefully write those down on the wiki 15:11:39 <edsu> Topic: Demos 15:12:13 <cygri> wiki page: 15:12:19 <edsu> martin: here at ctic we develop an open data solution in spain, a good proof of concept of the linked data solution 15:12:59 <edsu> ... here you can see some metadata based on the VoID and Dublin Core vocabularies 15:13:24 <edsu> ... you can see license and provenance information, and the available data formats 15:13:47 <edsu> ... the generation of the catalog is using sparql and xslt 15:14:29 <martin> 15:14:30 <edsu> ... we have a list of catalogs (a meta catalog) 15:15:16 <fadi> fadi has joined #egov 15:15:23 <edsu> ... similar to the deri dcat approach, title, description, license 15:15:28 <martin> 15:15:40 <martin> 15:16:06 <edsu> ... also have a rss feed of the catalogs, which is used to geenrate a map of the catalogs 15:17:18 <edsu> cygri: you have used void for the data catalog, are the datasets in the catalog all available as rdf? this is not the case for most catalogs (e.g. data.gov) 15:17:38 <edsu> ... do you think it makes sense to use void when the dataset is not rdf? 15:18:21 <edsu> martin: i think void is by definition only for rdf data sets ... so i think no? 15:18:52 <edsu> cygri: that's what void was made for originally, but it possibly could be applied in a broader scope ... but i take your answer as saying you'd only use it for rdf data sets? 15:19:04 <edsu> martin: i think void could be useful 15:19:23 <cygri> zakim, who is here 15:19:23 <Zakim> cygri, you need to end that query with '?' 15:19:29 <edsu> mapstraction.addOverlay(''); 15:19:35 <cygri> zakim, who is here? 15:19:35 <Zakim> On the phone I see ??P3, LuigiMontanez, martin, George, edsu, ??P7, jonphipps, ??P8, +1.425.378.aacc (muted), fadi (muted) 15:19:37 :19:40 <Zakim> ... trackbot 15:20:34 <Zakim> + +1.202.564.aaee 15:21:27 <edsu> cygri: do we have a new attendee from dc? 15:21:48 <edsu> cygri: ok, it's brandt from epa in washington 15:21:54 <cygri> zakim, aaee is brand 15:21:54 <Zakim> +brand; got it 15:23:04 <edsu> bobbin: i'm on the call too 15:23:15 <cygri> zakim, aacc is bobbin 15:23:15 <Zakim> +bobbin; got it 15:23:56 <cygri> zakim, who is here? 15:23:56 <Zakim> On the phone I see ??P3, LuigiMontanez, martin, George, edsu, ??P7, jonphipps, ??P8, bobbin, fadi, brand 15:23:59 :24:01 <Zakim> ... trackbot 15:24:25 <DavidJames> LuigiMontanez and I are sharing a conference phone 15:24:43 <cygri> zakim, davidjames is with luigimontane 15:24:43 <Zakim> +davidjames; got it 15:24:50 <cygri> zakim, davidjames is with luigimontanez 15:24:50 <Zakim> davidjames was already listed in LuigiMontanez, cygri 15:24:51 <bobbin> Bobbin Teegarden, semantic consultant in Seattle 15:25:14 <edsu> cygri: seems like Li isn't going to make the call 15:25:21 <edsu> Topic: Deliverables 15:26:37 <edsu> 15:26:54 <edsu> ... a couple of points were raised on the mailing list 15:27:13 <edsu> ... erik suggested we should be clear about the types of serices we want to enable 15:27:27 <edsu> ... so that's where i would like to pick up 15:27:40 <DavidJames> we're getting a lot of echo and delay on the line 15:27:41 <LI_DING> LI_DING has joined #egov 15:28:20 <edsu> cygri: i sent an email 15:28:50 <edsu> ... one deliverable might be use cases and requirements 15:29:20 <edsu> ... a second thing could be an rdf vocabulary and reference that lists the terms, which required/optional, examples 15:29:56 <edsu> ... it would make sense to use some sort of formalism, uml, or perhaps rdf schema, since it will give us one possible way of deploying dcat data 15:30:55 <edsu> ... 15:31:23 <edsu> ... do you think we could delay the decision about the concrete format until we do use cases requuirements? 15:31:23 <Zakim> + +1.518.495.aaff 15:31:34 <Zakim> - +1.518.495.aaff 15:31:50 <PaulZH> I do agree to postpone the decision 15:32:38 <Zakim> + +1.518.495.aagg 15:32:47 <edsu> edsu: i agree in principle, but it will take more time 15:32:52 <LI_DING> hi 15:32:55 <LI_DING> li is joining 15:33:25 <edsu> Zakim, +1.518.495.aagg is LI_DING 15:33:25 <Zakim> +LI_DING; got it 15:34:04 <edsu> LI_DING: we're reviewing cygri's proposal at 15:34:55 <edsu> cygri: i think by writing down use cases and requirements we'll get a better understanding about technical choices 15:35:30 <edsu> LI_DING: what is the current status, discussion the requirements? 15:36:27 <edsu> cygri: yes, basically we're discussing whether we should abstract out of the concrete syntax, and write use cases and requirements 15:37:22 <edsu> ... there doesn't seem to be a lot of disagreement or agreement with this 15:37:55 <edsu> LI_DING: i want to hear more voices first i think 15:38:11 <cygri> zakim, who is on the phone 15:38:11 <Zakim> I don't understand 'who is on the phone', cygri 15:38:23 <cygri> zakim, who is on the phone? 15:38:23 <Zakim> On the phone I see ??P3, LuigiMontanez, martin, George, edsu, ??P7, jonphipps (muted), ??P8, bobbin, fadi (muted), brand, LI_DING 15:38:25 <Zakim> LuigiMontanez has LuigiMontanez, davidjames 15:38:58 <DavidJames> Regarding ... I like the list of requirements. 15:39:49 <DavidJames> The deliverables also look good to me. 15:39:55 <edsu> LI_DING: i'd need more time to review the proposal, but i think we want to keep things as minimal as possible to get something out there quick, also i think we should keep use cases simple, how much do we want to get? 15:40:19 <edsu> ... we should try to produce something actionable 15:41:37 <edsu> cygri: i don't hear any strong objection to moving forwards with the deliverables i outlined in the email ; for now we should continue working with this assumption 15:41:54 <LI_DING> one thing could be a challenge 15:42:03 <DavidJames> Can we ask everyone to vote (or something similar)? 15:42:34 <edsu> LI_DING: maybe we can have a challenge a deliverable: how many gov't data sets can you find? 15:43:16 <edsu> ... lets grow the number of government data sets, more people using the vocabulary 15:43:45 <edsu> cygri: but what does this mean for the format we want to design? 15:44:10 <vassilios> i think it is not a matter of number of datasets but number of catalogues 15:45:07 <Zakim> -brand 15:45:22 <edsu> LI_DING: it's a parallel effort: one side we grow the datasets, and on the other we develop the terminology, vocabulary that can be used 15:46:16 <edsu> cygri: DavidJames you asked whether we should do a vote, i'm not sure what point this would serve 15:46:33 <edsu> ... since there doesn't seem to be any strong disagreement 15:46:43 <cygri> ack DavidJames 15:46:48 <edsu> DavidJames: i think it would be nice to hear the agreement 15:47:22 <edsu> cygri: i think this is something i'd like to do on the next call, rather than rushing it 15:47:35 <edsu> ... to make sure there is enough time 15:47:49 <edsu> Topic: Use Cases 15:48:56 <edsu> cygri: we want to have use case or stories for what people want to be able to do: for example i want to be able to get a list of datasets from data.gov that are not supported by the current data.gov user interface 15:49:22 <edsu> ... i'd be interested to hear about what use cases people on the call have 15:49:32 <edsu> ... for standard formats for data catalogs 15:49:42 <Zakim> -LI_DING 15:50:41 <edsu> martin: i'd like to be able to query multiple catalogs, to be able to query other geographic regions 15:51:16 <vassilios> cross-catalogue querying 15:51:25 <edsu> cygri: so you want to be able to federate national catalogs into say a european union catalog? 15:51:47 <edsu> s/martin/vassilios/ 15:52:00 <edsu> vassilios: yes 15:52:21 <george> (fed/state/local) gov agency independently published catalog using (some set of standard) vocab for dynamic aggregation of catalogs 15:52:55 <george> would like to see bottom up (as per Li - in use) drive basic (extensible) rdfs vocab convergence for w3c blessing 15:53:00 <edsu> DavidJames: for the nationaldatacatalog we'd like to consume data from other data catalogs, we'd like to have one uniform way of getting at catalog data 15:53:33 <edsu> ... for municipalities and state governments we'd like to do a similar thing, enabling federation across many levels 15:54:38 <edsu> george: i think i share the interest that david and luigi have ; would be great to have some sort of vocabulary at the w3c that reflects what's in use as much as possible 15:54:42 <edsu> cygri: agreed 15:55:47 <edsu> martin: i think federation is soemthing i would like to do ; i agree with vassilios with his approach 15:55:56 <LI_DING> I was dropped from the call 15:56:46 <edsu> cygri: it might be a good next step to draft this use case as a little document, to sketch how it could look in practice as a story 15:56:47 <vassilios> i could help on this 15:57:14 <edsu> ... there are a couple of other use cases on the mailing list, maybe we can get those into written form too 15:57:27 <vassilios> OK 15:57:55 <vassilios> and i thin kit is more or less the same whether we speak about EU or USA 15:58:03 <edsu> cygri: would be great if you could start it, and we could see if other use cases are covered 15:58:33 <edsu> ACTION: vassilios to document a federation use case for dcat 15:58:33 <trackbot> Could not create new action (unparseable data in server response: No child element named 'id') - please contact sysreq with the details of what happened. 15:58:48 <george> +1 15:58:48 <LuigiMontanez> yes, I have access 15:58:50 <LuigiMontanez> +1 15:58:52 <DavidJames> +1 15:58:56 <edsu> +1 15:58:56 <martin> +1 15:58:58 <fadi> +1 15:59:03 <edsu> cygri: wiki is ok? 15:59:17 <cygri> 15:59:36 <edsu> cygri: great, there is a page where i've copy pasted stuff from the email, i propose we add subsections there, use this as a live document 15:59:53 <edsu> cygri: so that's it for this week, thank you all for joining in 15:59:56 <DavidJames> thanks 16:00:00 <george> thank you cygri 16:00:01 <cygri> thanks all! 16:00:06 <LuigiMontanez> thank you cygri, edsu for transcribing 16:00:06 <vassilios> thank you! 16:00:13 <Zakim> -George 16:00:17 <Zakim> -??P3 16:00:18 <george> thanks edsu 16:00:21 <Zakim> -LuigiMontanez 16:00:23 <Zakim> -fadi 16:00:25 <Zakim> -jonphipps 16:00:25 <edsu> np :-) 16:00:29 <Zakim> -edsu 16:00:31 <Zakim> -??P8 16:00:37 <Zakim> -martin 16:00:39 <edsu> RRSAgent, generate minutes 16:00:39 <RRSAgent> I have made the request to generate edsu 16:00:51 <Zakim> -bobbin 16:01:05 <cygri> ok, chairing a teleconference from a conference hallway is a bad idea. i won't try that again :-) 16:01:19 <edsu> cygri: heheh, any news from www2010? 16:01:21 <george> wish i was there! 16:01:29 <LuigiMontanez> LuigiMontanez has joined #egov 16:01:36 <bobbin> zakim? 16:02:08 <cygri> edsu, yes, many interesting things going on. great conference so far 16:02:10 <edsu> shoot, the minutes don't look to good 16:02:17 <edsu> 16:02:31 <cygri> bobbin, what do you want zakim to do? 16:02:51 <bobbin> +1 16:03:19 <edsu> cygri: it does look good 16:03:26 <edsu> (the conference) 16:03:40 <edsu> cygri: have you and Li had a chance to chat about stuff informally? 16:03:40 <cygri> edsu, the minutes look good to me? 16:03:51 <edsu> oh, they do look better now when i reloaded 16:04:02 <cygri> edsu, yes we had dinner yesterday and are planning a few things 16:04:08 <edsu> cygri: nice 16:04:26 <edsu> cygri: i think having you and Li on the same page will help a great deal 16:04:30 <Zakim> -??P7 16:04:31 <Zakim> T&S_EGOV(LD TECH)10:00AM has ended 16:04:32 <Zakim> Attendees were +1.202.955.aaaa, martin, George, +03539149aabb, edsu, jonphipps, +1.425.378.aacc, +03539149aadd, fadi, LuigiMontanez, +1.202.564.aaee, brand, bobbin, davidjames, 16:04:35 <Zakim> ... +1.518.495.aaff, LI_DING 16:05:19 <DavidJames> DavidJames has left #egov 16:06:27 <cygri> edsu, agreed 16:07:03 <cygri> will go now and see if they left any lunch for me 16:07:10 <cygri> thanks for scribing and the comments ed 16:18:33 <lindstream> lindstream has left #egov 17:16:50 <cygri> cygri has joined #egov 17:40:23 <ww> edsu: sorry wasn't able to make it today 17:41:05 <ww> would have liked to bring up the spatial/temporal ambiguity of dcat:granularity though 17:50:49 <DavidJames> DavidJames has joined #egov 17:56:42 <ww> cygri: do you think it would be reasonable to distinguish between spatial and temporal granularity/resolution in dcat? 17:58:11 <ww> (nevermind datasets that have different granularity on their different axes, which happens with some envionmental satellite datasets for example) 17:58:12 <cygri> ww, i'll have to talk to fadi to remember why we didn't distinguish them. can i get back to you about this next week? 17:58:27 <ww> sure no hurry 18:01:24 <Zakim> Zakim has left #egov 18:04:36 <ww> any thoughts on rdf:graph, rdf:Graph? 18:09:50 <cygri> ww, what are those? 18:10:21 <ww> well, they don't exist, which I think is problematic 18:10:51 <ww> using the talis changeset, vocabulary, for example, changes are expressed as additions and removals of reified triples 18:11:10 <ww> i need a way to express the graph that those triples are supposed to live in 18:11:19 <ww> (not strictly related to egov as such, of couse) 18:11:34 <ww> we have rdf:Statement, rdf:subject, rdf:predicate, rdf:object 18:11:40 <ww> but no rdf:graph 18:12:03 <ww> I suppose because I believe that named graphs were added after the rdf core vocabulary was etched in stone 18:13:19 <ww> for my immediate purposes I've invented a namespace for this, but... 19:33:35 <DavidJames> DavidJames has joined #egov 19:44:52 <cygri> cygri has joined #egov 20:54:51 <cygri> cygri has joined #egov 21:00:21 <cygri> cygri has joined #egov # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00000253
http://www.w3.org/egov/wiki/Chatlog_2010-04-29_Data_Catalog_Vocabulary
CC-MAIN-2014-15
refinedweb
3,213
64.24
In this tutorial, we’ll learn about Mock Service Worker and how we can use it to mock network requests. We’ll build a chat application that will use the mock data provided by the Mock Service Worker API. What is Mock Service Worker, and what problem does it solve? According to its official website, Mock Service Worker is an API mocking library that uses the Service Worker API to intercept actual requests. Using Mock Server Worker, it becomes very easy to get a mock server up and running. It’s based on the idea of Service Workers in order to capture requests for caching. It has the following features, among others: - Interception on the network level - Standardized Service Worker API - Supports both REST and GraphQL APIs - Execution on the client side - Supports TypeScript What we will be building In this tutorial, we‘ll be building a chat application that will have a list of users and a list of messages. The mock data for this chat application will be supplied by the mocks defined by Mock Service Worker. At the end of this tutorial, our application should look like the following: We’ll be using Next.js for building the application and Chakra UI for styling the application. Next.js is a popular React framework that supports server-side rendering and a lot of other features out of the box. More details regarding Next.js can be obtained from its official documentation. Chakra UI is a simple yet powerful component library for building React applications. More details regarding Chakra UI can be obtained from its official website. Create a Next.js application We can create a Next.js application using the following command: npx create-next-app The above command will create a new Next.js application and set up everything for us. After the installation is complete, we can follow the instructions present on the screen to start the development server. Adding Chakra UI to our Next.js application We can install the Chakra UI dependencies using the following command: yarn add @chakra-ui/core @emotion/core @emotion/styled emotion-theming Once the installation is complete, we need to update the pages/_app.js file with the following code: // pages/_app.js import { ThemeProvider, CSSReset, theme } from "@chakra-ui/core"; const App = ({ Component, pageProps }) => { return ( <ThemeProvider theme={theme}> <CSSReset /> <Component {...pageProps} /> </ThemeProvider> ); }; export default App; This will ensure that all the Chakra UI styles are now present in our application. We can now add any Chakra UI component to our application. Note: Adding Chakra UI is optional. It’s only used here to design a good-looking interface. For the sake of keeping this tutorial short, we won’t dive deep into Chakra UI components. Installing Mock Service Worker in our application Let’s add Mock Service Work to our application now. We can do so using the following command: yarn add msw --dev This will add Mock Service Work into our list of development dependencies. Since we don’t need any mocking of our data in production, it should be installed only in the development environment. Defining mocks Using Mock Service Worker, we can mock both GraphQL and REST APIs. In this tutorial, we’ll be mocking REST APIs. Let’s define the mocks for Mock Service Worker in a new file, mocks/handlers.js, with the following content: // mocks/handlers.js import { rest } from "msw"; import users from "data/users"; // contains mock data for users import messages from "data/messages";// contains mock data for messages export const handlers = [ rest.get("", (req, res, ctx) => { return res(ctx.json(users)); }), rest.get("/users/:id/messages", (req, res, ctx) => { return res(ctx.json(messages)); }), rest.post("/users/:id/messages", (req, res, ctx) => { const { message } = JSON.parse(req.body); return res( ctx.json({ id: Math.random(), message, }) ); }), ]; From the above code, we can see that we’ve created three mock endpoints, the data from which will be fetched on the server side by Next.js: GET backend.dev/users– this API endpoint is responsible for sending the initial data for showing our list of users. GET /users/:id/messages– this API endpoint will be responsible for sending the data for showing a list of messages. POST /users/:id/messages– this API endpoint will be responsible for sending the data when a new message is created. We’ll use all of these API endpoints in our Next.js application. Integrating Mock Service Worker with our application Now, let’s integrate these mock APIs with our application. To do so, we need to add a new file, mocks/browser.js, with the following content: // mocks/browser.js import { setupWorker } from "msw"; import { handlers } from "mocks/handlers"; export const worker = setupWorker(...handlers); The above file will be responsible for sending mock data on the client side. We also need to create a new file for sending mock data on the server side: // mocks/server.js import { setupServer } from "msw/node"; import { handlers } from "mocks/handlers"; export const server = setupServer(...handlers); The above two separate files are necessary because, according to MSW documentation, the same request handlers can be shared between browser and Node environments. Since Service Workers cannot run in Node, the integration process is different depending on the environment. We’ll also need to create another file, mocks/index.js, which will be responsible for figuring out whether to send data from the server or client. // mocks/index.js if (typeof window === "undefined") { const { server } = require("mocks/server"); server.listen(); } else { const { worker } = require("mocks/browser"); worker.start(); } The window object above is defined only on the client side. Leveraging this feature, we can easily figure our whether the data is being requested from the server side or client side. Next, we need to add import the mocks/index.js file in our pages/_app.js file: // pages/_app.js require("mocks"); .... const App = ({ Component, pageProps }) => { .... }; export default App; For demo purposes, we’re loading the mock data from MSW. In a real application, the mocks should be present only for the development environment. We can import MSW only on development by checking the NODE_ENV variable: // pages/_app.js if (process.env.NODE_ENV === "development") { require("mocks"); } .... const App = ({ Component, pageProps }) => { .... }; export default App; Finally, we need to run MSW’s init command to place the Service Worker in the public directory of our application. In the case of Next.js, the public directory is ./public. npx msw init ./public Fetching mock data from Mock Service Worker We’ll be building the user interface for fetching the users first. We can use the Next.js getServerSideProps method to fetch the data on the server side and then render it on the browser. To do that, we need to create a new file, pages/index.js, with the following content: // pages/index.js import React from "react"; const Home = ({ users = [] }) => { const usersNode = () => { if (!users.length) { return <>No users found</>; } return ( <> {users.map((user) => { return ( <div key={user.id}> {user.first_name} {user.last_name} </div> ); })} </> ); }; return usersNode(); }; export async function getServerSideProps() { const response = await fetch(""); const users = await response.json(); return { props: { users, }, }; } export default Home; Here, we’re fetching the mock data from the API endpoint on the server side and rendering on the user interface. The above code will render the following user interface: Now, we’ll develop the user interface for fetching the list of messages. When a user is clicked, we fetch a list of messages from the /users/:id/messages API endpoint and render it on the interface. To do that, we need to update our pages/index.js file with the following content: // pages/index.js import React, { useState } from "react"; const Home = ({ users = [] }) => { const [messages, setMessages] = useState([]); const handleFetchMessages = async (userId) => { // 1. Set the fetching state to 'true' to show a spinner // 2. Fetch all the mock messages // 3. Store the messages in the state // 4. Set the fetching state to 'false' to remove the spinner const response = await fetch(`users/${userId}/messages`); const messages = await response.json(); setMessages(messages); }; const messagesNode = () => { if (!messages.length) { return <div>Please click on any items from the left sidebar</div>; } return ( <div> {messages.map((message) => { return <div key={message.id}>{message.message}</div>; })} </div> ); }; .... return ( <> {usersNode()} {messagesNode()} </> ); }; .... export default Home; We fetch all the mock messages from the endpoint, then we store the data in the messages React state and render that array on the interface. Before the data is fetched, our user interface should look like the following: Once a user is clicked and the data is fetched from the API endpoint, our user interface should look like this: The different layers of our Next.js application are illustrated in the diagram below. All the Next.js pages can connect to the mock API of MSW and request for the data. Testing our application using Cypress We’ll write a couple of integration tests using Cypress. Cypress is an end-to-end JavaScript testing framework. It has a lot of features and is very easy to integrate with any frontend application. First, we need to install Cypress as a dependency: yarn add -D cypress The above command will add Cypress into our list of development dependencies. As with MSW, we don’t need any testing of our application in production, so it should be installed only in the development environment. Next, we can add a script to our package.json file in order to run tests using Cypress: // package.json { .... "scripts": { .... "test": "cypress open" }, .... } Now, we can run the following command to start Cypress from the root of our project: yarn test Please note that the development server of our application should be up and running since we need to run integration tests. It’s a good idea to run yarn dev in one terminal and yarn test in another. The above command will launch the Cypress test runner. Next, we can start writing our integration tests using Cypress. We need to create a new file, cypress/integration/index.spec.js, with the following content: // cypress/integration/index.spec.js context("Cypress Tests", () => { beforeEach(() => { // This will ensure that Cypress always visits our development server // before running any tests cy.visit(""); }); describe("User Interface Assertions", () => { it("should consist of 5 users", () => { cy.get("[data-test-id=user]").should("have.length", 5); }); it("should consist of 5 messages when any user is selected", () => { cy.get("[data-test-id=user]").first().click(); cy.get("[data-test-id=message]").should("have.length", 5); }); }); }); In the above code, we’ve written two tests: - The first test checks that there should be five users on the UI. - The second test checks that there should be five messages on the UI when any user is selected. Both of these tests should pass per our mock data. Conclusion In this tutorial, we learned about how easy it is to start mocking and using mock data from Mock Service Worker. The source code for this application is available on GitHub, and a demo is hosted on Vercel. Please note that the styles present in the demo application are due to the Chakra UI components. Also, a sample POST example is available in the demo application. All the mock data are present in this directory. LogRocket: Full visibility into your web.
http://blog.logrocket.com/getting-started-with-mock-service-worker/
CC-MAIN-2020-40
refinedweb
1,880
58.38
Python package to make it easy to use Isogeo REST API Project description Isogeo API Python SDK A Python package to use Isogeo REST API. Getting API keys API keys are required to use it. Send us your request by email. Getting Help There is a basic documentation about the Isogeo API. Installing To use: pip install --user isogeo-pysdk For developers: git clone git@github.com:isogeo/isogeo-api-py-minsdk.git cd isogeo-api-py-minsdk python setup.py install Quickstart from isogeo_pysdk import Isogeo # authenticate your client application isogeo = Isogeo(client_id=app_id, client_secret=app_secret) # get the token token = isogeo.connect() # search within catalogs shared to the application search = isogeo.search(token) # print some statements print(isogeo.SUBRESOURCES) # available sub resources print("Search __dict__ keys: ", search.keys()) # search response basic structure print("Search query parameters: ", search.get('query')) # search response query passed print("Total count of metadatas shared: ", search.get("total")) # total of available resources print("Count of resources got by request: {}\n".format(len(search.get("results")))) # total of resources returned by search request Samples are available in the source repository. For more details, please have a look to the documentation on Read the Docs. Tests Tests are performed for each published commit by Travis To run tests: pip install --upgrade -r tests/requirements_test.txt python setup.py install python -m unittest discover Build To package and upload: .\build_upload.ps1 To build docs: cd .\docs\ .\build_docs.ps1 Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/isogeo-pysdk/
CC-MAIN-2018-26
refinedweb
267
52.05
Java Application Development on Linux 428 The authors, Carl Albing and Michael Schwarz, chose to create a book that is a complete guide to writing commercial-quality Java programs. With the burgeoning presence of Linux, they focused on how to use the tools of the Linux platform to assist in the creation and maintenance of Java programs. They have broken the book up into five major parts: Getting Started, Developing Business Logic, Developing Graphical User Interfaces, Developing Web Interfaces, and Developing Enterprise Scale Software. Each chapter is self-contained, and the knowledgeable reader can pick and choose what they would like to read without losing track. Carl and Michael have properly started each chapter with a summary of what you'll learn, and conclude with a What You Still Don't Know section. A Resources section is included to give you more references for further study. Part 1, Getting Started, provides a 10-chapter overview of Linux, Java, the SDK's (Software Development Kits) from Sun and IBM, version control via CVS, and IDEs. The first two chapters cover enough command-line Linux to manage your files and directories, plus the Vi editor to create and edit your programs. Chapter 3 gives you a summarized but complete overview of the Java language (minus the standard classes), and Chapter 4 covers how the program can deal with the context in which it's running. The next two chapters cover Sun's SDK and (mainly for comparison) IBM's development kit. In some instances, the Java program may be so large and/or so complex that running the byte codes in the Virtual Machine may not be quick enough, so Chapter 7 describes how to use the GNU Compiler for Java (gcj) to create native-code programs. Larger programs definitely need some form of source control (actually, any project larger than a classroom exercise needs it), so source control using CVS is clearly laid out for you. While other products are available, CVS (Concurrent Versioning System) is widely available, robust, mature, and reliable, so the authors chose to describe its use in detail. For building and deploying the numerous files of a larger project, Ant provides value beyond what the make facility can offer, especially with the RMI (Remote Method Invocation) dependency problems that make can't address. Finally, Integrated Development Environments are covered. While Carl and Michael focus on NetBeans, SunONE Studio Community Edition and Eclipse are also covered. If the book stopped after Part I, you would still have a valuable addition to your bookshelf. However, it continues with a five-chapter discussion on how to properly develop business logic. One chapter is totally devoted to the business aspects of getting requirements, documentation, and buy-in. The next covers how to use a simple software development methodology to analyze the program and discover the objects to be created. The following chapter goes over a frequently overlooked aspect of programming - automated testing - with JUnit. The last two chapters of Part II cover storing data in databases using Oracle, PostgreSQL, and MySQL, and using the Java Database Connector (JDBC) to access them. While Linux users (at least the older ones like me) are more used to command lines, most users want some form of a graphical user interface (GUI) to access the program and their data. Chapters 16 and 17 describe how to create a GUI using Swing and the Standard Widget Toolkit (SWT). By far the most popular way to access programs is via a browser. Java Servlets are (maybe not so) little programs that run on the targeted web server, relieving the user of having to install an application on their local computer. This allows the user to always have access no matter which machine they're on (how many times have you complained that the program you want is on the PC where you're not?), and to always be accessing the latest version of the software (assuming the web administrator keeps it updated on the server). Chapters 18 and 19 cover Servlets and JSP (JavaServer Pages), then Chapter 20 describes Java-based web application servers (JBoss and Geronimo) for serving the servlets. Finally, Part V covers Enterprise JavaBeans (EJBs) in what the authors describe as an almost criminally brief introduction. While it is definitely an overview, they still cover more than enough about EJBs to get you rolling, and provide many references to where you can fill in the blanks. They wrap up the book with a plea for help. The book is an Open Content book, and therefore they are requesting comments, suggestions, and patch files to help improve the text and examples. I have to admit that Java Application Development on Linux. You can purchase Java Application Development on Linux from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. I'll be the first to quote Bash... (Score:5, Funny) Re:I'll be the first to quote Bash... (Score:2, Funny) Re:I'll be the first to quote Bash... (Score:2) Re:I'll be the first to quote Bash... (Score:5, Insightful) if you're old enough to remember back that far, you will recall that when k&r released the c language, on of the big "selling points" was that it was a hardware/os agnostic language. you could write applications in c for a variety of different operating systems running on lots of different hardware and even re-use code, libs and entire applications (so long as you had the compiler, obviously). the "write once" mantra has been with us for 30+ years... and, in that regard, java beats the living pants off the other contenders. Re:I'll be the first to quote Bash... (Score:2) Re:I'll be the first to quote Bash... (Score:2, Informative) Re:I'll be the first to quote Bash... (Score:2) Only because you can install multiple virtual machine revisions in parallel. Actually, this is cheating, as it increases the maintainance overhead. Working on a java app now (Score:5, Interesting) The advantage: Java has abstracted alot. The downfall: Java has abstracted alot. For anyone who has done alot of programming in Java, they will understand. Re:Working on a java app now (Score:2) Re:Working on a java app now (Score:3, Insightful) When I programmed in Java, it wasn't Java itself that was the problem with respect to abstraction, it was the dime-a-dozen here-today-gone-tomorrow APIs that appeared on the cover of JavaPro. My co-workers would get all hot and horny over some new API only to have it backfire due to bugs, high volatility between versions, or the API just solving the problem terribly. Java itself is actually quite good, and Sun makes an good effort with it. However, with popularity came idiots, and with idiots came the AP I hope the book has a section on porting.... (Score:3, Interesting) Re:I hope the book has a section on porting.... (Score:4, Informative) I think you'll find that the java.nio classes are actually non-blocking IO, not native IO. And in all my years developing Java on AIX, Solaris, Windows, Mac, and Linux, I've yet to come across a platform specific class (at least in the core APIs or any API written in pure Java - JNI excluded). In other words, there are no OS gotchas. There are, however, app server gotchas, but that's a different story. Bob Re:I hope the book has a section on porting.... (Score:3, Informative) Re:I hope the book has a section on porting.... (Score:3, Interesting) Re:I hope the book has a section on porting.... (Score:2) As far as NIO, the only problem I know there is that you cannot select more than 64 objects on windows, which is MAX_WAITABLE_OBJECTS on WinNT/DOS. Eclipse? (Score:4, Insightful) BTW. the ret of my project was Java for a HP iPAQ 5555 which, interestinly enough was developed on Windows using IBM websphere device developer, which is based on Eclipse Freespirit Re:Eclipse? (Score:4, Informative) IN Java not WITH Java (Score:2) The IDE Issue... (Score:5, Insightful) While Carl and Michael focus on NetBeans, SunONE Studio Community Edition and Eclipse are also covered. Editing Java in vi is one of the biggest waste of time I can imagine. Eclipse and Intellij are far far more productive environments in ways that are too numerous to describe. I think a Java development on Linux book should really ignore vi and just be an Eclipse centered tour at this point with a little bit of documentation on bash usage , scripting, deployment issues and tuning the environment. Re:The IDE Issue... (Score:2) Yea. /me puts on flame-resistant suit You should use EMACS, of course !!! Re:The IDE Issue... (Score:3, Interesting) Re:The IDE Issue... (Score:5, Informative) You *really* need to have a look at Eclipse. Debugging is nice, but it's not the whole crop. What's at the top? It understands your code. The first thing you'll notice is the incremental compilation. You don't have to ctrl-z (or alt-tab or whatever) and run the compiler and wait. It compiles it as you're typing, and tells you where you've screwed up. That improves your efficiency right there. Next on the list is lint-checking. This starts with needless imports, and continues with warnings for unused private methods, empty and undocumented catch blocks, and a host of things that are easily missed. It's a real eye-opener to load up your vi-edited code into Eclipse and see the cruft. Last, and most powerful of all, is refactoring. I can, with that dreaded mouse, move a class between packages far faster than you can even if you're a regexp wizard. I can rename variables and methods without fear. In short, I can do everything I need in order to make sure that the codebase makes sense. No more comments like, "This method doesn't do this anymore, but it's too much hassle to change its name" Knowing that classnames and packages aren't set in stone, you are much more free to get to writing the code, and change what you need to change, as you discover the need to change it. If I had to guess, I'd guess that you tried JBuilder, didn't care for it, and haven't looked back. Eclipse is so radically different from that environment that its almost miscategorization to call it 'an IDE'. -Zipwow Re:The IDE Issue... (Score:2) I do find I tend to have an IDE open AND a shell prompt AND a decent (tabbed) window based text editor. As you point out, IDEs can be a bit clunky for many simple uses. ~Cederic Re:The IDE Issue... (Score:2) -Zipwow YMMV (Score:2) ma to mark the start of the block j as many times as it took to get to the end of the block, counting in my head as I go 'a to return to the top of the block Then in another window, or after exiting and running vi on the second file. move to where you want the block of code That is so much faster than Copy, Paste. I used vi for years. Then I leared emacs and enjoyed the directory navigation and being able Re:The IDE Issue... (Score:3, Insightful) My team is working on a serious project right now (it will be responsible for > $20 million in annual revenue when launched). We've used the refactoring feature in the past without issues. We also build every single time someone does a commit (using CruiseControl). Our policy is nobody leaves for the day if the build is broken. We've had no problems at all with the "twerps" you seem to have. Sounds like you might want to bitch slap some of your devel Re:The IDE Issue... (Score:2) Re:The IDE Issue... (Score:2) Perhaps for experienced developers, but for those just getting familiar with Java, you can't beat a text editor. IDEs obscure too much of what's actually going on. If you learn java with an IDE, you'll likely find it difficult without one. But then, "graphical programmers" seems to be the big rage these days. Re:The IDE Issue... (Score:2, Insightful) Me too. But I suspect the book covered vim, not vi. That's a modern, good programmer's editor. Personally, I've used Emacs for all kinds of text editing for ten years, and I can't see why I should learn another, inferior one just because I happen to be programming in Java rather than C, C++, Python or Perl at a certain point in time ... Re:The IDE Issue... (Score:2) How about, "I've been developing Java programs since JDK 1.0 Beta 2 came out, and every project I've seen where GUI builders were used had problems as a result." No, seriously. I'm not Re:The IDE Issue... (Score:2) An AC ?? And you want an answer?? Ok, try this : create a GUI with the Visual Editor plugin. ( BTW, since everything in Eclipse is a plugin, is use of the word plugin redundant? ) Now, open one of the generated code objects. Edit it to include some sort of functionality not there... like add a focus listener to a text field or put a label somewhere or something, whatever you want, i Re:The IDE Issue... (Score:2) when you get used to vim, really used to it, you can't live without it. and yes, it does code completion. sadly java is so verbose that it kinda makes vim hard. i have very little c experience, but have done alot of work with perl, python, and php. for scripting languages, especially like perl, it's invaluable. not a user of emacs, but i'm sure it's the same. however, vim is great for alot of 2-3 class java solutions, and even larger ones as well. not everyone writes huge enterprise a Re:The IDE Issue... (Score:3, Informative) The Java trap (Score:2, Interesting) Re:The Java trap (Score:4, Insightful) Re:The Java trap (Score:2) Posting links to anything remotely related on GNU.org is an easy way to get modded up. Re:The Java trap (Score:2) Jesus, Stallman can talk a load of crap. Most people use an OS, program, language, whatever because of the *benefits*, not because of some ideology. Stallman can really come across like a religious fundamentalist sometimes. Is he seriously suggesting that no-one should ever use any proprietary software? So what if Java isn't licensed under the GPL? And then there's this:- If you develop a Java program on Sun's Java platform, you are liable to use Sun-only features without even no Re:The Java trap (Score:2) That's not an argument: Most people do foolish things. More specifically, things that are easy in the short-term, but may hurt in the long-term. (Most programmers don't use version-control systems, which is really scary!) One example: putting all you documents in a proprietary undocumented format so your documents are at the mercy of one company. Another example is writing your programs in a proprie Re:The Java trap (Score:2) Sounds pretty wide-ranging (Score:5, Insightful) * Basic Linux (files, directories, vi) * Basic Java (two different SDKs) * Basic software development (requirements gathering, et.al.) * Basic programming (CVS, build tools) * Basic Web programming (servlets, presumably JSPs, no Struts/Spring/other frameworks) * Database programming (Oracle AND PostgreSQL AND MySQL) * And finally, Enterprise Software in the guise of EJBs (remember: friends don't let friends use Entity Beans!) Granted it's 600 pages, but I'm wary about how much real detail they can pack into all those topics. I'm guessing this won't be much of a reference book, but rather a large collection of introductions to a variety of Java topics. Commercial quality apps? (Score:3, Insightful) Re:Commercial quality apps? (Score:2) "Commercial quality" and "Open source" are two different possible aspects of a piece of software. Don't fall into the FUD trap, there are plenty commercial quality open source applications. There are also plenty of commercially sold open source applications. There's nothing wrong with that. - Erwin Re:Commercial quality apps? (Score:2) Switched to apollon and never looked back. Stick to FREE Java for your own protection (Score:2, Troll) While the gcj toolchain is not capable of supporting bleeding edge features, its likely you do not truly need these so the gcj baseline will also hold you to a sane subset of proven Java features. Re:Stick to FREE Java for your own protection (Score:2) As far as I know, mingw should be able to compile windows binaries. Apache Gump is the nightly status of OSS (Score:2) Look at [apache.org] This is a nightly check out and build of all OSS projects in Gump. It is slowly coming together, as now the projects are putting in tweaks to work better with the kaffe toolchain, pulling out any naughty use of sun.* code, etc, etc. The goal is simple: all the Apache and other main OSS projects, built with OSS libraries, on an OSS JVM. One day, we shall be truly free... success largely depends on expertise (Score:3, Informative) Our product that runs on Linux/Solaris/AIX/Win32 also runs wonderfully on OS/390, but this is only AFTER the code base was revisited to respect that fact that a 390 is EBCDIC. For example, ASCII config files that you ship along with your distro to the 390 will be read in the system default encoding if you're using plain Readers. You'd want to use streams with an explicit encoding type. Or, just use XML since the parsers internally understand UTF-8. So, some may say "debug everywhere" but in some cases this isn't being completely fair, if you're placing the whole blame on the JVM. Re:success largely depends on expertise (Score:2) Best java gui tk for linux (Score:3, Insightful) Java-Gnome binds gtk with java. Very nice. Java -- the abusive relationship (Score:5, Funny) Oh yes, it was sooo much better than VB if you can get past the quick way to make graphical interfaces. The multi-threading made creating a multiplatform port-scanning tool so much more pleasurable. Then there was running the code on multiple platforms. The need to install the JRE, ensure you're pointing to the right CLASSPATH, and all those somewhat cumbersome things. Yeah, after a while, I forget those experiences. I come crawling back, not wanting to be assimilated in I'm sure it's going to take time and effort, and I know I need to put more time in our relationship. Right now, though, I'm in the middle of a project with PHP so I'll get back to you when I can. Just remember, Java, that it's not you...it's me. P.S. -- I think your father's a prick. I wonder (Score:2) Java and Linux (Score:4, Interesting) I usually do my development on OS X (except for new JDK 5 coding - use my Mac as an X display for a Linux box -- annoying that Apple is slow getting JDK 5 out except for in a $500 developer's preview). Anyway, I do most of my deployment on Linux, and the ease of this depends on which hosting company I am renting a server from. For example, is a usable (i.e., PostgreSQL) database installed, easy to administer, etc. I have not read the reviewed book, but hopefully a lot of practical issues are addressed. One interesting thing about the Linux platform is that now all new distros have RPMs (or equivalent) for installing runtime and developer support for GNU GCJ. I find GCJ to be very interesting (a bit of a nuisance to run on OS X) because not only is it a way to run Free Software (GPL) on Linux, but it also makes it possible to take large Java applications like Lucene, compile them natively, and then use the compiled code in Python, C++, Ruby, etc. programs. Very cool, really. If Linux was my development platform, GCJ would be a much more important tool for me - it would be great if Apple installed GCJ runtime libraries by default (yes, they are large). While Java is not as productive a language for many programming projects as Python, Ruby, etc., Java is a great language and platform for many types of projects; having GCJ runtime installed by default on OS X, Linux, and Windows (well Credit where credit is due. (Score:3, Insightful) I've recently worked on a J2EE project with nearly 1 million lines of code -- they're all needed, really Have there been platform related bugs? Yes. Are there any open? No. Are there some lurking? Maybe, but we've tested extensively. Could any collection of jackasses build this app? No, sorry. Is Java a magic bullet? No more than any other tool. Mod parent up! (Score:2) What about make and emacs? (Score:2, Interesting) At my last job, back on 2002, ant forced me to hate it when: 1. I had to get the next version of ant to ask it to pass a -ea to the java compiler. 2. We had this crazy huge build.xml file that was created for our project. It started off life as a rats nest and only got worse from there (OK, probably not ant's fault but it had the same effect on me). On top of it being huge, its in XML which is way hard to read compared to a ma Re:What about make and emacs? (Score:2, Informative) Ever try Maven [apache.org]? build.xml files tend to get crufty. Maven builds are sleek, particularly if you write your own plugins to handle the odd bits. And the mevenide integration with both Eclipse and Netbeans is almost flawless. Re:What about make and emacs? (Score:2) -ea? Its not a javac option. And you can add any compiler argument like with the tag. Maybe you mean the -ea enable assertions feature of the java program. yes, that didnt come out till after java1.4, but you could still do it by hand. 2. If you dont know what you are doing, yes, ant can be an ugly mess. So can make. 3. Echo the compile command line. Every try "ant -verbose"? I'm not sure it does, but remember that a Re:What about make and emacs? (Score:2) For people under the age of 40 Make is incomprehensible, unintuitive and full of quirks that make so sense. Or maybe that's just me. If you want 30 or so small, easy to read/understand Ant build.xml files, all controlled by a single daddy build.xml file, go right ahead - the tool supports it just fine. And it'll still be fast. If you want them really really easy to read, I'm very concerned. You shouldn't need to be messing about with them - write them, get them working, leave them alone. Constant fiddling i Re:What about make and emacs? (Score:2) You could've used exec and ran javac, which allows you to specify any worldly command line argument you wish. Ant allows you to import other buildfiles in a namespace-aware fashion. This allows you to create multiple build files, and access them from a top-level build file that imports the smaller buildfiles. Re:What about make and emacs? (Score:3, Insightful) Same tools on both (Score:2) Java on Linux Topics That Really Need Covering (Score:5, Insightful) None of the topics mentioned in the review really seem to be Linux specific. Why not just call it "Java Application Development" (period, no "on Linux")? There are some things that I think would be worth covering though, in a book about Java/Linux. Particularly for someone coming from a development of an app in a Windows Environment to deploying an app in a production Linux environment. Since often they will know all they need about Java. But won't be very familiar with Linux. And may not know the best way to do things in a 'Linux' way. Some examples... Init Scripts: Setting up init scripts to stop/start your Java services (e.g. getting tomcat to run on boot up). That differs a lot from how you'd do it with services on Windows. Permissions I: Often on windows things will be run as root/Administrator. On Linux the better way is to have Java services run as a non-root user. e.g. run Tomcat as tomcat not root. There are some implications to this. e.g. you an unprivileged user cannot listen on addresses with sub-1000 port numbers. The solution is something like iptables or mod_jk2 [rimuhosting.com]. Permissions II: Another permissions issue (that I see crop up a lot with people moving from the Windows dev machine to one of our Linux servers for productions) is file permissions. Users being not being able to read/write config/data files that they had been able to see/use well enough on Windows. i.e. a paragraph on the almighty chown -R would be handy. Command Lines: A page or two on running things from the command line would be a great thing. Often people working on Linux servers are doing so remotely. And won't have a GUI. And often they are only familiar with launching their app from the ide. So knowing about 'java' and 'javac' would be handy. And mention the need for colons between dir names not semi-colons. e.g. java -cp /myclasses:/3rdparty.jar mainclass. Automating Tasks Users moving from a windows/dev environment to a Linux/production environment would also be well served by a page or two on automation tools. e.g. using ant to automate the process of getting code out of CVS and deploying it. e.g. cron for automating the process of running Java jobs on a regular basis. -- Java Hosting on Linux, Simple Enough Even For Windows Users [rimuhosting.com] Re:Java: I love it, but... (Score:5, Informative) I can't remember the last time I had issues with code because I changed platform, OS, or even JVM version. It's to the point where I don't think about it anymore. Maybe if you're talking GUI code (desktop/applet), but for web or backend it's just not been an issue for me in some time. I've been developing on Java professionally for nine years now, and have have production systems in place for eight. I remember when you used to need to test every single VM, but by and large that time is done. For example, I just finished working on a project running on J2EE 1.2 on Websphere 4 (jdk1.3.1) on Windows to running Websphere 5 (jdk1.4.1) on Z-Linux. The *only* thing I had to change was code that was written out of spec (a few JSPs forgot to import java.util.Vector). If the developers of the app hadn't been sloppy, there would have been no code change at all. This is an app that hits databases on Oracle, DB2, Teradata, and LDAP (with updated drivers for all of those, too). I can think of plenty of counterexamples, but for most server-side business apps it really is write once, run anywhere. Re:Java: I love it, but... (Score:2) The GUI issues seem to be limited to areas where you bunt up against a platform limitation. Like using second/third mouse buttons on a mac, or failing to use the File class properly. They are usually self inflicted. The only real issue I ever had was with drag and drop flakyness under win32. I assume this thread will attract the usual Re:Java: I love it, but... (Score:2) I don't love Java. All things considered, I don't see that their efforts at cross-platform compatibility are really a big win over things like the Standard C Library. In both cases, you have a language and a supposedly cross-platform standard set of library calls, and in both cases you end up having to code around the quirks of the platforms you run on. I think the right place for Java to have targetted, the place where it could have been the most useful, was as a client-side platform-indepedant environm Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:5, Insightful) Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:2) What you call 'sysadmin stuff' is the thing that has to be repeated thousands of times (once on every computer your app is installed). If you had to spend 1 hour more with the code and 1 minute less per machine with 'sysadmin stuff' you would save lots of people lots of time although you might have to invest a little more. Java isn't bad because of issues at compile-tim Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:2, Flamebait) Re:Java: I love it, but... (Score:3, Interesting) We have hardly ever had any issues with "Write once, run everywhere." It works. Really. Probably writing Swing/GUI apps is different, but on the server side, developing and deploying across different platforms works like a charm. Admittedly the issues you get on development vs. production c Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:2) NetWare 5.x Windows NT Windows 98 Windows XP Windows 2000 Solaris 7-8 Linux (various versions and distro's) Linux 64 bit (SuSe for X86-64) IPAQ (small apps, not much experience) Palm OS (again small apps not much experience) Macintosh OSX 10.2 and 10.3 and i am now looking at Re:Java: I love it, but... (Score:4, Informative) I have coded a wide range of applications, and have used many of the facilities provided by Java. NIO was the only part of the standard library that gave me trouble. However, I have a friend who was using Java3D for a project. His jobsite uses pretty much the gamut of operating systems. He has told me that Java3D is just plain not portable. Code that worked on Windows would not work on Solaris. I have no details on this, but they ended up using something else, according to him. Re:Java: I love it, but... (Score:2) Re:Java: I love it, but... (Score:3) Re:Java: I love it, but... (Score:2) 1 MegaLOC. 36 megs of Java source. Swing, JSP, Servlets, SOAP, SOA, Kerberos, LDAP, JDBC, and EJBs (to name just a few). Our newest clients are C#. 4 years I've been working on it. I'm one of 4 developers using Linux. The other 20 or so use Windows. We deploy to Windows 2000, XP, Solaris, SuSE, Debian, and RedHat on the server side, an Re:Java: I love it, but... (Score:4, Insightful) Yes, I know you could argue that "C" fits this bill nicely, too, but the fact is that most corporate IT shops at the time were VB and PowerBuilder clients talking directly to databases. Your average corporate developer would do more harm than good with C, and Java was seen as a simplified C++. Anyway, I don't know if Gartner ever changed its stance on this, but the reality became quite different with the introduction of J2EE; J2EE required quite a different set of skills compared to good ol' J2SE, and many developers still can't adequately grok distributed server-side development. Java is just a language, and I firmly believe that more attention needs to be given to the art of programming rather than to any specific language. It seems nobody cares anymore for appropriate use of patterns and careful selection of algorithms. It's all brute force programming. Get it done. Here's your soup - go code. You can learn all the languages you want -- learn to speak English, Russian, Spanish, French, Hebrew, German and Greek -- but if you don't know how to communicate... Re:Java: I love it, but... (Score:3, Insightful) And for example C++, it should be "write once, port anywhere and then test anywhere"? At least with Java, you can skip one step. Re:Java: I love it, but... (Score:5, Informative) Anything written for java 2 (1.2 and up) should work fine on the latest 1.4.x, and will probably work fine on 1.5 (I have had some funny issues with 1.5, but they were build time issues) The only thing I've encountered that actually broke stuff in a version change was the bizarre choice by Sun to not just deprecate reading the OS environment, but to completely disable it by causing it to throw a runtime exception in 1.4 They changed their mind and re-enabled it and un deprecated it for 1.5 though. Re:I'd rather have... (Score:2) There are a huge bevy of tools for dealing with this for C. Other compiled languages have similar problems. With Java all of that goes away: you know whatever problem crops up, it's definitely not the build, because you did that once, at your location, and gave everybody the same binary. Re:I still fail to see .. (Score:3, Funny) What's wrong with Re:I still fail to see .. (Score:2) Re:I still fail to see .. (Score:3, Insightful) (Just as a side note, the weirdest porting problem I had was the result of someone who shall remain nameless assuming that all filesystems are case-sensitive. I unpacked the source tar onto an HFS drive and spent ages trying to work out why Wow... that's just troll-tastic! (Score:2, Insightful) I congratulate you on providing one of the best examples of trolling [wikipedia.org]I've seen in a while from a non-anonymous post. Let's see if you've covered the basics: Congratualations... you're a winner! All sarcasm aside, if you don't like Java and don't develop software in Java, then a book Re:I still fail to see .. (Score:2) As a troll though, congrats I guess. Re:I still fail to see .. (Score:2) I think that's also a bit more than flame bait. I'm learning both C and java. C is lower level, but at least I find it easier to write and read. And I don't have to worry about classes, filenames capitalized, commands that are extremely long and have so many "." and other weird things going on Binary Programs are not always appropriate (Score:2, Insightful) Portability - You can't run C and C++ in a web browser very easily. In an enterprise environment, or even on the internet, you need to be able to distribute your application quickly. No one likes having to download a program from the Internet, especially in the days of spyware and adware. Allowing people to just run your pro It ain't just the compiler, Luke. (Score:2, Informative) Java comes with portable GUI libs. Re:I still fail to see .. (Score:3, Informative) Although you can decompile java byte code with some degree of success, obfuscators exist which can be applied to the byte-code before you distribute it to make decompiling nothing but a waste of time as the code is irrevocably incomprehensible (and some byte-code obfuscators mess things up so bad that the decompiled code won't even compile at all!) Use of such obfuscators is not bad programming practice in the same way that obfus Re:I still fail to see .. (Score:3, Interesting) Close, but no cigar. If there are enough binaries for the different platforms, you might not need the code. The bigger problem is that people tend to stack libraries - e.g. on the Windows libraries. That will really get you stuck. The thing about java is that everyone is forced to distribute "source", or more Re:Write once, run everywhere is called GCC (Score:3, Interesting) Which, amazingly enough for a lie, I am now using to rewrite some of our inhouse utilities in preparation from the move from Win2k to Linux servers. There's not too much overhead on CLI Java programs, and I've ported one app so far, rewritten on my Windows box, and it ran without a single hitch on the Linux server it's destined for. No recompiles, no nothing. Re:Write once, run everywhere is called GCC (Score:2) Which linker? Which version of libc? Linux or UNIX headers? C is technically the most portable language ever, but it doens't make it trivial. People say "test everywhere" as if that's supposed to make Java look bad, but I think it is a god-send relative to hacking up the C preprocessor and figuring out autoconf. Re:Run everywere, my ass. (Score:3, Informative) If you are running OSX 10.3 you are running a very new version of the JVM. If you are running OSX 10.2 you are also running a very new version of the JVM. So I guess my question is what OS are you running on it? Now you mention that you don't "miss" Java. I will argue that you don't care what an application is written in, as long as it looks good, is stable and does what you want. So I challenge you with this. How Re:Run everywere, my ass. (Score:3, Informative) Re:Run everywere, my ass. (Score:2) I think what you are really saying is that you don't want some piece of crap C program thats big and bloated nor do you want a JAVA program that is big and bloat Re:So...? What's the big deal? (Score:2) it would be nice to see how to talk to KDE or Gnome. Hey, it would fantastic to see someone telling me how to get drag and drop in either system to integrate with a swing app. Plus something on how to do JNI code. We actually have a chapter doing that for both Windows and Linux in (product placement) Java Development with Ant; using Ant to compile then run some C code that reads the P5 real time clock, and so work out the round trip time. It isnt hard, just fiddly. That is what I want with a Java on Li Re:"Commercial quality"? (Score:4, Informative) That is the fault of the programmer, not the language. Chapter 2: Meanlingless error messages The application programmer decides the error messages. Uncaught exceptions might show to the end user, but if you don't understand these, show me a language with clearer error messages? "ArrayIndexOutOfBoundsException? FileNotFoundException? MidiUnavailableException? What does this mean, I do not understand any of this. Owie my brain hurts...." Oh, and it is spelled "meaningless". HTH. Chapter 3: Remaining slow no matter how fast the hardware is. Chapter 4: Losing data. And finally: Chapter 5: How to create the blue screen of death. Hmm...seems I just responded to a troll.
https://news.slashdot.org/story/05/01/25/1840259/java-application-development-on-linux
CC-MAIN-2016-44
refinedweb
6,654
73.27
Find all triplets with zero-sum in C++ (Hash Tables) In this C++ tutorial, we will learn to Find all triplets with zero-sum in C++. To solve this problem in this tutorial we are going to use hash tables. Introduction In this problem, we have to find triplets with sum equals to zero. This means if we have three elements x,y,z. And we add them we get zero as our result i.e x+y+z=0. There are many ways to solve this problem. One of them is to run three loops and find each element one by one. The problem with this method is that it has a time complexity of O(n3). This is a very high amount of time for a problem and if we increase the size of the array its time increases very high. Another method for solving this problem is to use Hashing Table. Hashing is a method in which the value is saved with the index and can be retrieved very fast. In this tutorial, we are going to solve the problem using hash tables. Program to find all Triplets with zero-sum in C++ #include<bits/stdc++.h> using namespace std; void triplets(int arr[], int n) { bool found = false; for (int i=0; i<n-1; i++) { unordered_set<int> s; for (int j=i+1; j<n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { cout<<x<<arr[i]<<arr[j]; found = true; } else s.insert(arr[j]); } } if (found == false) cout << " No Triplet Found" << endl; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } triplets(arr, n); return 0; } Input and Output Enter the number of elements : 4 Enter the elements 2 -2 0 1 -2 2 0 In the above code Firstly we enter the number of elements in the array. Secondly, function triplet is called with arguments one array and another one is the number of elements in the array. Further, the function runs and print the triplets. The function triplet Firstly creates an unorderd_set which is also called a hash table. After that values are traversed to check if it is a triplet. On the other hand, if it does not satisfy that condition then the item is added to the table. Finally, this method is faster than the three loops is takes O(n2) time. Which is much faster. Conclusion This method is Hash Tables (unordered_list) is very versatile. We can use hash tables in many different places in problems where we have to count or the number of items is required. Also Checkout: How to sort a Matrix in C++
https://www.codespeedy.com/find-all-triplets-with-zero-sum-in-cpp-hash-tables/
CC-MAIN-2020-40
refinedweb
454
80.92
With the new use of C++ namespaces in the 3.7 API, is it possible for an Out-of-tree (OOT) module to create blocks that are part of an existing GR namespace? For instance, if I have a new block that processes digital data streams, can I create an OOT module called "digital" and add my block to it? Or will this cause a confusion at link time, by creating two libraries with the same name? @(^.^)@ Ed on 2014-05-02 16:33 on 2014-05-02 16:43 Hi Ed - Are you asking whether you can reuse the same namespace and block name with an OOT module? If so, then so long as you don't load the library containing the GR-provided block(s), you can make it work -- it's a C++ issue rather than anything else. That said, it would generally be better if you named your block something else to help distinguish it from what GR provides -- unless what you want is intentionally a drop-in replacement for what GR provides. In C++ you can add to a namespace if you want to, so long as what you're adding augments, does not conflict with nor try to replace, what's already there. Not sure if this is what you were looking for, but maybe this helps? - MLD
https://www.ruby-forum.com/topic/4567043
CC-MAIN-2017-13
refinedweb
224
73.41
Most of you likely already know this, but I've seen 2 customers that were confused by this but I forgot to post this back then. The idea is that they were avoiding the use of static fields because they had the belief that the static fields in all the types in an assembly were initialized (if they had initializers) when the assembly loaded instead of when the type with the static fields was first referenced. This makes, for the typical class, a very nice and simple singleton class. Sure, if the class has things in it (like a public const or something) that you can access and don't need an instance around, then accessing those things will create the singleton instance sooner than needed, but I avoid putting such things in my singleton classes in the first place, although maybe that's just me :) Main is running, yay!Instantiating my singleton7 + 3 = 10Main is done running, boo! Main is running, yay!Instantiating my singleton7 + 3 = 10Main is done running, boo! using System; class Program { static void Main(string[] args) { Console.WriteLine("Main is running, yay!"); MySingleton.Instance.Foo = 7; MySingleton.Instance.Foo += 3; Console.WriteLine("7 + 3 = {0}", MySingleton.Instance.Foo); Console.WriteLine("Main is done running, boo!"); } } public class MySingleton { private MySingleton() { Console.WriteLine("Instantiating my singleton"); } private static readonly MySingleton m_instance = new MySingleton(); public static MySingleton Instance { get { return m_instance; } } public int Foo { get; set; } }
http://blogs.msdn.com/b/jmanning/archive/2008/02/06/a-type-s-static-fields-don-t-get-initialized-until-the-type-is-referenced.aspx
CC-MAIN-2015-27
refinedweb
239
56.66
23 April 2010 12:27 [Source: ICIS news] (Recasts, clarifying headline) LONDON (ICIS news)--Polypropylene (PP) buyers in Europe will face more price increases in May as producers formulate plans after the May propylene contract was settled up by €20/tonne on Thursday, sources said on Friday. The new monthly monomer contract was settled at €1,000/tonne FD (free delivered) NWE (northwest ?xml:namespace> “We are looking to improve the spread between propylene and PP by €25/tonne,” said one major producer. Another with similar expectations said: “We are looking to increase prices by about €50/tonne in May.” A third said it would be looking for a three-digit increase, but several market sources said this would not be feasible as some other producers were aiming for less. PP buyers were not happy with the current situation. Prices had risen already by over 30% in 2010, and several reported that they were finding circumstances very tough. "We will bend our backs and weather the storm,” said one buyer. “Prices will clearly be higher in May, but I think we are seeing the top.” May was widely seen as a sellers’ market largely due to reduced availability rather than strong demand. Sales volumes had picked up, however, and small technical issues in One major producer reported strong demand growth in April, at the same time admitting that the recovery was still fragile. “We have had our strongest demand month since October 2008,” said a company source. “What was unusual was the strength of demand in the last week of March, as it became clear that April prices would go up.” Some producers expressed sympathy with buyers, but said they too needed to make some money. “It’s true. Our customers need to breathe. We wanted a rollover in May propylene, and we need to get a bit of a margin increase,” said one. There was a widespread feeling among buyers that prices were getting close to the top of the cycle. “We have enough stock to go without buying from European sellers until July. I think the current stronger demand is based on stock-building and that will come to an end soon. If crackers are running flat out, we will soon see the shortages end,” said another buyer, who had bought some imported product that was due to arrive in Net PP prices were still in the region of €1,200/tonne FD NWE for homopolymer injection in April, but new offers for May were already available on companies’ website. New prices from LyondelBasell’s web-based sales platform, Alastian, are already higher, a buyer said. “Copolymer has gone up to €1,325/tonne plus delivery from the April level of €1,260/tonne [plus delivery]. Homopolymer’s the same - up to €1,235/tonne plus transport,” the buyer added. Buyers felt that May would remain a sellers’ month, but they envisaged better opportunities as the year progressed, expecting lower propylene prices in June and July, to be translated into lower PP prices. They also expected new capacities from Asia and the PP producers in ($1 = €0.75) ?xml:namespace> For more on PP visit ICIS chemical intelligence For more on LyondellBasell and other PP producers visit ICIS company intelligence To discuss issues facing the chemical industry go to ICIS connect
http://www.icis.com/Articles/2010/04/23/9353516/europe-pp-producers-seek-more-hikes-in-may-on-tight-supply.html
CC-MAIN-2014-35
refinedweb
553
59.33
t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. The following example from the GenericList<T> class shows how to use the default keyword. For more information, see Generics Overview. public class GenericList<T> { private class Node { //... public Node Next; public T Data; } private Node head; //... public T GetNext() { T temp = default(T); Node current = head; if (current != null) { temp = current.Data; current = current.Next; } return temp; } }
http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx
crawl-002
refinedweb
128
68.57
The new release features support of VC++ 6.0/7.0/7.1/8 (tested on VC++ 6.0 SP 6 and VC++ .NET 2005 beta) and Linux support (tested in Feudora Core 2 distribution). Unfortunately, I was not able to test it under VC++ .NET 2003 and Embedded VC++, but it should remain compatible. Anyway, I keep the previous version sources available too, with only minimal fixes suggested here in the forum. The new release does not change the critical debug log functionality, so I'd suggest you to move to the new version only if you need its new features: VC++ 2005 support, Linux support, or trace log classes, which were improved significantly (look at Appendix E: Q_TRACEX macro and trace logs). Notes regarding Embedded VC++ support: only critical error log is available (qafdebug.h and qafdebug.cpp). Trace log is developed using templates, and Embedded VC++ does not support templates as far as I know. Notes regarding Linux support: it is not complete, comparing to Windows. I did not implement multithread synchronization in trace log classes. There is no printing of version numbers, and even the name of the application. I'd appreciate help with improving Linux support. An important thing about trace logs that on Linux they are configured using environment variables. After publishing this article, the debug macros were improved significantly, so I decided to publish a new release of the code. It features support of VC++ 6.0/7.0/7.1 (tested on VC++ 6.0 SP 5 and VC++ .NET 2003) and support of Embedded VC++ 3.0 (thanks to Vadim Entov for porting the sources to Windows CE). The output error message format is changed for better readability and details. Now it provides detailed information about the error (both error code and message), version of the debugged application and optionally the file name and version of the source DLL module that reports about the error (a very handy feature when one has several DLLs sharing the same source files). Also, now the error log is written in UTF-8 format which simplifies mixing UNICODE and ASCII modules. C:\SOColl\SOMain.cpp(137) : Check error: got 10 (0xA) while expected 0 (0x0) time: 2003-12-08 17:34:33:443 process: 0x00000280 thread: 0x00000560 application: C:\Program Files\MSOffice\WINWORD.EXE <10.0.5522.0> module: C:\SOColl\Debug\SOColl.dll <1.6.0.8> last error: 2, The system cannot find the file specified. expression: ERR_NO_ERROR == DoProcess( szInputFile ) There are several new macros added: Q_CHECK, Q_ERROR_SUCCESS, Q_MAPI_ERROR, Q_RETURN, Q_MFC_EXCEPTION, Q_STD_EXCEPTION and Q_SET_MODULE (thanks to Andrey Krasnopolsky for his help in the development of the library). Also, there is an optional QSockErr.h header that implements Q_SOCKET_ERROR macro that simplifies reporting socket errors. Q_CHECK Q_ERROR_SUCCESS Q_MAPI_ERROR Q_RETURN Q_MFC_EXCEPTION Q_STD_EXCEPTION Q_SET_MODULE Q_SOCKET_ERROR I updated only few sections in the article: look at Using the debug macros for the new macro descriptions, check Unit tests support for better unit tests introduction, read Customizing the debug log for your projects for changes and improvements, do not miss also the new Additional examples section with some examples that visualize the power of the debug macros. After several attempts to use this error log facility as a trace log, I decided to explain the difference between error and trace logs as I see it. Look at Appendix E: Q_TRACEX macro and trace logs. I attached the trace logs facility to this article. Note that I did not invest as much time into the trace logs facility, and while I constantly use it, I still do not find time to finish the trace log levels feature (I'll appreciate any help with that). Thus the trace log sources are provided AS-IS with short explanations. I wish to thank everybody in this forum for helping me to better understand and argument my position, especially Marc Clifton, Daniel Turini, Sam Levy, Stoyan Damov, Alex Reser and Stewart Tootill. I wish to thank too the organizers and maintainers of this community for their ideas, time and efforts. Standard C++ debug macros are not rich. Usually only a couple of such macros with some variations is there in your toolkit: ASSERT() and TRACE() (look at [MSDN: Assertions] for complete list of the standard debug macros). In its general implementation, ASSERT() pops up a dialog box and/or terminates the program. TRACE() usually outputs a string to the debug output. ASSERT() TRACE() "Assert yourself" concept is extremely useful in debugging but it is diminished by limitations of standard debug macros. They do have severe drawbacks (look at the Appendix B: Drawbacks of C++ standard ASSERTs). They are not suitable especially for the projects I work on: DLLs and ActiveX COM objects, often running on a server. They lack some features important to me (like the ability to have release builds with the critical error log, reporting the actual error message to that log and controlling module versions). I cannot allow them to terminate the server process. I do not want to bother QA guys with the "Abort, Retry, Ignore" dialog boxes. Finally I do not like how these ASSERTs appear in the source code (look at the Listing 2). I want an alternative. ASSERT More than that, traditionally the role of these debug macros is limited to the input parameters testing while they can detect a wide scope of programming errors. I think that the design of the standard ASSERT macro limits its power. To overcome the ASSERT's limitations, I developed a set of simple, flexible and powerful debug macros that allow me to catch most of the programming errors on early stages of development. Even more, these macros, as a tool, stimulate writing the "code that debugs itself". The technique and the tool presented here proved their usefulness in real projects. 6 different places. The only way to know where it failed is to go through it step by step in the debugger, that is not always possible. The user or a QA guy will find some feature(s) non-working with no diagnostic of the problem. What would you do? E_FAIL Well, at this point, the ASSERT() macro comes to help us.! (May be only a bit ) The usual place for ASSERTs is at the beginning of the function where it tests for input parameters. Most programmers stop. Convert() BSTR Well, I mix here runtime error conditions (memory overflow) with runtime programming errors or illegal conditions (NULL pointer in input parameters). I think they are very close to each other since they are not expected by my algorithm. These are unexpected errors that should be handled by ASSERTs. I never will use asserts to test expected errors (like writing to a read-only file). You can see in the code that I filter one expected error that may occur in this function: the Convert method may return the E_UNKNOWN_FORMAT error. There are no other expected errors (like file read errors) because the input file is generated by the caller process and must be always available for me. If it cannot be read, this is an unexpected error. NULL Convert E_UNKNOWN_FORMAT I definitely want to have all this debug staff, but I do not like how the code looks. And even if I know that the code failed in a specific place, I would like to know why - to get the HRESULT code at least. Plus, I may repeat again all what I wrote in the Appendix B: Drawbacks of C++ standard ASSERTs. I think now it is the right time to present the right tool. HRESULT When discussing this article in the forum, I quoted "The Practice Of Programming" by Brian W. Kernighan and Rob Pike. They say that most of the programmers (companies) write their own versions of the ASSERT macro to overcome the limitations of the standard one. They just recommended to use some other name in order to not break others code. When I first started to think about a set of debug macros, I defined the following requirements: While developing the debug macros, I formulated some additional requirements, most of which were assumed by me but not stated: I realized that using C++ syntax it is very simple to reach these requirements. It took me about 10 releases to come up with the first set of debug macros and about an year to improve it to the current state . bool Q_ASSERT( bool ) This is the macro similar to the regular ASSERT() macro. It returns the same value as it receives. And it reports if the bool is false (good condition failed). bool). true //. SUCCEEDED() actually uses FAILED() inside. And it reports if HRESULT is an error.) ); bool Q_ERROR_SUCCESS( DWORD ) This is a macro for testing ERROR_SUCCESS-compatible error codes returned by many Win32 API functions (by registry functions, for example). This macro will report if the given error code differs from ERROR_SUCCESS constant. It will report the error message too. ERROR_SUCCESS DWORD dwRet = RegQueryValueEx( hKey, _T("Value"), NULL, &dwType, (LPBYTE)szBuf, &dwSize ); if( Q_ERROR_SUCCESS( dwRet ) ) // here it will report about any error /*do something*/; // this line is executed only if no error occured bool Q_CHECK( dwConstant, dwExpression ) This is a macro for testing any expected values. This macro will report if the expected dwConstant differs from the result returned by dwExpression. It will report both the expected and received values. dwConstant dwExpression DWORD dwErr = DASetOption( NULL, SCCOPT_FIFLAGS ); if( Q_CHECK( DAERR_OK, m_dwErr ) ) // report about any error /*do something*/; // this line is executed only if no error occured void Q_MAPI_ERROR( HRESULT, MAPI_Interface ) This is a special macro for reporting errors returned by MAPI interfaces. Each MAPI interface has a special facility for converting the error codes to error messages. Such code takes more than 10 lines, so I implemented it as a macro. This macro has to be used as a statement, not as an expression. HRESULT hr = piProfAdmin->CreateProfile( szName, NULL, 0, MAPI_DEFAULT_SERVICES ); if( Q_FAILED( hr ) ) // take care of standard HRESULTs { // decode and report the MAPI error Q_MAPI_ERROR( hr, piProfAdmin ); return hr; } int Q_SOCKET_ERROR( int ) This is a special macro for reporting errors returned by WSAGetLastError() function from Windows Sockets API (WinSock). While WinSock has a lot of well-documented error codes, it has no function that returns a human-readable string message for an error (as far as I know). This macro converts the error code to a string message and returns it. It does nothing if the error code is 0. This macro is defined in QSockErr.h header file. WSAGetLastError() if( SOCKET_ERROR == listen( socket, SOMAXCONN ) ) { int nRet = WSAGetLastError(); if( WSAENETDOWN != nRet ) // this is the only expected error Q_SOCKET_ERROR( nRet ); // report about unexpected error return nRet; // in any case, return the error } void Q_RETURN( hr ) This is a shortcut macro for testing an HRESULT expression and returning from the function in case of any failure. It represents the following logic: if( Q_FAILED(hr) ) return hr; Actual code is a bit more complex to protect from executing the tested expression twice. This macro has to be used as a statement, not as an expression. // The following code works much better than the MFC-wizard // generated one - it reports the actual location of the problem. Q_RETURN( piWordApp->GetDocument( &piDoc ) ); Q_RETURN( piDoc->GetSelection( &piSel ) ); Q_RETURN( piSel->Copy() ); void Q_MFC_EXCEPTION( CException ) void Q_EXCEPTION( CException ) // old macro name for backward-compatibility This is a special macro that is very useful when processing exceptions in MFC Wizard-generated code. It reports the error message contained in the exception. This macro has to be used as a statement, not as an expression. catch{ CException & e ) { // report about the exception - it is an unexpected error // (In a case if some exceptions are expected, I will // process them differently. Q_MFC_EXCEPTION( e ); } void Q_STD_EXCEPTION( std::exception ) This is a special macro that is very useful when processing C++ standard library exceptions. It reports the error message contained in the exception. This macro has to be used as a statement, not as an expression. catch{ std::exception & e ) { // report about the exception - it is an unexpected error // (In a case if some exceptions are expected, I will // process them differently. Q_STD_EXCEPTION( e ); } void Q_LOG( LPCTSTR ) This macro writes a custom error message to the error log. It replaces un-descriptive Q_ASSERT(false). This macro has to be used as a statement, not as an expression. Q_ASSERT(false) DLLEXPORT int Func01( LPCTSTR lpszString ) { // report about the unexpected function call Q_LOG( _T("This function is deprecated " "and it should never be called!") ); } void Q_SET_MODULE( szModuleName ) This is a special macro for setting the current DLL module name. I did not find a simple automatic way to know in context of which DLL the code executes, so I use a special static string variable. You need to specify only the file name of the DLL module, and it will automatically find its location and version number at runtime. This macro is not necessary for an EXE module. Usually, it has to be added to DllMain() function. This macro has to be used as a statement, not as an expression. DllMain() BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { Q_SET_MODULE( _T("MODULE.DLL") ); ... Now, let's return to that function and add the debug macros in it. Once we add the debug macros, the function will carefully report about all unexpected errors at the moment they happen. And the error reporting staff staff, it only will remove these Q_ signs not touching the program logic (it's an allegory but it's close to the truth). Q_ When something goes wrong (the programmer tries to access an invalid property name or there is no enough memory), the program will write to the error log file all the error information available: C:\Work\XM\XMClient.cpp(770) : Unspecified error time: 2003-12-22 12:34:48:044 process: 0x000012D4 thread: 0x00001088 application: c:\connector\xmsrv.exe <1.0.0.15> module: c:\connector\XMClient.dll <1.0.0.24> last error: 1008, An attempt was made to reference a token that does not exist. expression: FAILED(0x80004005) You have all the required information here: the name and the version of the hosting process, the last error code, your module and its version, the location in the source file and description of the error (sure, E_FAIL provided in this example is not very descriptive , but there are other error codes). In many cases it is enough to take a look at the log record on the QA computer to understand what's wrong with your program. In debug build, the same log message is output to the debug log in VC++ IDE. It allows quick navigation to the source of the error. In order to use the debug macros, you need to add two files to your project: QAFDebug.h and QAFDebug.cpp. You might need linking your program to version.lib library (in VC++ 6.0, it is not linked to the project by default). I recommend also to adjust several constants in the source code to define the desired location and maximum size of the log file. Look at the Customizing section. (like DebugView from). I have a lot of different ActiveXs and DLLs hosted by different processes, so I need to have a single well known location for the log file. I decided to put it under the folder: C:\Documents and settings\UserName\Application Data\MyCompany\Log\error.log Note that Windows CE does not have a large file system. Actually, it has about four standard root folders and that's it. Therefore, on Windows CE, the error log is written to the analog of My Documents folder. In this folder, it creates the sub-folder \MyCompany\Log\. In fact, I'd recommend switching the error log off in release builds for Windows CE - a hand-held device has limited resources. For DLLs hosted by NT services (they have no current user account), I use the All Users or Default User folders (it differs between Windows versions). Or you may define an environment variable named QAFERRORLOGPATH. I think using the environment variable is the best way for NT services. QAFERRORLOGPATH An endless error log is dangerous. Therefore, I implemented a maximum log file size limit (by default, 1 Mb). There are two log files at each moment - the current one and the previous one. Generally, 1 record takes about 300-600 bytes, so I reserve space for about 2,000 records. This should be enough and the size limit guarantees that both log files together will not be larger than 1 Mb. Note that usually, if the application works as it was expected, you will not find the error log files at all. All processes write to the same log file. Of course, access to it should be synchronized. But since it is the critical error log and not a regular trace log, and critical errors happen quite seldom, I use the file itself for synchronization. I lock it on opening and try to open the file several times (max. 200 msec) if it is locked by someone else. This protects me from any kind of deadlocks. on early stages of production, when the QA/RND loops are very short, tests do not cover 100% of features and new releases almost immediately go to production (for me, as a developer,). These are the default settings. Look at the next section if you want to override this. I also switch off the unit tests support in release builds since unit tests are a bit heavy. First of all, I recommend you to change the following constants in QAFDebug.h and define them to something unique for your projects: #define QAFDEBUG_COMPANY_NAME "YourCompany" Your company name which defines a unique subfolder in the application data folder, and also a key in the registry for configuration. QAFDEBUG_LOG_ENV_VAR = _T("QAFERRORLOGPATH") Name of the environment variable that may set the output debug log folder. QAFDEBUG_SILENCE_MUTEX = _T("QAFDebugMutex001A") The name of the mutex for synchronizing with = (1024 * 1024) Maximum log file size in bytes (not in characters as in the previous versions). QAFDEBUG_LOG_FILE_NAME = _T("error.log") The current error log file name. QAFDEBUG_LOG_OLD_FILE_NAME = _T("error.old.log") The previous error log file name. The following defines allow, switching off specific features of the debug log (or any reporting at all): QAF_DISABLED Switch off any error reporting (not used by default). QAF_LOGFILE_DISABLED Switch off writing to the error log file (not used by default). QAF_OUTPUTDEBUGSTRING_DISABLED Switch off writing to the debug trace window (defined in release builds by default). QAF_UNITTEST_DISABLED Switch off unit test support (defined in release builds by default). I use CppUnit for unit test automation. Once I reviewed quite a lot of unit testing frameworks for C++ and decided to take it as most suitable for my needs. Writing unit tests is tedious work but it saves my time later, when debugging and testing changes in the code. Writing test cases in CppUnit is not difficult. In addition to test case, test suite and fixture classes which are easy to learn, there are a few "work-horse" macros. The most basic of them is CPPUNIT_ASSERT macro. This macro executes an expression and reports if it succeeded or failed. A typical test case may look like this: CPPUNIT_ASSERT void CUnitTest::testCase01( void ) { CPPUNIT_ASSERT( SUCCEEDED( QAFGetRegKey() ) ); CPPUNIT_ASSERT( 0 == _tcscmp( ST_VAR, _T("100%") ) ); ... } If any of the lines fail, CppUnit will report the location of the failure. My problem was that it cannot report what exactly happened - CppUnit only knows the end result of the expression: TRUE or FALSE. Here debug macros come to help. If the functions being called are instrumented with QAFDebug macros, they will carefully report to the debug log file what went wrong in the function body. The unit test runner may collect the error log file and attach it to the unit test report log. TRUE FALSE QAFDebug Usually, the unit test does not only tests if the function works. A good unit test should also test the function call with wrong parameters and ensure it returns correct error code. The error becomes being a normal, desired behavior. For example, look at the following unit test case: void CUnitTest::testCase01( void ) { CPPUNIT_ASSERT( FAILED( QAFGetRegKey( NULL ) ) ); CPPUNIT_ASSERT( 0 != _tcscmp( ST_VAR, _T("0%") ) ); ... } In this case, I need( SUCCEEDED( QAFGetRegKey() ) ); CPPUNIT_ASSERT( 0 == _tcscmp( ST_VAR, _T("100%") ) ); // skip writing to the error log since this function should fail Q_SILENT( CPPUNIT_ASSERT( FAILED( QAFGetRegKey( NULL ) ) ) ); Q_SILENT( CPPUNIT_ASSERT( 0 != _tcscmp( ST_VAR, _T("0%") ) ) ); ... } The unit test support introduces some overhead. Synchronization between processes requires using mutexes and a memory mapped file. Therefore, I only keep it in debug builds and exclude it in release builds. Usually, I do the same for the unit tests - only debug builds contain tests. Again, the overhead becomes an issue if only the tested application starts writing hundreds of messages to the error log file. If no error occurred, only a couple of additional assembler instructions execute per macro. There are many opportunities to make programming simpler and faster. I present here a couple of add-ins (most of VC++ programmers should already know them) that help me not only with the debug macros but with the entire coding process. You can find the corresponding files in the QAFDebug_doc.zip. The UserType.dat file makes Visual Studio 6.0 to highlight common ATL and MFC classes, types, macros and functions as keywords (in blue). This helps a lot because the colored standard types are easy to recognize and you do less-ins for Visual Studio 6.0 that upgrades IntelliSense features of VC++. I strongly recommend this add-in. I added several keyboard shortcuts for my macros to make my life simpler. You must not replace this file, but add its contents to the existing one. Now, when I type qs, it automatically inserts Q_SUCCEEDED(). The other shortcuts mean: qa (Q_ASSERT()), qi (Q_INVALID()), qf (Q_FAILED()), qe (Q_ERROR()), qx (Q_EXCEPTION(e)), ql (Q_LOG( _T("") );), qc (Q_CHECK( , )) and qr (Q_RETURN();). This file is usually located under the following folder (you also may edit it from Visual Assist options): qs Q_SUCCEEDED() qa Q_ASSERT() qi Q_INVALID() qf Q_FAILED() qe Q_ERROR() qx Q_EXCEPTION(e) ql Q_LOG( _T("") ); qc Q_CHECK( , ) qr Q_RETURN(); C:\Program Files\Visual Assist 6.0\Misc From time to time, I work with JNI (Java Native Calls) DLL modules. Often, the interface of the module cares little about the error reporting - the only thing important to the caller is whether the call succeeded or not. Thus, there is not much left for the postmortem failure analysis. Let's take a function that should never fail under normal conditions. Only when it meets something unexpected, it would return a failure. The following JNI wrapper calls a C function LRS(). It does not report the error code returned from this function. Instead, it simply returns an empty string in case of any error. The critical error log keeps trace of all internal failures. LRS() JNIEXPORT jstring JNICALL Java_com_company_ta_Detector_getTaFromFile (JNIEnv * env, jclass cls, jstring jFileName) { if( Q_INVALID( NULL == env ) ) return NULL; if( Q_INVALID( NULL == jFileName ) ) return env->NewStringUTF( "" ); char szLang[MAX_PATH] = { 0 }; const char * FileName = NULL; FileName = env->GetStringUTFChars( jFileName, NULL ); if( Q_INVALID( NULL == FileName ) ) return env->NewStringUTF( "" ); int nRet = LRS( FileName, szLang ); if( !Q_CHECK( NO_ERROR, nRet ) ) return env->NewStringUTF( "" ); return env->NewStringUTF( szLang ); } Another example is taken from a custom socket connection protocol. Any data transfer protocol relies heavily on many assumptions (buffer sizes, constants, relations between different variables). Implementing a complex error processing using exceptions with tracing can be painful and may affect performance. After the protocol is fully debugged, the error processing will seldom be needed. Here assertions become very handy. Actually, using assertions in this function helped me in discovering and fixing one very rare and difficult bug. // Write the attachment data if there is enough space if( (0 != m_dwAttachSize) && (ulBufSize > ulBytesSentRet) ) { if( Q_INVALID( m_dwRemained > m_dwAttachSize ) ) { Q_CHECK( m_dwRemained, m_dwAttachSize ); return OP_FAILED; } // space remained in the socket buffer unsigned long ulDataSize = ulBufSize - ulBytesSentRet; // if there is less actual data than the buffer space if( ulDataSize > m_dwRemained ) ulDataSize = m_dwRemained; // take the actual data unsigned long ulWritten = 0; // for the file attachment read the data from the file DWORD dwPos = m_dwAttachSize - m_dwRemained; if( 0x0000 == m_wCodePage ) { dwPos = 0; bool bRet = ReadAttachment( dwPos, ulDataSize ); if( Q_INVALID( ! bRet ) ) { Q_CHECK( 0, dwPos ); Q_CHECK( 0, ulDataSize ); return OP_FAILED; } } // cannot read the file by some reason if( Q_INVALID( NULL == m_pAttachment) ) return OP_FAILED; // send the data to the socket if( 0xFFFF == m_wCodePage ) ret = pChannel.SendUTF16( m_pAttachment + dwPos, ulDataSize, ulWritten ); else ret = pChannel.Send( m_pAttachment + dwPos, ulDataSize, ulWritten ); // a couple of things that should never happen Q_INVALID( OP_NEED_MORE_DATA == ret ); Q_INVALID( 0 == ulWritten ); if( OP_FAILED == ret ) return ret; ulBytesSentRet += ulWritten; m_dwProcessed += ulWritten; m_dwRemained -= ulWritten; } Q_CHECK( GetPacketSize(), m_dwProcessed + m_dwRemained ); An excellent book on debugging Win32 applications. This book should be studied in schools... schools of programming, I mean . This is my favorite. In a very popular manner, it discusses writing high quality programs and touches the entire development circle. Another favorite of mine. It belongs to the same genre as Writing Solid Code, but of course it is different. Must to read, IMHO. This book is too academic but also recommended. I'd say it lacks a bit of fun. This book is a kind of old fashion but still valuable. This book speaks more about algorithms than about style of coding. But there are a couple of interesting chapters. The idea behind the debug macros in this library is very similar to mine. They convert HRESULT error codes to meaningful error messages. Macros there implement only the idea of having the error processing in release builds. There is no log file and I do not like the idea of breaking the program execution. The author of this article is actually who inspired me to re-write this article and better argument my position. I liked to learn from his experience too. Look at the title. A good one. A short and complete reference of all assertions available in VC++. A very interesting article on using templates to construct ASSERTs. C++ unit testing framework that I'd undoubtedly recommend. Once upon a time, I took his set of simple classes for working with registry and used it till now. While the original sources are significantly modified, I keep the link to the original author. These classes are used in QTrace trace log facility. This is an example of the standard assertion message that is displayed by the ANSI assert() function. Personally, I do not like the standard assertions coming with VC++. They suffer from many little but annoying defects. I'm sure that the framework I present here is also full of drawbacks (Appendix D lists the missing features only). Still, mine provides me with more goods. assert(). assert Most of the standard ASSERT macros pop up a dialog box like the one on the screenshot. choosing "Ignore". I prefer to have a single well-known file with the error log. stderr The C run-time library allows redirecting the assertion to a file or to the OutputDebugString API by calling the _CrtSetReportMode function (look at [Debugging Applications, page 61]). But none of these functions take care of the common file location for all your programs. Neither do they truncate the file in case it becomes too large. (I'm not quite honest here - it is possible to write a helper class which will do it.) At last, in a case you develop a COM in-process object or a DLL, you are not in charge to redirect stderr because it belongs to the entire process (this is one of my problems with regular ASSERTs). OutputDebugString _CrtSetReportMode All the Microsoft-supplied assertions suffer from one fatal flaw: they change the state of the system. This issue is discussed in detail in [Debugging Applications, page 62], here I'll explain it in short. Many of other Win32 functions which might destroy the last error code by setting it to 0. (To be honest again, I have to say that I found this argument when recently I started to re-read this book in searching information for the revised article). SetLastError GetLastError occasionality, and the release build will fail because of the missing function call. While the golden rule is to try never call functions in the assertions, these things still happen. I believe that by integrating the assertions into the actual algorithms, it is possible to eliminate this class of defects. Note that in this case, when assertions are disabled, the compiler is able to optimize out unnecessary equations, with minor exceptions which may be handled manually. QAFDebug/QAFTrace Q_EXCEPTION TCHAR Some time after writing the debug error log facility, I catch myself on attempts to use this log as a trace log. I clearly understood that the error log design goals did not suite the trace log requirements. A good trace log must have: printf() << None of those are implemented in the critical error log facility. Moreover, these requirements contradict with the requirements of the critical error log. I've analyzed every trace debug log I could find at that moment. No one suited me completely but I learned a lot and got new ideas. It is not a big deal to write a trace log, so I wrote it. (The big deal is to improve it to a "professional" component, with rich features and documentation.) To the moment the unit is quite stable, but there are many features still waiting to be implemented. Anyway, I like its flexibility, simplicity, and rich formatting options. Let me demonstrate its usage: #include "QAFTrace.h" // The variable declaration is somewhat need to be hidden with #ifdef #ifdef QD_TRACE_ENABLED // Create the static instance of the log file class, // specify the file name, default log level and the maximum file size in bytes. QTrace::LogFile log( _T("mylogfile.log"), QTrace::TraceDebug, 512 * 1024 ); #endif int main() { int i = 65, j = 5; int arr[5] = { i, i, i, i, i }; QD_TRACEX( log, "Output a simple string" ); QD_TRACEX( log, L"Output a UNICODE string, j = " << j ); QD_TRACEX( log, QTrace::Format( "printf-style %d, %d", i, j ) << " and more!" ); QD_TRACEX( log, "Format hex codes = 0x" << QTrace::Hex( i ) ); QD_TRACEX( log, QTrace::Dump( &arr[0], sizeof(arr), _T("int[5]") ) ); return 0; } The output will look like: 01:31 14:05:01:342 [3DA:11E] Output a simple string <== c:\wrk\tst.cpp(10) 01:31 14:05:01:342 [3DA:11E] Output a UNICODE string + j = 5 <== c:\wrk\tst.cpp(11) 01:31 14:05:01:359 [3DA:11E] printf-style 65, 5 and more! <== c:\wrk\tst.cpp(12) 01:31 14:05:01:383 [3DA:11E] Format hex codes = 0x41 <== c:\wrk\tst.cpp(13) 01:31 14:05:01:402 [3DA:11E] Memory dump of "int[5]", address 0x3FE56470, size 20b (0x14) <== c:\wrk\tst.cpp(14) 3FE56470 00 00 41 00 00 00 41 00 00 00 41 00 00 00 41 00 ..A...A...A...A. 3FE56480 00 00 41 00 ..A. The trace log contains only the important information - timestamp, process and thread ID, the message and the source file location (similar messages may be output from different functions). There may be different trace log files in one process, and many processes can write to the same trace log. All trace logs are created in the same folder where the critical error log is located. Each trace log can be switched on/off through the registry under /HKLM/Software/YourCompany/Log/ using a DWORD registry value named the same as the trace log file name ("mylogfile.log" in my example). By default, the trace log is disabled, and you should define a specific value in the registry to enable it. Note that on Linux the trace log is enabled by setting an environment variable. This environment variable has the same name as the log file, with dots replaced by underscores "mylogfile_log". /HKLM/Software/YourCompany/Log/ DWORD Usually, I either create a static log class instance, or add it as a member of another class - there is no problem with multiple instances of the same trace error log because they use a named mutex for synchronization (not implemented on Linux yet). When the trace log is disabled, the performance impact is very little - Q_TRACEX macro is converted into if( !log.IsEnabled() ) ; else log.output(); construction. Q_TRACEX if( !log.IsEnabled() ) ; else log.output(); There are two sets of trace macros: QD_XXXX and QR_XXXX. QD_XXXX macros are completely excluded from RELEASE builds for the sake of performance. QR_XXXX macros allow creating trace logs which will be available in both DEBUG and RELEASE builds. Again, the trace debug log is purposed to help in debugging the system and the critical error log is intended for QA and early production bug diagnostics. These are very different goals. When the program works as expected, the critical error log should remain empty and the debug trace log might be flooded by trace messages (if it is enabled, of course). This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here Q_LPTSTR szPos = _tcsrchr( szCopyFilename, PATH_DELIMITER ); szPos[1] = 0; Q_LPTSTR szPos = _tcsrchr( szCopyFilename, PATH_DELIMITER ); if( szPos ) { szPos[1] = 0; } else { szPos = szCopyFileName; szPos[0] = 0; } #define ROOT_LOG_FOLDER _T("Software\\MyCompany\\Log\\"); m_pdwEnabledTraceLevel = new CRegDWORD( (LPCTSTR)CStringConcat( ROOT_LOG_FOLDER, szID ), HKLM, TraceNone, registry_value::RF_READONLY ); Q_ASSERT( NULL != m_pdwEnabledTraceLevel ); #pragma message("automatic link to VERSION.LIB") #pragma comment(lib, "version.lib") QTrace::Device::Device( LPCTSTR szID, const bool bNeedMutex, const QTrace::TraceLevel nDefaultTraceLevel ) : m_hMutex(NULL), m_szID(NULL), m_nDefaultTraceLevel(nDefaultTraceLevel), m_dwWaitTimeout(0), m_pdwEnabledTraceLevel(NULL) { inline bool QTrace::Record::Write( LPCVOID const pBuffer, const DWORD dwBufferSize, DWORD & dwBytesWrittenRet ) { //; ... // I assume that the object is always installed and available. // If it is not created, this is definitely a bug. if( NULL == lpszFilename ) throw MYEXCEPTION(); General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/3641/Code-that-debugs-itself?msg=1231124
CC-MAIN-2015-32
refinedweb
5,702
63.39
LWP_YIELD(3L) LWP_YIELD(3L) NAME lwp_yield, lwp_suspend, lwp_resume, lwp_join, lwp_setpri, lwp_resched, lwp_sleep - control LWP scheduling SYNOPSIS #include <<lwp/lwp.h>> int lwp_yield(tid) thread_t tid; int lwp_sleep(timeout) struct timeval *timeout; int lwp_resched(prio) int prio; int lwp_setpri(tid, prio) thread_t tid; int prio; int lwp_suspend(tid) thread_t tid; int lwp_resume(tid) thread_t tid; int lwp_join(tid) thread_t tid; DESCRIPTION lwp_yield() allows the currently running thread to voluntarily relin- quish control to another thread with the same scheduling priority. If tid is SELF, the next thread in the same priority queue of the yielding thread will run and the current thread will go the end of the schedul- ing queue. Otherwise, it is the ID of the thread to run next, and the current thread will take second place in the scheduling queue. lwp_sleep() blocks the thread executing this primitive for at least the time specified by timeout. Scheduling of threads is, by default, preemptive (higher priorities preempt lower ones) across priorities and non-preemptive within a pri- ority. lwp_resched() moves the front thread for a given priority to the end of the scheduling queue. Thus, to achieve a preemptive round-robin scheduling discipline, a high priority thread can periodi- cally wake up and shuffle the queue of threads at a lower priority. lwp_resched() does not affect threads which are blocked. If the prior- ity of the rescheduled thread is the same as that of the caller, the effect is the same as lwp_yield(). lwp_setpri() is used to alter (raise or lower) the scheduling priority of the specified thread. If tid is SELF, the priority of the invoking thread is set. Note: if the priority of the affected thread becomes greater than that of the caller and the affected thread is not blocked, the caller will not run next. lwp_setpri() can be used on either blocked or unblocked threads. lwp_join() blocks the thread issuing the join until the thread tid ter- minates. More than one thread may join tid. lwp_suspend() makes the specified thread ineligible to run. If tid is SELF, the caller is itself suspended. lwp_resume() undoes the effect of lwp_suspend(). If a blocked thread is suspended, it will not run until it has been unblocked as well as explicitly made eligible to run using lwp_resume(). By suspending a thread, one can safely examine it without worrying that its execution-time state will change. NOTES When scheduling preemptively, be sure to use monitors to protect shared data structures such as those used by the standard I/O library. RETURN VALUES lwp_yield(), lwp_sleep(), lwp_resched(), lwp_join(), lwp_suspend() and lwp_resume() return: 0 on success. -1 on failure. lwp_setpri() returns the previous priority on success. On failure, it returns -1. ERRORS lwp_yield() will fail if one or more of the following is true: LE_ILLPRIO Attempt to yield to thread with different priority. LE_INVALIDARG Attempt to yield to a blocked thread. LE_NONEXIST Attempt to yield to a non-existent thread. lwp_sleep() will fail if one or more of the following is true: LE_INVALIDARG Illegal timeout specified. lwp_resched() will fail if one or more of the following is true: LE_ILLPRIO The priority queue specified contains no threads to reschedule. LE_INVALIDARG Attempt to reschedule thread at priority greater than that of the caller. lwp_setpri() will fail if one or more of the following is true: LE_INVALIDARG The priority specified is beyond the maximum avail- able to the pod. LE_NONEXIST Attempt to set priority of a non-existent thread. lwp_join() will fail if one or more of the following are true: LE_NONEXIST Attempt to join a thread that does not exist. lwp_suspend() will fail if one or more of the following is true: LE_NONEXIST Attempt to suspend a non-existent thread. lwp_resume() will fail if one or more of the following is true: LE_NONEXIST Attempt to resume a non-existent thread. 21 January 1990 LWP_YIELD(3L)
http://modman.unixdev.net/?sektion=3&page=lwp_setpri&manpath=SunOS-4.1.3
CC-MAIN-2017-30
refinedweb
639
54.93
Automate/Schedule a Macro Hi, I’ve created a macro that I would like to run at a scheduled interval, e.g. every 15 min. Is there a way to schedule a macro to run? Thanks, Pat - PeterJones last edited by There isn’t a way to do that natively. However, there may be a way using one of the scripting plugins, like PythonScript (or the others listed below). The PythonScript help lists the various notification signals that you can trap for a callback, but I didn’t see any that appeared to be timer-based – though I may have missed one. As an alternative, I am sure that Python or Lua (the programming languages, independent of the PythonScript or LuaScript plugins) have some manner of setting and handling timer-based alarms. During your startup (for PythonScript, use the startup.py), set an alarm; when the alarm is handled, have it use notepad.runMenuCommand()(or equivalent) to call the macro, and then have it schedule itself (set the alarm) again. I don’t know enough Python (or Lua) to work up an example for you, sorry. ----- Scripting Plugins (Links) - PythonScript - PythonScript HOME - PythonScript DOWNLOAD Plugins > Python Script > Context-Help - Getting Started with Python - LuaScript - jN: JavaScript for Notepad++ - NppExec I will have to dig through PythonScript when I get some time. In the mean time, I use Windows and someone suggested using Windows Task Scheduler. Any idea what file or script I would have it call to run the macro? - Eko palypse last edited by you cannot use task scheduler to start a specific macro within notepad++(npp). Task scheduler can only be used to start programs like npp. May I ask you what exactly you try to do with the macro? Maybe there is a “better” way doing it. Eko macro that I would like to run at a scheduled interval This Pythonscript code shows one way of doing it: import threading def timer_callback(): print('hello world every 3 seconds!') # or, for example, notepad.runMenuCommand(menuName, menuOption) threading.Timer(3.0, timer_callback).start() timer_callback() @Scott-Sumner said: def timer_callback(): print(‘hello world every 3 seconds!’) # or, for example, notepad.runMenuCommand(menuName, menuOption) threading.Timer(3.0, timer_callback).start() timer_callback() Hi Scott, I tried your script as follows: def timer_callback(): notepad.runMenuCommand(Macro, my-macro) threading.Timer(3.0, timer_callback).start() timer_callback() I am getting “NameError: name ‘notepad’ is not defined.” Any thoughts on how to resolve that? Hi, @patrick-coleman, @scott-sumner and All, Just a piece of information : When you want to execute a Windows program or batch script, on specific intervals, the Microsoft schtasksutility is quite powerful ;-)) For instance, the line, below, typed in a console windows, would create a task, named Testwhich executes the test.batbatch, located in \D:every minute : schtasks /create /sc minute /mo 1 /tn "Test" /tr D:\test.bat For help on this command, which replaces, the old atcommand, type in schtasks /? To list all the scheduled tasks, simply type schtasksand valid To delete the Testtask, type in the command schtasks /delete /tn test Here is, below, the detail of the schtaskscommand ( Sorry, it’s written in French on my system, of course ! ) SCHTASKS /paramètre [arguments] Description : Permet à un administrateur de créer, supprimer, effectuer des requêtes, modifier, exécuter et mettre fin à des tâches planifiées sur un système local ou distant. Remplace AT.exe. Liste de paramètres : /Create Crée une nouvelle tâche planifiée. /Delete Supprime les tâches planifiées. /Query Affiche toutes les tâches planifiées. /Change Modifie les propriétés d'une tâche planifiée. /Run Exécute la tâche planifiée immédiatement. /End Arrête la tâche planifiée actuellement en cours d'exécution. /? Affiche cet écran d'aide. Exemples : SCHTASKS SCHTASKS /? SCHTASKS /Run /? SCHTASKS /End /? SCHTASKS /Create /? SCHTASKS /Delete /? SCHTASKS /Query /? SCHTASKS /Change /? Well, now the deal is how to connect that stuff with the action of running a macro from within N++ ;-)) Not tried, yet ! Best Regards, guy038 Well, now the deal is how to connect that stuff with the action of running a macro from within N++ ;-)) Not tried, yet ! Yea…good luck. I’ll look forward to seeing the solution on THAT one. :-) @Patrick-Coleman said: I am getting “NameError: name ‘notepad’ is not defined.” You have to understand Python/Pythonscript a bit for this one. The short story is you probably need this at the top of the script: from Npp import notepad For my setup, I put that line in my startup.py(which runs upon Notepad++/Pythonscript-plugin startup, hence its name), so I don’t have to put that in my individual script files (but you can do it that way). @Scott-Sumner said: I’ll look forward to seeing the solution on THAT one. :-) Seems it’s time for another nice hackish (though unnecessary) solution. Here we go. :-) - Download and install my NppUISpy plugin. Follow the instructions for its manual installation. - Download the tool NirCmd (scroll down to the end of the text to find the download links) and unpack the zip file to a directory where you have write access. - Start Notepad++, go to Plugins menu and launch the NppUISpy plugin by clicking on its Spy! menu entry. - In the left pane of the plugin’s UI go to the tree node of the Macro menu and open it by clicking on the small +sign to its left. Find the entry of the macro you want to start and remember the related number in the Command Id column. Please note: The tree items respond to mouse clicks and make Notepad++ to execute the related command. Maybe you prefer to click only on the tree lines at the left and the small +signs to prevent that. The toolbar button items in the right pane respond to mouse clicks as well. - Start a console window and navigate to the directory where you have unpacked NirCmd. - Type the following command: nircmdc win postmsg ititle "Notepad++" 2072 0 XXXXXwhere XXXXX is the number you remembered in step 4. The command of step 6 can be put into a batch file which in turn can be executed by a scheduled task. I knew it was going to get wild and crazy like that. :-) It’s fine though as there is a Notepad++ tie in, so we are not getting into “off-topic” land… Curious, though, why did you say “(though unnecessary)”…? @Scott-Sumner said: Curious, though, why did you say “(though unnecessary)”…? Because you have already posted a (I guess) working Python solution. I see. Well, we don’t know yet that the Pythonscript-based solution will work for the OP, so it is still nice to have other options. BTW, I like the looks of your “spy” plugin! (see…without the alternative solution path being presented, I never would have learned about that plugin!) Does the “spy” plugin take a large amount of time to initialize when it starts up? I added it to my setup and it seems to have some odd interactions with some of my Pythonscript stuff that runs on startup. I haven’t investigated further yet but the first thing I noticed is that it seems to take longer now for my Notepad++ to get to a “ready for editing” state. Hmm, the plugin itself does nearly nothing when it is loaded, it only adds its menu entries to the Notepad++ UI. Only when you click on the Spy! menu entry it examines the main menu and the toolbar of Notepad++ and fills its trees. All these data gets thrown away when you close the dialog. But it is a Delphi application and as such it incorporates the needed parts of the VCL (Visual Component Library), the abstraction layer of Delphi for the Win32 API. In this context it loads a noticeable amount of Windows DLL files. Maybe this causes the increased load time. I have installed about to 45 plugins, thus my Notepad++ needs some time to start up anyway and I was not aware of an increased load time after adding the new plugin.
https://community.notepad-plus-plus.org/topic/16746/automate-schedule-a-macro
CC-MAIN-2019-51
refinedweb
1,339
72.46
Here's how to handle signals from a Button and a CheckBox by using signal handlers in QML. Cascades provides these signal handlers for you to use, and you can access them by using the prefix "on," followed by the signal name that you want to handle. In this code sample, the checked status of the check box is displayed beside it, and clicking the button resets the checked status to its default value (not checked). import bb.cascades 1.0 Page { content: Container { CheckBox { id: myCheckBox text: "Unchecked" // When the checked status changes, update the check box's // text to reflect the new state onCheckedChanged: { if (checked) myCheckBox.text = "Checked"; else myCheckBox.text = "Unchecked"; } } Button { text: "Reset" // When the button is clicked, reset the checked status // of the check box onClicked: { myCheckBox.resetChecked(); } } } // end of Container } // end of Page Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/documentation/device_comm/input/touch_input.html
CC-MAIN-2019-30
refinedweb
156
71.75
unittest exits Discussion in 'Python' started by Alan Baljeu,56 - Bob Helber - Jan 13, 2004 How many namespace exits?Franco Figún, Apr 26, 2004, in forum: ASP .Net - Replies: - 6 - Views: - 2,132 - Cowboy \(Gregory A. Beamer\) - Apr 26, 2004 Tomcat 5.0 dies/exits with no info in log filesAnders, Jul 26, 2005, in forum: Java - Replies: - 6 - Views: - 3,403 - Anders - Aug 5, 2005 JNI Exits with SIGUSR2, Nov 23, 2005, in forum: Java - Replies: - 3 - Views: - 622 - Thomas Fritsch - Nov 28, 2005 Unittest - adding a doctest suite to unittest.mainPaul Moore, Oct 14, 2008, in forum: Python - Replies: - 1 - Views: - 410 - Paul Moore - Oct 14, 2008
http://www.thecodingforums.com/threads/unittest-exits.644355/
CC-MAIN-2014-52
refinedweb
109
79.6
Mono 0.29 Hello everyone, A new release of Mono has been released. Mono is an open source implementation of the .NET Framework for Unix, Linux and Windows systems. There are big breaking news: Mono JIT on PowerPC runs Hello World, ASP.NET is feature complete, AppDomain unloading is supported and 64-bit ports of HPPA and SPARCv9 are available now. A new group of developers from Mainsoft has been contributing extensively to ADO.NET and ASP.NET. This release includes four components at once: the Runtime and Software Development Kit as well as the Documentation browser, our XSP web host for ASP.NET and the Mono/Apache module have been released. Packages for various distributions are also available from our download page. A big push in this release has been to get closer to completion on the .NET 1.0 and .NET 1.1 APIs and completing pieces that we need for the Mono 1.0 release. But at the same time work continues within the safety of #ifdefs on Mono 1.1 features (integrating .NET 1.2 components). I know that the following summary is incomplete, I apologize for missing major features Stats Since the last release, 3,071 individual commits were done to our runtime and class libraries. 310 bugzilla bugs were closed. Thanks A big thank you goes for Duncan Mak who worked steadily to get every new dependency of Mono compiled and tested in four platforms as well as maintaining the Red Carpet channel (and soon, give us the easy installer). Availability Binary Packages: Pre-compiled packages for various platforms are available from our web site from the download section: Since there are so many new package dependencies (libicu and the Cairo universe), we are not listing the individual packages to download anymore and we recommend that you use Red Carpet to install. The Ximian Desktop installer will be able to install Mono later this week, so with a single click, you should be able to install Mono 0.29 on your system. Source code: - Mono package (Runtime engine, JIT compiler, pre-compiled compiler and class libraries): - MCS package (Class Libraries, C# and VB.NET compiler and managed tools): - Apache Mono Module and XSP runtime (needed for the Apache module): - Mono Documentation browser: On CVS the tags are MONO_0_29, MCS_0_29, XSP_0_8, MOD_MONO_0_6 and MONODOC_0_8. Quick source code installation: If we have no packages for your platform, installing from source code is very simple: tar xzf mono-0.29.tar.gz cd mono-0.29 ./configure make install Mono Runtime Changes Fedora’s security features broke Mono 0.28, this version of Mono rectifies this problem. Ahead of Time Compiler Bug fixes in the C# compiler now permit all the assemblies to be pre-compiled using the ahead-of-time compilation option of Mono. On average a fully AOT environment will give the C# compiler a 20% performance boost. Porting Progress More work on the PowerPC code generator is on this release, the JIT engine was able to run “Hello World” for the first time. This involves JITing a fair amount of code, roughly about 100 methods and it also exercises various P/Invoke and calling convention features. At this point it seems like Mono exposes a few bugs on the MacOS X application support. 64-bit support for the VM was checked in for the SPARC v9 and HPPA architectures by Bernie Solomon. This is a significant change because this means that the values of the “IntPtr” variable is 8-bytes instead of 4-bytes. The port included various cleanups in our libraries to make them 64-bit ready. Internationalization Dick has checked in a large upgrade to our internationalization support, initially this code contains CultureInfo and string collation routines. This uses IBM’s IBM’s ICU library, available from:. Now Mono can cope with charset-encoded filenames instead of demanding them to be in UTF-8 format. See the man page for mono(1) for details. Generics Support Martin continues his work to support generics in Mono. The support is not ready for prime time yet, but you can see some thirty-something generic sample programs in mcs/tests/gen-* Improved Trace Facility The runtime features an improved trace facility, developers can now include and exclude groups of methods, namespaces, types and assemblies from the trace output, a helpful tool for debugging code. See the man page for details. For example, to trace method calls in the program, and on the System.XML namespace, use: mono –trace=program,N:System.Xml hello.exe AppDomain unloading and Module support Mono has finally gained module support, some programs from the Mercury compiler are known to work now and this should allow the IIOP.NET folks to continue their work (Zoltan). AppDomains can now be unloaded (Zoltan). Other runtime features Gonzalo and Zoltan have fixed a long-standing problem with the implementation of Equals on ValueTypes, this problem was not only fixed by Gonzalo, but later the performance was boosted by Zoltan. Lluis implemented context static field support for remoting. Zoltan implemented AppDomain unloading, LastErr flag on P/Invoke methods, stdcall calling conventions support, marshalling of structs and improved the support for running SML.NET and Mercury.NET generated code. AppDomain.LoadAssemblyRaw functionality has been added by Zdravko Tashev. Compilers and Tools Changes The C# compiler continues to be bug fixed. A new version of the compiler `gmcs’ is available for testing out the Generics features of C# 2.0. To use this feature, you must rebuild the Mono class libraries with the `generics’ profile: $ cd mcs-0.29 $ make PROFILE=generics $ make install Sebastien and Zoltan improved MCS to support delay-signing of assemblies. Also the sn (StrongName) tool is included in this distribution to re-sign and verify signatures of assemblies. Mono Class Libraries Changes Corlib has been renamed to Mscorlib We have finally renamed `corlib.dll’ into `mscorlib.dll’ which means that we removed all the various workarounds that we had in the code to cope with this difference. Novell.Directory.LDAP Sunil Kumar and his team at Novell have contributed a fully managed implementation of LDAP for Mono and the .NET Framework. The code is now part of the standard distribution of Mono, and is being used to implement our System.DirectoryServices namespace. The Mono.Directory.LDAP assembly is now deprecated in favor of this. System.Drawing and Windows.Forms In the last release of Mono we had started an effort to unify the three backends that we had for System.Drawing, since it was becoming hard to maintain. The new strategy to implement System.Drawing is to use the GDI+ API on Unix and implement the GDI+ C Flat API on top of the cairo library (which is now a dependency). The good news is that the code is much simpler, our support is more complete, and we can develop this one faster. The bad news is that there are many regressions on this release related to using System.Drawing and Windows.Forms on Unix. Windows.Forms in this release is broken on Unix, but fairly functional on Windows. The new rendering engine introduced for System.Drawing broke a lot of the functionality we had, and we will be working hard to address those limitations on the next release. Databases Reggie updates the ByteFX MySQL provider on CVS and Francisco updates the Npgsql provider, so this version ships with the latest editions of these two providers. Victor contributed an updated DB2 provider. We could not get the latest version of his code before the release, but expect the namespace to change on the next release as we become binary compatible with the IBM.Data.Db2Client implementation. Eran Domb has been actively fixing bugs in the System.Data assembly and related tools. JavaScript Cesar continued with the grammar fixes to the language. Code Generation for: default ms compiler jscript assembly format, function declarations, variable declarations, boolean literals, string literals and initial code generation for binary operations. Semantic Analysis: initial /fast features, like detecting not declared variables. Web Services and Remoting Changes Lluis has been working hard on completing the Web Services and Remoting assemblies to reach 1.0. All the encodings are now supported (previously we supported only document/literal): literal encoded and RPC format is now supported, with wrapped or bare parameters. A new documentation page is generated now for web services automatically and added support for generation of WSDL files for client HttpPost and HttpGet. Web Services error handling and error reporting has improved a lot as we started using it for developing our own web services and the various improvements to the HTTP runtime also benefit this space. The discovery classes have been added to support the DISCO protocol, and a new tool (disco) is distributed as well. Remoting.Configuration has been implemented thanks to Jaime who did the first pass at the implementation and Lluis who completed it and deployed it. Remoting objects can be hosted in XSP, the .rem and .soap files types are now supported as well. Improved the performance of calls between application domains, and also implemented support for asynchronous calls as well as improving the support for synchronization and static fields. WSE: The Web Services Enhancements Sebastien added support for trace filters on input/output SOAP messages. He also added support for WS-Security on the client side: UserName rountrip (except digital signatures) and XML encryption using X.509 certificates to/from a web service. Mono Documentation Browser Changes MonoDoc is the Mono Documentation Browser. It includes class library documentation, tutorials, the C# language reference and errors reference. Monodoc contains inline editing and collaboration facilities built into it. On this release of MonoDoc we are shipping with its collaboration features turned on. Users can now edit the content for the class library documentation and submit their improvements through a Mono Web Service. Improvements will appear on upcoming releases of MonoDoc. The editing facility in MonoDoc contains new shortcuts to insert cross references, tables, item lists and code samples (miguel). Also Ben added support for editing enumeration definitions. The Web edition has better JavaScript navigation facilities for the tree explorer, and Gonzalo improved the caching of data for the web edition of Monodoc: now it will return the time-stamp of the documents to avoid reloading redundant information over the web. You can use the Monodoc/web edition to host the documentation for your own class libraries. You can see the web front-end for Monodoc live at John Luke contributed various aesthetic changes to the web edition and various Gtk# types were documented by him. The new style is closer to the NDoc web interface. New documentation for NUnit, Npgsql is also available. Monkeyguide: We are shipping the Monkeyguide in this release, but we need help in updating it as well as doing editing work on it. It is known to contain old materials that confuse people, if you are interested in helping the documentation effort, please subscribe to the mono-docs-list@ximian.com mailing list. ASP.NET: Feature complete Two major changes in this release: OutputCache support and state session support. With this we consider our implementation of ASP.NET to be feature complete, and at this point we are requesting ASP.NET developers to try out their existing applications and report any problems to us (Please use Bugzilla to file a report). In depth: Now Mono supports the session managers other than the in-memory session manager. There are two: the StateServer and the SQL-based state server. Both configured the same way you would on Microsoft.NET. The Mono SQLSessionServer allows you to use any database provider that implements the IDbConnection interface (The default provider is Npgsql). A little extra configuration is required because of this extra flexibility. If you are not using Npgsql you need to add the StateDBProviderAssembly and StateDBConnectionType attributes to your app settings like so: <appsettings> <add key="StateDBProviderAssembly" value="Npgsql"/> <add key="StateDBConnectionType" value="Npgsql.NpgsqlConnection"/> </appsettings> OutputCache is supported now on ASP.NET pages. Two new tools asp_state.exe and dbsessmgr.exe ship: the first is the state manager for ASP.NET and the later is a tool to manipulate the current session database. Support for other languages in ASP.NET is included now, they only need to distribute a CodeDOM provider (VB.NET does). Support for different character set encodings on files, requests and responses instead of only supporting UTF-8. Timeouts: now it is possible to use the machine.config or the application config file to control the amount of time that the runtime will wait to process an ASP.NET request. If the timeout is exceeded the operation is aborted. A request queue mechanism: it now possible to inform the runtime through the machine.config or application config file how many threads it should consume from the threadpool: any excess requests will be queued up instead of consuming all the threads available: <system.web> <httpruntime executiontimeout="90" maxrequestlength="4096" usefullyqualifiedredirecturl="false" minfreethreads="8" minlocalrequestfreethreads="4" apprequestqueuelimit="100"/> </system.web> Alon and Yaron from Mainsoft have actively contributed to fixing plenty of bugs and controls on this release. Security The Mono Cryptographic libraries are very complete and all written in managed code. Various people take bits and pieces of it and run it on smaller devices where the Compact Framework might not have all the functionality they need. In this release Sebastien expands the Mono.Security code base with new features: - Augmented support for X.509 certificates. - Basic chaining and trust-anchors. - Added a managed MD4 implementation to support NTLM authentication. - Added PKCS#8 support to protect private keys - required for PKCS #12. You can track Sebastien’s blog for more up-to-date information on security. Support for .NET 1.2 Some work has begun in various areas to support the .NET 1.2 APIs, although Mono 1.0 will not ship with support for 1.2 APIs, some work is being done to get a head start. Runtime features Martin continued his work on the runtime features to support generics and Zoltan brought in some of the new features from .NET 1.2 to System.Reflection: Dynamic methods and the new Reflection.Emit support for things like type modifiers. ObjectSpaces Implementation on ObjectSpaces has begun: Mark Easton, Richard Thombs and Tim Coleman have started work on this new database system. The current strategy has been to stub out code to get the basics moving, and write unit tests as we go. Crypto Most of the new cryptographic functionality available in .NET 1.2 was already part of Mono.Security or were internal classes of System.Security. Pieter Philippaerts donated this RIPEMD160 managed hash implementation. Added the new classes for the new HMAC and it’s derived companions: HMACMD5,HMACRIPEMD160, HMACSHA256, HMACSHA384 and HMACSHA512 (Sebastien). Added the new PKCS#5 PBDKF2 password based key derivation inRfc2898DeriveBytes (Sebastien). Also new: - System.Security.Cryptography: Complete support for ASN1 data and OID. - System.Security.Cryptography.Pkcs: Started implemention usingMono.Security PKCS#7 support. - System.Security.Cryptography.X509Certificates: Started implementation using Mono.Security X.509 support. Other News Gonzalo has written a couple of new tools to generate an XML map of an API and a tool to compare arbitrary sets of XML API maps. We are now using this in place of our previous “CorCompare” tool to generate the API status pages on the Mono site. The new tools allow us to update those more frequently and they more accurately represent the current library status. Our IL assembler and disassembler are much better and more conforming than before. The people behind this release Roughly 70 developers following developers contributed to this release: Aleksey Demakov, Alexandre Pigolkine, Andreas Nahr, Atsushi Enomoto, Ben Maurer, Bernie Solomon, Carlos A. Barcenilla, Carlos Alberto Cortes, Carlos Guzman Alvarez, Cesar Octavio Lopez Nataren, Christopher Taylor, Daniel Kornhauser, Daniel Morgan, Dave Bettin, David Waite, Dennis Hayes, Dick Porter, Duncan Mak, Eran Domb, Ettore Perazzoli, Fawad Halim, Francisco Figueiredo Jr., Gaurav Vaish, Gert Driesen, Gonzalo Paniagua, Hector E. Gomez, Hye-Shik Chang, Jackson Harper, Jaime Anguiano, Jean-Marc Andre, Jeff Seifert, Jochen Wezel, Joel Basson, Johannes Roith, John Luke, Jonathan Pryor, Jordi Mas, Laurent Morichetti, Lluis Sanchez, Marek Safar, Mark Easton, Martin Baulig, Martin Willemoes Hansen, Miguel de Icaza, Mike Kestner, Nick Drochak, Paolo Molaro, Pedro Martinez, Peter Bartok, Peter Teichman, Peter Williams, Philipp Past, Philip Van Hoof, Pieter Philippaerts, Radek Doulik, Rafael Teixeira, recht@netbsd.org, Reggie Burnett, Richard Thombs, Richard Torkar, Sebastien Pouliot, Sunil Kumar, Tim Coleman, Timothy Parez, Todd Berman, Victor Vatamanescu, Wojciech Polak, Yaron Shkop, Zdravko Tashev and Zoltan Varga. This list is not complete, it is missing contributions that were sent to the list, as it was very hard to track the one million incremental line patch since the last release.
http://www.mono-project.com/docs/about-mono/releases/0.29.0/
CC-MAIN-2018-26
refinedweb
2,803
56.15
Pause the processing of a message #include <sys/neutrino.h> int MsgPause( int rcvid, unsigned cookie ); int MsgPause_r( int rcvid, unsigned cookie ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The MsgPause() and MsgPause_r() kernel calls pause a message. The thread associated with the rcvid must be reply-blocked on a channel that's owned by the calling process. Here's an overview of how you'd use these functions: The deadlock could make (for example) a thread of the user application block on the resource manager, a thread from the resource manager block on procnto, and a procnto thread block on the resource manager. Blocking states None. If priority inheritance causes the priority of the calling thread to drop, other threads may run. 0 on success. If an error occurs:
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/m/msgpause.html
CC-MAIN-2018-43
refinedweb
142
57.67
I'm making a cross platform application which does it's storage in SQLite files. These files are quite big, 10,000,000 in a table. When I open the file I run a query to count the amount of rows in the table. My code, using the sqlite3 module: - Code: Select all def runquery(con): # con is a sqlite3 connection object with con: cur = con.cursor() cur.execute("SELECT COUNT(rowid) FROM snp",[]) return cur.fetchall()[0][0] Execute time for a table with 10,000,000 rows: - Kubuntu, 4 gb ram, dualcore: 8s - Windows XP-32, 2 GB Ram, dualcore: 15m32s - Win7-64, 4 GB RAM, I5: 13m15s During execution, hardly any memory or cpu power is used, so no bottleneck there. When I run the query through the sqlite3.exe shell it is as fast as the Linux implementation. I think this means that the python code is to blame for the bad performance. It's the cur.execute line that takes so long to execute. Anyone knows why the big difference betwene Windows and Linux? And more important, how can I imporve the performance, so it will work as fast as the Linux machine. It's unusable right now. I'm using Python 2.7.5, fresh installed today on the machines.
http://www.python-forum.org/viewtopic.php?p=7260
CC-MAIN-2016-50
refinedweb
216
76.11
wrapperTutorial Overview Objective: Learn the architecture of wrapper S-functions and how to create an inlined wrapper S-function using TLC. Folder: (open) matlabroot/toolbox/rtw/rtwdemos/tlctutorial/wrapper Wrapper S-functions enable you to use existing C functions without fully rewriting them in the context of Simulink® S-functions. Each wrapper you provide is an S-function “shell” that merely calls one or more existing, external functions. This tutorial explains and illustrates wrappers as follows: Why Wrap User Code? — Reason for building TLC wrapper functions Getting Started — Set up the wrapper exercise Generate Code Without a Wrapper — How the code generator handles external functions by default Generate Code Using a Wrapper — Bypass the API overhead Many Simulink users want to build models incorporating algorithms that they have already coded, implemented, and tested in a high-level language. Typically, such code is brought into Simulink as S-functions. To generate an external application that integrates user code, you can take several approaches: You can construct an S-function from user code that hooks it to the Simulink generic API. This is the simplest approach, but sacrifices efficiency for standalone applications. You can inline the S-function, reimplementing it as a TLC file. This improves efficiency, but takes time and effort, can introduce errors into working code, and leads to two sets of code to maintain for each algorithm, unless you use the Legacy Code Tool (see Import Calls to External Code into Generated Code with Legacy Code Tool). You can inline the S-function via a TLC wrapper function. By doing so, you need to create only a small amount of TLC code, and the algorithm can remain coded in its existing form. The next figure illustrates how S-function wrappers operate. Wrapping a function eliminates the need to recode it, requiring only a bit of extra TLC code to integrate it. Wrappers also enable object modules or libraries to be used in S-functions. This may be the only way to deploy functions for which source code is unavailable, and also allows users to distribute models to others without divulging implementation details that may be proprietary. For example, you might have an existing object file compiled for a processor on which Simulink does not run. You can write a dummy C S-function and use a TLC wrapper that calls the external function, despite not having its source code. You could similarly access functions in a library of algorithms optimized for the target processor. Accomplishing this requires making changes to a template makefile, or otherwise providing a means to link against the library. Note Object files that lack source code and are created with Microsoft® Visual C and Microsoft Visual C++® Compiler (MSVC) work only with MSVC. The only restriction on S-function wrappers is for the number of block inputs and outputs match number of inputs and outputs of the wrapped external function. Wrapper code may include computations, but usually these are limited to transforming values (for example, scaling or reformatting) passed to and from the wrapped external functions. In the example folder, the “external function” is found in the file my_alg.c. You are also provided with a C S-function called wrapsfcn.c that integrates my_alg.c into Simulink. Set up the exercise as follows: Make tlctutorial/wrapper your current folder. In MATLAB®, open the model externalcode from your working folder. The block diagram looks like this: Activate the Scope block by double-clicking it. Run the model (from the Simulation tab, or type Ctrl+T). You will get an error telling you that wrapsfcn does not exist. Can you figure out why? The error occurs because a mex file does not exist for wrapsfcn. To rectify this, in the MATLAB Command Window type mex wrapsfcn.c Note An error might occur if you have not previously run mex -setup. Run the simulation again with the S-function present. The S-Function block multiplies its input by two. Looking at the Scope block, you see a sine wave that oscillates between -2.0 and 2.0. The variable yout that is created in your MATLAB workspace steps through these values. In the remainder of the exercise, you build and run a standalone version of the model, then write some TLC code that allows the code generator to build a standalone executable that calls the S-function my_alg.c directly. Before creating a wrapper, generate code that uses the Simulink generic API. The first step is to build a standalone model. On the C Code tab, click Build. The code generator creates the standalone program in your working folder and places the source and object files in your build folder. The file will be called externalcode.exe on Microsoft Windows® platforms or externalcode on UNIX® platforms. As it generates the program, the code generator reports its progress in the MATLAB Command Window. The final lines are: ### Created executable: externalcode.exe ### Successful completion of build procedure for model: externalcode Run the standalone program to see that it behaves the same as the Simulink version. There should not be differences. !externalcode ** starting the model ** ** created externalcode.mat ** Notice this line in wrapsfcn.c: #include "my_alg.c" This pulls in the external function. That function consists entirely of /* * Copyright 1994-2002 The MathWorks, Inc. */ double my_alg(double u) { return(u * 2.0); } Inspect the mdlOutputs() function of the code in wrapsfcn.c to see how the external function is called. static void mdlOutputs(SimStruct *S, int tid) { int_T i; InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0); real_T *y = ssGetOutputPortRealSignal(S,0); int_T width = ssGetOutputPortWidth(S,0); *y = my_alg(*uPtrs[0]); } Tip For UNIX platforms, run the executable program in the Command Window with the syntax !./ executable_name. If preferred, run the executable program from an OS shell with the syntax ./ executable_name. For more information, see Run External Commands, Scripts, and Programs. Generally, functions to be wrapped are either included in the wrapper, as above, or, when object modules are being wrapped, resolved at link time. To create a wrapper for the external function my_alg.c, you need to construct a TLC file that embodies its calling function, wrapsfcn.c. The TLC file must generate C code that provides: A function prototype for the external function that returns a double, and passes the input double u. A function call to my_alg() in the outputs section of the code. To create a wrapper for my_alg(), do the following: Open the file change_wrapsfcn.tlc in your editor, and add lines of code where comments indicate to create a workable wrapper. Save the edited file as wrapsfcn.tlc. It must have the same name as the S-function block that uses it or TLC is not called to inline code. In MATLAB, open the model externalcode from your working folder. Activate the Scope block by double-clicking it, and run the model (from the Simulation tab, or type Ctrl+T). This gives you a baseline result. Inform Simulink that your code has an external reference to be resolved. To update the model’s parameters, in the MATLAB Command Window, do one of the following: Type set_param('externalcode/S-Function','SFunctionModules','my_alg') In the S-Function block parameters dialog box, in the S-function modules field, specify 'my_alg'. Create the standalone application, by entering one of the following commands in the Command Window: slbuild('my_alg','ForceTopModelBuild',true) slbuild('my_alg', 'StandaloneCoderTarget','ForceTopModelBuild',true) These commands force the code generator to rebuild the top model, which is required when you make changes associated with external or custom code. Alternatively, you can force regeneration of top model code by deleting folders in the code generation folder, such as slprj or the generated model code folder. For more information, see Control Regeneration of Top Model Code. Run the new standalone application and verify that it yields identical results as in the scope window. !externalcode If you had problems building the application: Find the error messages and try to determine what files are at fault, paying attention to which step (code generation, compiling, linking) failed. Be sure you issued the set_param() command as specified above. Chances are that problems can be traced to your TLC file. It may be helpful to use TLC debugger to step through wrapsfcn.tlc. As a last resort, look at wrapsfcn.tlc in the solutions/tlc_solution folder, also listed below: %% File : wrapsfcn.tlc %% Abstract: %% Example tlc file for S-function wrapsfcn.c %% %% Copyright 1994-2002 The MathWorks, Inc. %% %% %implements "wrapsfcn" "C" %% Function: BlockTypeSetup ================================ %% Abstract: %% Create function prototype in model.h as: %% "extern double my_alg(double u);" %% %function BlockTypeSetup(block, system) void %openfile buffer %% ASSIGNMENT: PROVIDE A LINE OF CODE AS A FUNCTION PROTOTYPE %% FOR "my_alg" AS DESCRIBED IN THE WRAPPER TLC ASSIGNMENT extern double my_alg(double "wrapfcn" %<y> = my_alg( %<u> ); %endfunction %% Outputs Look at the highlighted lines. Did you declare my_alg() as extern double? Did you call my_alg() with the expected input and output? Fix mistakes and rebuild the model.
https://fr.mathworks.com/help/ecoder/ug/wrapping-user-code-with-tlc.html
CC-MAIN-2021-49
refinedweb
1,492
56.25
Agenda See also: IRC log <mhausenblas> ok, I guess we're set and ready! <cygri> member:zakim, who is on the phone? <cygri> member:zakim who is on the phone? <cygri> zakim BartvanLeeuwen is with Galway <sandro> I'm thinking skype is the best bet. <sandro> (with sound turned off) <mhausenblas> the only thing we now need (for both Zakim and skype) is .... <mhausenblas> Washington! :) <sandro> ( who is dvilasuero ? ) <cygri> sandro, dvialasuero is daniel vila from madrid <cygri> it's richard.cyganiak <mhausenblas> trackbot, start telecon <trackbot> Date: 25 January 2012 <mhausenblas> scribenick: mhausenblas <bhyland> ping <sandro> pong bhyland <sandro> GUEST: Gofran Shakair <sandro> GUEST: Deirdre Lee PhilA: I'm in Galway, W3C staff ... I've been working on vocabularies, ADMS, DCAT, organisation ontology dvilasuero: In Galway, Master student with Boris (UPM) from Spain fadi: In Galway, finished my MSc on Publishing Linked Gov Data, Google Refine, DCAT boris: In Galway, UPM, we do Linked Government Data in Spain, will help facility vocab <PhilA> mhausenblas: I'm co-hosting here. Head Linked Data section here at DERI cygri: In Galway, LiDRC at DERI as well, I'm focusing on vocabs (DCAT, DataCube) and also other WG (RDF, RDB2RDF) ... I'd like to learn about requirement for DataCube vocab, also DCAT BartvanLeeuwen: In Galway - I'm a Semantic Fire Fighter from A'dam ... doing Linked Open Data, looking for advise for best practices and share again <PhilA> Note to self, need to talk to fadi about Dan Smith's work on Refine Extensions csarven: In Galway, MSc in LiDRC, with Michael and Richard, working on data-gov.ie, tooling around this GofranS: In Galway, MSc students in eGov unit at DERI, focusing on metadata i18y, ADMS DeirdreLee: In Galway, heading the eGov unit in DERI, working with Vassilios of the EC ... we're doing Open Data, policies, etc. ... for example, DCAT is of interest BenediktKaempgen: In Galway, from FZI in Karlsruhe, Germany ... into business intelligence, interested to provide feedback for DataCube and other related efforts ... such as SKOS extension for hierarchy ... as well as versioning input ... we've published Eurostat and XBRL data Spyros: In Galway, IBM SCTC in Dublin, we are into Linked Open Data publishing (dublinked.ie) ... we do data management for Smart Cities using Linked Data <sandro> first/last name spelling? <sandro> I think I have everyone but Spyros on <sandro> got it. <rreck> sheesh, it took 4 tries and then dropped <cygri> cmusialek: Chris Musialek, working on data.gov <George> cmusialek: GSA Data.gov lead, working on vocab.data.gov and other related GLD for Data.gov <George> t_gheen: One World Law Library <rreck> whew, i called in 9 times <bhyland> ping pong <George> t_gheen: Library of Congress <bhyland> Introducing George Thomas from US HEaltha & Human Services <George> bhyland: 3RoundStones, GLD co-chair, US Gov LD initiatives (EPA), strong open source product orientation, more on Web Arch, Data Mgmt <George> ... better tooling for Web2.0 app dev's for using RDF stack tech <George> ... <George> objectives for F2F2 - focus on enabling aspects for GLD publishers, how to roll out LD projects <George> ... value add to augment tech chops with mgmt understanding <cygri> me sandro, it's Gofran Shukair and Benedikt Kämpgen <George> Yigal (not in IRC) - working on Gov Grant vocab - <George> ... been working with Gov Data for a long time, worked with Dan Gillman (BLS) <George> Mike Pendleton (not on IRC) - EPA - doing LD projects, new approaches to data warehousing and publishing using LD <George> ... interest and contribution in Procurement <George> Anne Washington (not on IRC) from George Mason University, Professor Public Policy, bkgrnd CS and IS <George> ... interest and bckgrnd in Dig Archives, preservation incl metadata <sandro> Okay, has everyone correctly listed (I think). <George> ... need for external 'non-branded' info in determining scope and direction of GLD projects <George> ... part of the W3C eGov IG <sandro> <George> Dan Gillman (not yet on IRC) <George> BLS, DC F2F2 host <rreck> where is the video ? <olyerickson> @bhyland I have been on in car, just arrived at TWCRPI <George> ... involved with metadata standards and requirements for access to statistical data (for 'quite some time' :) <George> ... got involved with GLD through chair role of Open Gov Vocab WG (part of Fed CIO Council Data Arch Subcmt) <George> ... interest in synergy and application of W3C/GLD to BLS data <bhyland> w? <bhyland> q/ <George> olyerickson: Dir of Web Science Ops at TWC RPI <George> ... project lead for logd.twc.rpi.edu - int gov cat search demo, govpedia.org project, others <George> ... interest in firming up international BP guidance for GLD, co-leading URI construction session later today, also vocab rec's esp DCAT, (other good collab mojo) <George> sandro: W3C primary staff contact with PhilA, key interest is making SemWeb work, GLD all ++, QB??, more :) <George> GeraldSteeman: NASA S&T Info Prg Office, deliverable reviewer from lay-person persp, general interest in GLD <George> ... bhyland adds contibutions from Gerald incl outreach at high levels <George> DaveReynolds: SW/LD long timer, CTO Epimorphics, UK Pub Sector - data.gov.uk (variety of offices/agencies), vocab work - Org Ont (UK Organogram with cygri and JT), QB, LDA co-developer (great stuff!), variety of edu/env publishing scribe: Linked Data API see <George> ... interests - mostly vocab with cygri etal <cygri> simonWall? <PhilA> Picking up on DaveReynolds comments about the org ontology being used for organograms - here's an example <George> simonWall: morning! Dir of Data Mgmt Australian Bu of Stats - working on standardizing statistical data/metadata, statistics/statistics/statistics <sandro> simonWall: I lead the Data Management Section at the Australian Bureau of Statistics (). (in Canberra) <George> ... unlike (sandro ;), most interested in QB vocab, role as influencer of international stat community, interest in LD, and W3 membership <George> ... is alive and well :) <George> rreck: consultant in Wash DC, masters in comp linguistics, textual data & RDF thesis, published, working in law enforcement, working with vocabs, 3rd W3C (GRDDL, other?) group <George> ... review props that influence stability of GLD, collab with AnneW <cgueret_work> I'm here but you don't hear me <cgueret_work> it's christophe gueret <cygri> christophe gueret <cgueret_work> from the VU <cgueret_work> yep <cgueret_work> should be <cgueret_work> <cgueret_work> :/ <cgueret_work> that's me :) <cgueret_work> thx :) <bhyland> Please look at <cygri> <sandro> cygri: we have a draft spec <BenediktKaempgen> Wiki page: <sandro> cygri: started in 2010, that's the current status : cygri: recently not that much activity re consumption ... working on a generic client for any kind of DataCube data ... we have quite some issues in the queue raised by people that have been using DataCube ... suggestions for improvements and extensions (incl. from BenediktKaempgen) ... next steps are ... transferring the issues to GLD tracker <cygri> cygri: as well as discuss extensions in GLD <Zakim> mhausenblas, you wanted to update on Gishlain status cygri: additionally we want to publish the current spec as a FPWD in the GLD ... I do have an action on it anyways ... in order to improve DataCube we should take into consideration all the valuable feedback ... need to find a balance between quickly getting out a FPWD on it vs. incorporating the feedback <BenediktKaempgen> +q <simonWall> +q <Zakim> mhausenblas, you wanted to still update on G.'s status ;) <Zakim> DaveReynolds, you wanted to agree with Richard :) Michael: Seems Gihslain will join G'way later today DaveReynolds: Agree with what cygri said ... need a canonical issues list and a FPWD of DataCube spec ... need to remove ambiguities in the spec ... folding in the experience from practice ... DataCube has been used by a number of groups now, already ... some co-ordination is needed ... esp. re aggregation there has been quite some development in the SDMX world <cygri> DaveReynolds: coordination with standards from the Observations&Measurements area bhyland: Are people happy enough to move to the W3C space? cygri: I think GLD is the appropriate space for this, yes ... so far the work has happened in an informal space (cf. Google code repo) <t_gheen> bhyland: what do we need to do? are the documents in good shape? How do we move forward and raise awareness? PhilA: From a process point of view we need to create a product for DataCube in the GLD tracker ... and also for future products (DCAT, etc.) as currently there is only one product cygri: Positiv <scribe> ACTION: PhilA to add products on issue tracker [recorded in] <trackbot> Created ACTION-29 - Add products on issue tracker [on Phil Archer - due 2012-02-01]. <cygri> ACTION: cygri to produce editor's draft of Data Cube spec [recorded in] <trackbot> Created ACTION-30 - Produce editor's draft of Data Cube spec [on Richard Cyganiak - due 2012-02-01]. Michael: I assume FPWD of DataCube will be available together with the other FPWD on BP, etc.? ... which would mean: soon <DaveReynolds> Agree with cygri that once have first working draft is a good time to seek feedback. BenediktKaempgen: Question re issues ... how will they be grouped ... Also, questions regarding consumption side <DaveReynolds> We do see groups consuming live Data Cube data, including iPhone apps. So there is some active use to learn from. cygri: My take on this is that the scope is backed up by the charter ... so we need to be careful regarding how far we go, can't stray too far from this ... but it's important that we're compatible with other related works such as DDI ... agree with co-ordination with others, yes <DaveReynolds> Agree with Richard, keep scope narrow as currently defined, but do a good job of co-ordination. cygri: regarding consumption tools - we're producing a vocab, not a processor <sandro> the charter says: ." <sandro> precended by: "The group will also produce documentation, examples, and, optionally, test cases and OWL ontologies for these vocabularies." cygri: though, feedback from DataCube consumers would be beneficial <Zakim> cygri, you wanted to talk about use cases <sandro> on <sandro> mhausenblas, it's optional. <bhyland> Question: Is this correct wiki page for updating the WG on progress, <DaveReynolds> mhausenblas: it currently is OWL (for values of "OWL" that are basically RDFS :)) simonWall: we're very active in the SDMX and DataCube space cygri: Would like to raise one more issue - does it make sense to also document use cases? Michael: +1 to use cases <bhyland> cygri: Does it make sense to document use cases for vocabularies? <PhilA> use cases are always good... Michael: Yes, we're backed up by charter (cf. 'examples') <bhyland> cygri: I think it is a good reality check to resolve design criteria issues. Helps with clarity <PhilA> Although UCS are probably best recorded in a separate document cygri: Matter of resources in the working group <bhyland> cygri: Do we have the resources in the group to document use cases. <BenediktKaempgen> +1 to use cases <simonWall> +1 for use cases <dvilasuero> +1 for use cases <t_gheen> bhyland: we are writing docs for real working people, so mapping to real world is important <cgueret_work> +1 to bhyland <t_gheen> bhyland: where is the wiki page to update progress for this? <BenediktKaempgen> eg., <bhyland> Is this correct wiki page for updating the WG on progress, cygri: AFAIK there is no single page that captures the current status ... not really updated, also <BenediktKaempgen> I updated it recently a bit. <t_gheen> bhyland: recommend creating a high level page to organize the information <t_gheen> ... can people devote time to this effort over the next few months? <Zakim> DaveReynolds, you wanted to talk about examples DaveReynolds: Yes, I can commit some time in the next 5 month, rather at the end ... re UC, there are different needs ... real data samples <George> +1 DaveReynolds +1 as well <simonWall> +1 too <rreck> oh too bad we didnt do it in google+ so others could have joined DaveReynolds: UC in the sense cygri was talking about vs. real world samples <sandro> rreck, maybe during a break we can experiment with other vid tech. Michael: both would be good! <sandro> rreck, also, I gather this is a commercial skype account that can do multi-way. <rreck> oh? DaveReynolds: also valuable to evangelise to document the usage ... but not in the spec but a separate doc <George> DaveReynolds: additional note on how case-study/examples realize use cases Michael: Agree with DaveReynolds to have a separate non-REC-Track doc on UC 1- <PhilA> Sounds to me as if bhyland is talking about usage guidelines? <sandro> or tutorials? not sure. <t_gheen> bhyland: who can work on this? <bhyland> Committment for DataCube/SDMX work offered by DaveReynolds, Richard, others? <simonWall> +q <bhyland> Add SimonWall to the list. simonWall: count me in re UC <PhilA> So the people working on the qb data are DaveReynolds, cygri, simonWall <BenediktKaempgen> You can count me in also. <t_gheen> bhyland: simonWall, DaveReynolds, cygri <olyerickson> is there a Skype ccall that one could be included in for video? <BenediktKaempgen> PhilA, can you add me, too? boris: Please look at the slides at <olyerickson> ...or is it only DC/Galway>? <PhilA> So the people working on the qb data are DaveReynolds, cygri, simonWall, mhausenblas, BenediktKaempgen <boris> <cygri> boris: starting presentation on vocabulary selection <cygri> ... charter says we need to provide guidelines to governments <cygri> ... RDF requires specific domain terms in order to provide a certain domain <cygri> ... modelling is important phase in data lifecycle <bhyland> ping pong <cygri> ... (showing different data lifecycle models, they all have a modelling phase) <cygri> ... big picture: 1. search for existing vocabularies in various search engines/repositories <cygri> ... 2. if suitable is found, re-use it <cygri> ... 3. otherwise, search for suitable thesauri etc <cygri> ... 4. if those exist, build a vocabulary by transforming these resources into RDFS <cygri> ... 5. otherwise, build from scratch. this happens if the domain is very new or complex. but doesn't happen so often <bhyland> Encourage interactivity IMO <bhyland> lol, co-chairs differ ;-) <George> :) <cygri> boris: there are multiple repositories for searching vocabularies, but no one definitive <bhyland> No one central place to find a vocab is a feature, not a bug :-) <cygri> ... (summary table of available repositories) Michael: ontologi.es is in fact Toby Inkster ;) <cygri> boris: there are no guidelines to help developers to decide which engine/repo to use <olyerickson> Note that DataFAQs <> will soon provide a statistical vocabulary ranking service based on use in the LOD cloud. I've asked them for a statement as to how this will work. Note also that they will provide a commmunity vocab ranking service soon as well Michael: re relevant vocabs - ORG seems to be missing? <cygri> boris: (summary list of gov-relevant vocabs) <bhyland> @Michael, noted. I'll add. <bhyland> This is a partial list <cygri> ... probably need to include a few more Michael: re vocabulary prefixes - my advise is simple - use prefix.cc <cygri> ... there is a list of popular prefixes from the RDFa group <DaveReynolds> Vocabulary list: would like to see org on there :) <GofranShukair> also DOAP is missing <DaveReynolds> DOAP is on the previous list <GofranShukair> yeah sorry now i see it :( <DaveReynolds> But wasn't on the prefix list I don't think. <cygri> boris: (demo of LOV - ) <DaveReynolds> Not sure about BIBO as the one and only vocab in that area to single out, but not my field. <cygri> boris: criteria for selecting a particular vocab/ontology <dvilasuero> definately, if we have BIBO there we should have some other important library vocabs <George> LOV search - nice <cygri> ... usage, maintenance, coverage, etc etc <cygri> ... tools for building vocabularies: neologism, protege, ... <cygri> (LOV people are: Bertrand Vatant and Pierre-Yves Vandenbussche) <BenediktKaempgen> +q <Zakim> mhausenblas, you wanted to note re suitability <cygri> mhausenblas: what is “suitable”? how do you define this? <George> mhausenblas: what is 'suitable'? <cygri> ... give concrete advice how to figure out which competing vocabulary to use <cygri> ... and advice when it makes sense to build your own <George> ime suitability is often a vocab combo - ie org + vcard <cygri> ... also important for suitability: does my data sparql well if expressed in this vocab? <cygri> ... existence of multiple repos/engines not a problem. they do different things <cygri> ... some crawl, some are curated <olyerickson> I've asked DataFAQs people to compare/contrast their vocab ranking capability with LOV vocab ranking. <cygri> ... if we had the resources: meta search engine? <George> +1 vocab metacrawler at w3 <cygri> ... would have value if run at W3C <cygri> ... our best practice document will be frozen in time, so static lists will go out of date <olyerickson> +1 to more than vocab search; need ranking "vocabRank" or "schemaRank" <cygri> ... perishable info should maybe not go in there <bhyland> The Best Practices Recommendation document will be almost "frozen" as of the publication data. The way we'll add flexibility to the Vocabs is through the community driven LOD Cookbook. cygri: Agree with Michael <bhyland> +1 to Michael <olyerickson> GLD recommendation for "high quality" linked data is to use widely-used, relevant vocabularies *correctly* cygri: we should avoid to create concrete suggestions what are suitable vocabs - it's arbitrary <George> these are two diff gld deliverables tho - selection, and recommended <olyerickson> The question is, how to find vocabs (a) in wide use (b) whether they are relevant <DaveReynolds> +1 to Michael and Richard, W3C shouldn't be maintainer of such lists, especially not if that has implications on procurement cygri: I'd like to see guidance on how to use the tools (check lists) to determine what is relevant, quality, etc, <bhyland> Cygri: For this WG, suggest that we have a basic sets of questions we ask the maintainer. We don't want to arbitrarily add vocabs. <olyerickson> +1 to DaveReynolds ( by default ;) ) boris: I agree with both Richard and Michael said <olyerickson> I think surveys/questionaires/etc don't scale <George> recommendation for domain agnostic - cross cutting vocabs for all GLD publishers... <cygri> bhyland: what do you mean by implications on procurement? <George> snapshot problem regarding procurement and inclusion on some 'list' like a gld deliverable <olyerickson> I think we should leverage the presence of vocabs "in the wild" (ie LOD Cloud) to assist selection <Zakim> PhilA, you wanted to agree with mhausenblas and add a bit more <cygri> mhausenblas: it's a competitive advantage if my vocab is w3c-listed and yours isn't. best practice document will be frozen in time <cygri> PhilA: here are some criteria: <cygri> ... 1. permanence of domain name <cygri> ... for example, LOV service URL looks not permanent. that's bad. <George> gov consortium mandates are nice ... <rreck> I think we should call URLs URLs not URIs <cygri> ... 2. change control. who's in charge of changing it? <cygri> ... dublin core has a large committee in charge, so changing it is hard. that's good <cygri> ... 3. is it actually used in the wild? <cygri> ... we should point out these criteria even if it may be very hard to evaluate in practice <cygri> +1 to all PhilA said <cygri> BartvanLeeuwen: should also point out that local language documentation is important <sandro> +1 BartvanLeeuwen -- another criterion is support for multiple languages, eg in the documentation for the vocabulary <cgueret_work> +1 too <GofranShukair> +1 too <cygri> ... ideally, vocabularies should have documentation in multiple languages <cgueret_work> vocabs should be properly described in several languages Michael: We need to distinguish between vocab discovery and vocab creation guidelines, I believe <cygri> boris: most vocabs are english but governments speak all sorts of languages. we have work in progress on how to express multilingual vocabs on the web of data <George> GofranShukair: ADMS <cygri> GofranShukair: ADMS describes semantic assets. that includes vocabularies <GofranShukair> <cygri> ... we describe metadata, incl language <cygri> ... ready for review <boris> I can take the action <cgueret_work> will be pleased to contribute with French concerns <scribe> ACTION: boris to create a Wiki page on multi-lingualism of vocabs [recorded in] <trackbot> Created ACTION-31 - Create a Wiki page on multi-lingualism of vocabs [on Boris Villazón-Terrazas - due 2012-02-01]. <cygri> bhyland: multilingual issues are important. awareness should be raised. please, write a blurb on this <GofranShukair> <olyerickson> In addition to the multilingual vocab issue, there is the multilingual instance data issue --- english predicates but literals in other languages. <cygri> bhyland: having criteria for inclusion of vocabularies is important. let us draft a list of vocabularies. <cygri> ... where is it hosted? university? production system? what's the institution's commitment to maintenance? <cygri> ... we should work on such a checklist over the next two days <sandro> +1000 <cgueret_work> +1 Michael: we should maybe also talk about how vocab management (what is the process to add new terms? who owns the namespace? hit-by-truck scenario) <Zakim> mhausenblas, you wanted to discuss change control and vocab ownership <PhilA> +1 to bernadette's suggestions for capturing criteria for vocab selection <cygri> mhausenblas: there can be issues around ownership of namespace, hit by bus risk etc <rreck> +1 namespace ownership problems <George> mhausenblas: namespace ownership, distinguish btw discovery, management, creation advice - more will discover than create - <cygri> ... need to distinguish between vocabulary search and vocabulary creation. different issues <sandro> +1 bhyland: during these two days let's start the checklist of things people need to look for in deciding whether a vocab is good enough, such as stability, domain name, point of contact, etc. <rreck> I have had commercial clients unwilling to use existing namespaces because of copyright exposure <cygri> ... experience shows that something can start informally and move to something more formal, e.g. story of VoID <PhilA> PhilA: notes that danbri has solved the "what happens if I go under a bus" issue through an agreement with DCMI (so FOAF is as stable as DC) <sandro> ( I don't think bhland said we should produce a list of vocabs. ) <cygri> ... so we can say there's a process that can take you from informal work to something permanent and fit for purpose <cygri> mhausenblas: i like checklists <rreck> +1 +1 to sandro's ' fears/nightmare-scenarios' <sandro> charter quote: ." <sandro> +1 cygri: don't list vocabs, just list how to evaluate vocabs Michael: Does the WG interpret this in the sense of 'we provide checklist how to' or rather 'list concrete vocabs'? ... I'd very much prefer the former <George> cygri: lists of recommended vocabs in bp vocab selection? instead, criteria list for selection - then there's std vocabs for cross cutting GLD publisher concerns - nice delineation +1 <simonWall> +1 <cygri> sandro: i agree. arbitrary lists would be a problem <DaveReynolds> +1 to cygri, criteria not lists <cygri> sandro: we might explain that criteria list in terms of "nightmare scenarios" <George> sandro: how to write this 'checklist' - nice to explain in terms of issues/challenges (fears/nightmare-scenarios) <George> +1 cygri <cygri> ... "here are possible things that could go wrong. check how the vocabulary or its maintainers deals with that" <cygri> ... this would bring it to life <cygri> bhyland: i agree but can we put a positive spin on it? <Zakim> sandro, you wanted to suggest the document include fears/nightmare-scenarios <cygri> PhilA: for the record: it would be horrible if danbri was hit by a bus. <Zakim> PhilA, you wanted to make 2 suggestions for vocab selection if you want me to, or I'll park it if time is short <cygri> PhilA: national part of domains matter <cygri> ... but you can use .us in .ie <cgueret_work> +1 to PhilA <cygri> ... multilingual: want to use dublin core in finnish? don't reinvent it. provide a translation with finnish labels <BartvanLeeuwen> +1 to PhilA <George> cygri: +1 provide labels for existing vocab/namespace <rreck> we should mention Z39.19? <George> ... common issue/problem/mistake <simonWall> The Finnish National Library maintains the Finnish version of Dublin Core... <rreck> skos <George> mhausenblas: label as 'quality requirement' <cygri> mhausenblas: some quality criteria can be expressed as sparql queries <cygri> ... for example presence of labels <PhilA> PhilA: chose Finnish at random - but good to see that my entirely random choice is ahead of the game, simonWall <cygri> ACTION: mhausenblas to compile first version of vocabulary selection quality checklist [recorded in] <trackbot> Created ACTION-32 - Compile first version of vocabulary selection quality checklist [on Michael Hausenblas - due 2012-02-01]. <DaveReynolds> Having the label in the URI for vocab terms is a multi-language issue for some folks. There is genuine argument on both sides whether opaque URIs + labels in all languages is better than having one preferred language reflected in the URIs. Michael: Z39.19 sounds interesting indeed, thanks rreck! <simonWall> Point taken (I googled that one; I do know that the New Zealand National Library maintains the Maori version of DC though.) <cygri> ACTION-31? <trackbot> ACTION-31 -- Boris Villazón-Terrazas to create a Wiki page on multi-lingualism of vocabs -- due 2012-02-01 -- OPEN <trackbot> <dvilasuero> *mhausenblas: i could help with that action <rreck> i have done alot of work with z39.19 and multi-lingual representation <cygri> DaveReynolds, do you have some pointers re multilingual URIs? would be good to include the debate in that wiki page <SpyrosKotoulas> <cygri> scribenick: BenediktKaempgen <DaveReynolds> cygri: would have to dig, the OBO world has best practice advice on using opaque URIs which might be relevant. Also I have annedotal evidence though would need to be circumspect about to phrase that in public :) Spyros: On Dublin data rdfized to RDF ... what is legacy data? Is gov supposed to transform all data (e..g., pdfs, scan, xsl)? ... most data from relational db <dvilasuero> cygri: we also have a paper for las dc conf on multilingual URIs <dvilasuero> where we review obo and others Spyros: often also: geo data, temporal data (statistics), record oriented relational data (e.g., about citizens) <PhilA> Spyros' slides are now linked from the agenda <PhilA> scribe: BenediktKaempgen Spyros: concerns: privacy issues (who can assess whether something is privacy sensitive?), how much to publish (efficiently, considering the costs), ... <bhyland> ping Spyros: considering risks with opening up data; how about institutions that are not quite government <bhyland> Sorry is this is a repeat, per the charter on legacy data: "Legacy Data. The group will produce specific advice concerning how to expose legacy data, data which is being maintained in pre-existing (non-linked-data) systems. Spyros: also technical issues: architecture, what visualizations (applications consuming data), how to facilitate use by non-experts ... how to automate such processes ... how to provide guidance/template/references/cookbook for processes ... transforming data into RDF often possible but might be awkward <Zakim> mhausenblas, you wanted to comment on the term 'legacy data' and to discuss prioritisation of data sources - demand driven <olyerickson> I think we should consider referring to "data life cycle" ala (DDI Alliance) mhausenblas: two reactions: term legacy data, maybe we should use a different term (e.g., raw data) <davidwood_> bhyland, please check your phone for immediate text message requiring your action. Sorry to interrupt. <olyerickson> I think the core question is, what best practices for data life cycle management should this group make that pertain to GLD? mhausenblas: Secondly, question always: where to start publishing data? Uptake then further drives publishing process. User-pull rather than publisher-push. <Zakim> DaveReynolds, you wanted to ask what makes this 'legacy' <George> me thinks we're talking about exposing RDB's ergo R2RML <mhausenblas> Michael: re multimedia interlinking see DaveReynolds: RDF can walk along "legacy"/raw data ... Representing key parts in raw data/legacy is difficult. <George> +1 - exposing these existing/emerging W3 works for this Richard: We should list related work (R2RML, M, Griddle, xslt...) <mhausenblas> cygri: There are a number of existing W3C standards that already address the transformation part (R2RML, GRDDL, etc.) <olyerickson> I think the real issue is how to integrate LD best practices with your existing data life cycle management infrastructure <mhausenblas> +1 to what olyerickson <t_gheen> bhyland: Spyros points out how broad the description of legacy data is in the charter <t_gheen> ... we should set some boundaries <dvilasuero> +1 olyericksson Bhyland: How to bound this topic? <mhausenblas> s/what olyerickson/what olyerickson said <cygri> +1 to byhland. bounding is important <mhausenblas> 1+ <mhausenblas> Michael: Scope should be on W3C standards and then expand <olyerickson> @bhyland please re-state what to take a stab at... <bhyland> bhyland: the charter is very broad in the description of what is to be included in the "Legacy" section of the BP Recommendation. mhausenblas: What resources are available? <bhyland> We need to bound it. Suggest we put some lines in the sand as to what is "in" and we'll be able to reasonably do within the next 6 mos in this WG. <George> mhausenblas: IBM Biplav/Spiros resource committment to drive expeccted 'legacy' contribution <bhyland> Spyros is here on behalf of IBM and is an invited guest of the F2F. Thus, he cannot make make committments for IBM to this WG. <cygri> mhausenblas: if we go for a broad interpretation of this topic, then we need people and volunteers cygri: Agree with boundaries. Good starting point would be W3C standards. <rreck> better arbitrary than nothing? cygri: E.g., it would be helpful to describe tools. Risk to be arbitrary with inclusion. <George> cygri: standards, tools, approaches cygri: Also useful to describe approaches, e.g., for modelling. <olyerickson> Hmmm...this is the first time I realized we were talking about CONVERSION cygri: There should be experiences in WG to give recommendations on such processes. <mhausenblas> Michael: Against listing tools explicit, but rather provide examples of tool catalogs such as found and a <Zakim> mhausenblas, you wanted to discuss tools <bhyland_> We have some of the content Cygri is describing in the current LOD cookbook, especially as it relates to the auto conversion vs. human-involved modeling. <rreck> +1 point at the wiki makes good sense mhausenblas: Problem with tools is that they can get outdated. <cygri> olyerickson: i converted a price from dollars to pounds recently mhausenblas: Similar to Vocabulary case, have a checklist. <bhyland_> MichaelH: His bias is on describing checklist approach rather than a specific list of tools which will become dated over time. <olyerickson> @cygri that's the "right" direction, isn't it? DeirdreLee: Agrees with not describing tools. But in case of vocabularies makes sense. ... Users demands would help with legacy issues. cygri: Agrees with seeing transforming legacy data as a process that needs to be a compromise of effort and benefit. Start with metadata, concept schemes, and later go on with the acutal raw data. Looking at users will really be useful. <stasinos> cf. <bhyland_> cygri: Handling legacy AKA "raw data" has some logical starting points and (could go on infinitely). Address misconceptions about converting to RDF as an "augmentation" to existing system. Others convert to RDF and that is it. <olyerickson> +1 to cygri cygri: Important w.r.t. legacy data: What does it actually mean? What does it implicate? Regarding on the situation, specific approaches may make more sense than others (e.g., transformaing most data into RDF). <mhausenblas> Michael: Suggest to think along TimBL's 5 star scheme olyerickson: Discussion about legacy is not usefull if not seen from perspective of a certain scenario. Best-practice they need is to continuously manage their data. <George> Refine+DERI_extensions and R2RML covers 80% of the GLD publisher waterfront afaic - i'd love to see standards, tools, approaches covering spreadsheets and RDB's <cygri> olyerickson, i didn't see the link you mentioned? <rreck> +1 concrete examples are essential <DaveReynolds> +1 to olyerikson - focus on Linked Data as an access approach and how it ties in to existing data management practice, avoid terms like "legacy" olyerickson: Life examples of tools of how to get specific issues done, might be useful. <olyerickson> link to DDI Alliance <bhyland_> Olyerickson: Feels we walk a line between decribing checklists to evaluate vs. associating specific tools to "get the job done." <olyerickson> Link to ANDS recommendations <cygri> olyerickson, are you aware of ? <Zakim> mhausenblas, you wanted to ask if we can agree on a term now, please? should we use original data? source data? <bhyland_> Time check: 3 minutes until tea break <Zakim> cygri, you wanted to suggest talking about standards instead of tools when possible DeirdreLee: Concrete example: EU Inspires (?) data publishing very cumbersome. To sell the approaches to government may be very difficult. <DaveReynolds> Aside: INSPIRE can be met via linked data, e.g. UK has proposed URI guidelines for naming INSIPRE spatial objects. <George> +1 source data (although I don't have any 'legacy' heartburn...) <bhyland_> Agreed: Legacy data to be recast as "raw data" <olyerickson> @cygri No I wasn't, thanks! <DanG> Legacy? How about "metadata-challenged" mhausenblas: Shall we use a different term than legacy. Suggestion: See it in terms of TimBL star schema. <DeirdreLee> legacy/raw data is 'existing' data. Linked Data is simply an extra way to represent 'existing' data <George> +1 to hopping TBL's 'raw data' bandwagon, however 'raw data' is a misnomer in my gov experience mhausenblas: rename legacy to raw data. <DaveReynolds> -1 to "raw data" that caused problems when TBL used it <mhausenblas> PROPOSAL: To use 'raw data' rather then 'legcay data' along TimBL's 5 star scheme <cygri> kind of -1 to "raw data". statisticians hate that <PhilA> Proposal: To use the term 'Raw Data' to refer to existing data <olyerickson> +1 to "source data" over "raw data"... <cygri> "non-RDF data"? <dvilasuero> +1 to source data <PhilA> Proposal: Not carried <cygri> "spreadsheets" <mhausenblas> PROPOSAL: To use 'source data' rather then 'legacy data' along TimBL's 5 star scheme ???: Mainly about spreadheets and relational data. <cygri> +2 to sandro <stasinos> "pre-formal"? <olyerickson> +1 to exposing...what? ;) <bhyland_> OK, chairs have conferred and we agree ... "Source Data" <olyerickson> mhausenblas' proposal seconded... <mhausenblas> PROPOSAL: To use 'non-RDF data' rather then 'legacy data' along TimBL's 5 star scheme mhausenblas: how to call that first publing working draft <simonWall> unlinked data! <cgueret_work> -1 to non RDF <rreck> non-RDF is stilted <PhilA> -1 to non-RDF <rreck> +1 bio <cgueret_work> @simonWall some RDF is also unlinked <boris> no open data? <olyerickson> +1 to bladder relief... <PhilA> +1 to source data <DaveReynolds> +0 on "source data", it means some different but in a less harmful way than "raw data" <cgueret_work> +1 to source data <rreck> +1 source data <cygri> +0.5 to source data. not my favourite but could work well enough. +1 source data <mhausenblas> bhyland_: we resume at 10:30am/3:30pm <olyerickson> are we hanging up? <olyerickson> do we have to dial in again? <olyerickson> ...or is everyone on mute? <bhyland_> ping, is the Galway team read to resume? <mhausenblas> yes <mhausenblas> sorry <sandro> "Interfacing to Existing Data System" <sandro> "Providing an RDF Interface" Galway is coming... <sandro> "RDF Interfaces" <sandro> galway ping <sandro> cygri, mhausenblas ... <sandro> "Providing RDF Interfaces" <bhyland_> -1 to non-RDF. I prefer "Source Data" <mhausenblas> PROPOSAL: To use 'source data' rather then 'legacy data' along TimBL's 5 star scheme <bhyland_> +1 PhilA <cygri> +0.5 <cgueret_work> +1 to "source" too <cygri> +0.5 to source data <DaveReynolds> +0 on "source data", it means some different but in a less harmful way than "raw data" +1 source data (although domain specific/original data would be more clear) <cgueret_work> and what about "genuine data" ? :) <bhyland_> Proposal for replacement name, it has a "use by date" of at least the FPWD <sandro> sandro: the default is we dont revisit decisions. <boris> +0.98 to "source data" <bhyland_> Agreed: "Source Data" <cgueret_work> cool <mhausenblas> RESOLUTION: To use 'source data' rather then 'legacy data' along TimBL's 5 star scheme <sandro> +0 source data okay as long as it's open to revisiting before LC. ( -1 to this term forever) <boris> olyerrickson: we have general URI recommendations, e.g., data patterns. dvilasuero: Agrees. <bhyland_> What do you mean missing? olyerrickson: instance-hub-uri-design makes it possible to re-host uris ... re-host, i.e. move to a different architecture after testing ... requirements to uri creation approach: no need to make URI self-describing, non-domain-specific <bhyland_> yes, Michael, it must be. I see legacy discussion in two parts in fact. olyerrickson: major parts: id, org, category/token <DanG> What about using subject matter categories rather than agency based ones? They won't die if the agency does. olyerrickson: explanations of examples are linked from the wiki, e.g. in best practices document <DaveReynolds> DanG - UK recommendation is def to use subject matter and avoid agencies olyerrickson: room for discussion. <olyerickson> This is NOT a recommendation; it's simply what we are ucing <olyerickson> s/ucing/using/ <bhyland_> @Michael - we're planning to break in 15-20 minutes, when we've completed or at least come to natural break point in URI discussion. We have to walk to get our lunch. <simonWall> I was planning to be gone by now, good night all. Richard: Good handle of what the section should say. Small concern: some guidelines are applicable everywhere,e.g., slashes, stability; other aspects that apply only to specific use cases. UK gov guidelines mostly only apply to specific environments. ... E.g., re-hosting is something quite specific. <olyerickson> @cygri good point; that was "merely" RPI's requirement ;) <bhyland_> cygri: The main focus should be on stuff that is "true everywhere". <bhyland_> What always applies vs. more specific example that could be better described as use cases. Richard: Recommendations should be more generic. Needed: To abstract from the use cases of TWC or UK gov to have a less complicated design. <bhyland_> Example from DERI, re: data.gov.ie project ... <mhausenblas> s/data.gov.ie/ Richard: approach was to complicated, but this was realized only afterwards. <dvilasuero> +1 cygri <Zakim> PhilA, you wanted to caution against using the org component, slide 3 PhilA: Concern: Names of governments departements change very often, should not be included in URI. Similar goes for locations. <bhyland_> How about if we provide 1) background on the imporance of URI strategy; 2) the value of persistence strategy; 3) detail the issues involved to evaluate a URI scheme olyerickson: Good point. But there is always the question whether create URIs from the concepts (from the actual data). If modelled from the data, then even if concepts changed, at that time of modelling the data was valid and as such the URIs are valid still, also. <olyerickson> _dammit or /dammit ?;) <mhausenblas> Michael: I don't see much of a point in criticising RPI's work now - he made it clear it's an example, not the recommendation <olyerickson> +1 to sandro's point sandro: important to have a plan in case a name changes. <bhyland_> NB: We aren't criticizing RPIs URI draft ... it gave us something in black & white to discuss. Therefore it is good & useful IMO. <George> {sector}.data.gov.*/id/{thing-type}/{instance}/natural/instance/hierarchy <cygri> really good point <mhausenblas> +1 to Dave's wise words re scalability of URI spaces via sub-domains <bhyland_> DaveReynolds: Describe constants: 1) the constants (e.g., sectors for the UK). 2) use of sub-domains to allow for autonomy within gov't authorities. 3) explain scalability implications involved depending on URI structure. Explain URI construction and allude to performance issues ... <mhausenblas> +1 <bhyland_> ... Separating the advice of what to do vs. if you don't do it, you'll get bitten in the bum <stasinos> +1 <dvilasuero> +1 <DeirdreLee> Stale URIs (from non-existant depts) will make the data look stale, even if it's brand new.... DaveReynolds: Depends on the use of URIs: stabilized, architecture-dependent. Separation of tools that allow to create uris and the methods of how to deal with issues afterwards. <mhausenblas> Michael: We're implicitly assuming transparent URIs now Yigal: also responsibilities change. We need to think about temporal issues such as at what time did uri represent something. <mhausenblas> Michael: also known as hackable URIs <George> Yigal: temporal aspect in URI? which HHS? responsibilities change even if/when orgs don't <DaveReynolds> For those who may not be aware ... as well as the original UK recommendations there are recommendations about spatial objects (as relates to the EU INSPIRE directive) useful example of patterns of things beyond "id" and "def" <cygri> +1 to point out ways in which things can/will break bhyland: We need to bound URI construction topic. ... On the one hand best practices should be valid as long as possible. On the other hand it should also include more specific issues. ... cannot tell Google, Yahoo which vocabularies to use. :-) thanks PhilA. Can someone scribe? <PhilA> scribe: PhilA <BenediktKaempgen> Thanks. <bhyland> ping <cmusialek> sorry about that! olyerickson: I'd like to propose that the guidance we're getting -> we should transform what we have so far into a check list or decision tree <cmusialek> thanks! <bhyland> sorry from all of us in DC .. we seem to get aperiodically dropped from our guest network and there is no explicit notification ... olyerickson: highlight the issues. What we're saying is what we did, what we thought about and why we did it <bhyland> and worst, we loose the IRC history :-( <bhyland> s/worst/worse of all/ <George> UK guidance also talks about /def (controversy!) and /dataset among other topics bhyland: I would say, not having read the UK guidance in 8 months or so - that's more comprehensive and thought out. We should consider others (and strip out the UK-specific stuff) sandro: I like the decision tree idea a lot <olyerickson> +1 to "decision tree" idea sandro: "Don't do this" or it will cause problems later and "you probably don't want to do this but you may have reasons not to" and so on bhyland: cmusialekhas a mission to do today. I don't think the guidance is ready for him. The RPI draft is a good input - needs to be discussed further <olyerickson> "RPI thing" is not a draft...it's what we did and why ;) <olyerickson> Wait a minute...I think ChrisM is a test subject and should actually cmusialek: I'm less familiar with the intricacies of URI design. But I'm hearing that it's time to act from the US gov and maybe get 80% right <bhyland> s/cmusialekhas/cmusialek/ olyerickson: I'm going to disagree with you, bhyland ... We're not saying to Chris, go ahead and use this. I'm saying "try it, see what breaks and let us know" <bhyland> Olyerickson is saying the draft RPI URI guidance is a proposal ... try it and give us feedback. olyerickson: I'd also say take a look at the UK advice and tell us what the problem is <DeirdreLee> +1 Olyerickson <bhyland> RPI has used the RPI version for a very specific case. olyerickson: We've used ours for a very specific case <DeirdreLee> community drives standards or standards drive community? The former DeirdreLee (if it's to be used) cygri: I wanted to say that in terms of structuring these BP Recommendations, I agree with sandro and mhausenblas to structure these as a list ... Seems a good way to teach/inform <olyerickson> +1 to cautioning about what might go wrong...BUT it needs to be informed advice cygri: Have you thought about future change? Is there 'cruft' in there (scribe doesn't recognise the term cruft but that's life) <boris> +1 to richard <mhausenblas> +10000 to cygri bhyland: I appreciate John's request for data.gov to take the RPI advice and see how it works. That might be the RPI state, but I'm not sure it's the W3C position as it hasn't been sanctioned by the WG <cygri> olyerickson, who suggested giving uninformed advice? ;-) <olyerickson> +1 to keeping things separate <cygri> ack then, <olyerickson> @cygri I didn't mean...hmmm...what did I mean ;) <bhyland> AnneW: How do we iterate through a suggested set of guidelines & recommendations? <olyerickson> PROPOSAL: URI sub-team work on a check-list for URI construction sandro: The WG is supposed to iterate on the doc until everyone agrees with it ... then it goes to the outside world ... etc. <mhausenblas> +1 to olyerickson proposal <boris> +1 to oleyrickson <bhyland> sandro: The normal W3C process is that the group reviews and once they don't have any problems with it, then goes to last candidate review for feedback. <dvilasuero> +1 to oleyrickson bhyland: What RPI has provided is a draft. But let's encourage cmusialek to be part of the discussion as it continues to evolve <olyerickson> +1 to cmusialek et.al. be part of the conversation bhyland: Are we at a natural breaking point? <Yigal> In reference to using Congressional Districts as example: Is everyone aware that these are redrawn every 10 years? GalwayL YES <olyerickson> are we hanging up? <mhausenblas> reconvene at 12:25 and 5:15pm <olyerickson> I can also stay on bridge... <mhausenblas> reconvene at 12:15 and 5:15pm Wiki record of these minutes is up to date at this point <olyerickson> Note for the "Vocabulary Selection" team: check out the recent addition to DataFAQs re: the role of vocabulary selection in Linked data quality <mhausenblas> I have to go now, unfortunately, Richard is taking over Galway. Literally. :) sandro: the Washington room is still empty (the video link is showing us that). I can ping you when we're about to reconvene if you like? <cygri> zkim, code bern: Did a big restructuring of the wiki page yesterday <cygri> BernHyland: Two questions - how do we move from a wiki to a FPWD, and how do we reflect fture changes s/fture/future/ sandro: We can publish directly from the wiki using a transformation script we have ... It's called RevDoc. It's only my WGs that have used it ... so far ... code is not polished ... alternative is to convert to respec which a lot of folk prefer bernHyland: does it require your help to use RevDoc? sandro: yes - incantations and bones are involved ... it could be useful but there are alternatives bernHyland: Respec is the alternative bh: I'm familiar with Respec so I'd rather use that ... I'll need help from people to make sure that they remember to record who changes what and when <bhyland> ping <boris> <Zakim> cygri, you wanted to mention ReSpec 2 bh: There seemed to be a lot of activity last September in terms for formatting that we can look at sandro: One month off is OK. But we can put changes on the front page of the wiki <Zakim> cygri, you wanted to ask what documents the group is going to publish cygri: Do we have something like a complete list of the documents that the WG is going to produce (Rec and non-Rec) <DaveReynolds> +1 a clear list of docs and intended status would be helpful bhyland: The community directory is published, BPs will be a Rec, <BenediktKaempgen> +1 to list of documents that will be produced sandro: The Wg should do what it thinks is best, there are no rules as such bhyland: We should put things that logically go together in a single doc. For e.g. we might have a lot of stuff about URI consutruction that could be separate ... The Cookbook isn't a Rec - it could become part of the directory George_: The milestones section of the charter says that the directory and cookbook are separate sandro: I think we should remain open to splitting docs as we see fit <mhausenblas> Michael: Regarding publishing the BP FPWD, I think boris and I already had a chat, no? Boris, can you share our proposal on the call, please? <mhausenblas> Michael: Essentially, the idea was to manually transfer the content from the Wiki - we're three Editors, so workload-wise this should work cygri: I thought the Recommended vocabs were going to be in separate docs (DCAT and Data Cube) but I don't know about the otehr areas <bhyland> cygri: suggested re: recommended vocabs, have one doc for DCAT, another for DataCube <mhausenblas> Michael: Just to make it clear - I'm against the script-based version from the Wiki as we have a rather messy structure there and I don't wanna play guinea pig. sorry sandro, no offence meant sandro: If we're just going to endorse someone else's vocab we don't need a big doc for that bhyland: How much of the data cube spec is already written? cygri: We have a spec that is pretty much ready. We might want to add things and improve things but in principle there is an existing spec that covers what you woujld expect it to ... we will need to write more if we decide that there are issues that need to be addressed? bhyland: Is there any benefit for having this as a separate doc? <DaveReynolds> +1 that's what I thought cygri: Yes, that makes sense and I already have an action item to create it ... with help from DaveReynolds et al <BenediktKaempgen> +1 QB should be an own spec <mhausenblas> +1 <boris> +1 separate spec for qb boris: wrt the draft of the BP spec - we (Michael, Bern and I will create the doc, people only need to update the wiki) bhyland: Agreed Slides are at bhyland: The idea is the the CD (Community Directory) is a place where people not necessarily familiar with LD can get some guidance ... The initial CD was put together with some loose requirements from the June f2f ... Talks through her slides ... Haven't had a lot of feedback - need and would like more ... So where do we go? semanticweb.org? SWEO? ... Now that we have a working site, we can seek feedback, maybe open it up ... I think the first thing is to make sure that people think it's a good idea <olyerickson> RE UI, actually simple is good --- priority should be *useful* bhyland: Biplav asked what a company like IBM should put in? What's the (relevant) address for IBM? <George_> bhyland: addresses for global/multi-national concern is good topic for vocab rec tomorrow cygri: DERI is listed in there. We did that because we were asked to do it ... But I was thinking about why I should want to return to it to make sure our data is up to date? <George_> cygri: what's the incentive for data freshness on the CD? cygri: If people come here to find info about expertise then obviously we'd want to be properly represented ... We have an interest in being found if people are looking for LD expertise in Ireland <DeirdreLee> we need a vocabulary to describe Linked Data domain :) cygri: I'd be interested to know who else is working on the kind of thing we do <George_> cygri: LD Communities of Interest/Practice query where? bhyland: We used the W3C CSS and then made changes - we'd like to make the side panel batter olyerickson: Don't be too hard on yourself. It looks good and it's hard to do faceted browsing ... There seems to be some interlinking that is not linking up. If you choose a company, then look at the topics, then try and click on those, what you expect to see is a re-listing of relevant companies bhyland: Agree it would be useful to have tool tips around different terms ... such as adding tool tips ... I agree with cygri that if you know people are finding you through the DIR then you'll be more careful about keeping it up to date ]ack sandro sandro: I'm super picky about sites as a user. But I do have to wonder about a bit of usability testing wouldn't be a bad thing. Unless it delivers a good experience on attempt 1 you might lose people ... Are there way that other people could contribute improvements? Fork? ... I'm not sure how Callimachus puts things together. Are there grad students that could do stuff with it? bhyland: They're welcome to download the code and work on it. This is built on v.12 - we're now on v.16 which now includes import/export of apps ... updating the instance doesn't take a lot of work ... There's not a large technical hurdle to overcome. Just a bit of CSS and JS ... what I'd like is a list of features that we can fix ... expecially if they're trivial! s/expecially/especially/ bhyland: We went to a lot of trouble to get it on a w3 domain for reasons of permanence etc. Got to be easy to use sandro: Do you have an issues list? <olyerickson> @sandro VERY good point!! <cygri> +1 to sandro <olyerickson> is there a github wiki? bhyland: I'll ask James how he wants to queue up issues ... Things like needing a login is surprising <olyerickson> What is the code host? github? Google Code? each have built-in issues trackers bhyland: but maybe that's a good thing to prevent the spam <sandro> ACTION: bhyland to set up an issues list for dir.w3.org [recorded in] <trackbot> Created ACTION-33 - Set up an issues list for dir.w3.org [on Bernadette Hyland - due 2012-02-01]. <olyerickson> Problem solved: bhyland: Then we can see what is easy and what needs more work to implement, prioritise etc. <olyerickson> Ah okay sandro: There's a Callimachus issues list, what we need is a dir.w3.org issue list <olyerickson> @sandro thanks for the clarification bhyland: Obviously James and I are best places to decide if it's a Callimachus or dir.w3.org issue cygri: I wanted to give an armchair view of usability but not sure if that' the bets use of our time? <sandro> now you can submit issues. :-) bhyland: I have an bias towards action - I was expecting some philosophical issues to deal with <cygri> on the philosophical side, i just want to know whether it's httpRange-14 compliant I'm going to need to ask other people in the government space and see what they expect and compare it with what there is <t_gheen> Mike_Pendleton: bugs in Firefox display Mike_Pendleton: The left had side has a list of things that may or may not mean anything to people. ... Conversation then found a bug ... continues to give thoughts to bhyland who takes notes... <t_gheen> bhyland: how about visualizations? <bhyland> <t_gheen> ... names queries? <t_gheen> s/names/named <sandro> Hmmm. When I'm looking at an "area of expertise", like ... I don't see who has that expertise. <t_gheen> ... are there other ways to view the information that are more meaninful? <olyerickson> Not sure what you're looking at... <olyerickson> Okay, bhyland was referring to visualizations on <t_gheen> bhyland: any suggestions for linking up with egov interest group? <t_gheen> ... open knowledge foundation PhilA: That's best achieved by a personal conversation cygri: We work with OKFN and can tell them about it. The DIR isn't quite there yet though <t_gheen> ACTION: bhyland convene a meeting on armchair usability for community directory [recorded in] <trackbot> Created ACTION-34 - Convene a meeting on armchair usability for community directory [on Bernadette Hyland - due 2012-02-01]. BartvanLeeuwen: Backing up a bit... if we think about being able to pull some data directly from the Web, perhaps through gr: data? <George_> BartvanLeeuwen: GR for company products services (Deirdre - vocab for LD domain?) <t_gheen> bhyland: how does GR pull/update company info? bhyland: I think it's a really good suggestion. <George_> ... and then pull that from where ever into the CD Lots of red faces around the table looking at the large pile of uneaten dog food bhyland: We could offer guidance on what RDFa to include on your site, then we could accept a URL of a page to parse and then that could be added to the directory <t_gheen> bhyland: if there was basic RDFa on someone's site, how can we automatically update their info in the directory? bhyland: It's tiresome to have to enter that by hand in 2012 sandro: I think we'd want to support the system being able to import data from a given location BartvanLeeuwen: and preferably auto-updating too <George_> sandro: auto slurping high on list of to do's in general <cygri> washington seems to have dropped off skype? <DeirdreLee> Core business vocabulary? <t_gheen> bhyland: what is the state of the art for scraping a page, RDFa? bhyland: What's the state of the art for being able to scrape a site for RDFa, sandro: It doesn't have to be RDFa, it can be any RDF format <DeirdreLee> BartvanLeeuwen: I'm willing to take a look at it bhyland: take our site - say we had a book that we'd published. And we marked up the page with data. How to do we say look at this and this but not that BartvanLeeuwen: If you look at GR you can say what your service offerings are <George_> ACTION: BartvanLeeuwen to investigate GR ingest from CD provided page [recorded in] <trackbot> Sorry, couldn't find user - BartvanLeeuwen <scribe> ACTION: BartvanLeeuwen to investigate how Good Relations etc could assist with automatically filling up the directory [recorded in] <trackbot> Sorry, couldn't find user - BartvanLeeuwen <olyerickson> can we please not make this more complicated than necessary <scribe> ACTION: Leeuwen to investigate how Good Relations etc could assist with automatically filling up the directory [recorded in] <trackbot> Sorry, couldn't find user - Leeuwen <scribe> ACTION: van Leeuwen to investigate how Good Relations etc could assist with automatically filling up the directory [recorded in] <trackbot> Created ACTION-35 - Leeuwen to investigate how Good Relations etc could assist with automatically filling up the directory [on Bart van Leeuwen - due 2012-02-01]. <Zakim> cygri, you wanted to say this is not on the critical path for the community directory cygri: I'm all for eating our own dog food. At the same time, to make the CD a success, the question of whetehr it can slup in RDFa is not necessarily the most important <George_> but it does speak to the freshness and updating issue :) cygri: I don't want to discourage people looking at it, but it's not priority number 1 ... So this is a vendor directory for LD organisations etc, yes? ... Are there similar examples of sites that do the same for other areas? <bhyland> It is broader than a vendor directory. <bhyland> Cygri: is there an analogous site to this one? cygri: Can we find an example of something that achieves what we want to do in a differnt domain? bhyland: The library community likes directories ... It's not just about vendors <George_> agree with Mike_Pendleton wrt being aligned with Procurement bhyland: It's about finding expertise, whether commercial, academic or whatever <t_gheen> bhyland: there are many examples of these kinds of directories - ex. travel sites <boris> biomedical directories olyerickson: I'll reinforce what others have said about KISS ... It's hard to get people to add their data, even harder to get them to recode their websites ... if we want to be able to slurp in pre-cooked RDF then great, but maybe that should be a separate file ... an option for GR is having a separate location of the RDF info ... If I add my company info into the CD then it would be nice if the CD made an RDF file available that I could then add to my site bhyland: Love that suggestion ... It's a Foafomatic tool - great <George_> me thinks that's what BartvanLeeuwen meant in the first place, + the idea that callimachus could/should also serve as a RDFa template for those that can/will publish that bhyland: You get something back for your effort <BartvanLeeuwen> George_, ack <olyerickson> ;) DeirdreLee: It seems the CD seems to be taking a centralised approach. We want people to put theire data out there and then third party tools can use it ... And the CD is a third party tool in this context <George_> otherwise we'll pull it from dbpedia :) bhyland: Yep, think distributed, think linked data ... summarises what she's taken down so far (and Sandro reminds her he's on the q) <boris> bhyland: It uses a linking gov data chapter I wrote from last November ... we got permission to keep the copyright ... some of it prob belongs in the best practices ... useful if you've had a chance to review it of course boris: The content looks the same as the BP working draft - is it not the same? cygri: Refers to the charter... <cygri>. <BenediktKaempgen> +q BenediktKaempgen: We have been talking about the BP as a static document and it shouldn't be too specific as it will go out of date. The cookbook is more of a live document/resource BartvanLeeuwen: I see it as a more specific document and yes, a living one BenediktKaempgen: For example, a list of the current, most important vocabularies - that's a useful start for individuals <George_> BenediktKaempgen: posits list of vocabs as example of 'smaller more specific' <sandro> how about: when to use RDF/XML vs Turtle vs RDFa vs SPARQL ? BenediktKaempgen: so the criteria go in the BP doc, ones that meeti the crierta go in the cookbook DeirdreLee: What's the government element of the cookbook? <George_> DeirdreLee: what's the Gov angle? DeirdreLee: It seems as if it could cover life sciences etc. ... bhyland: There is a lot of overlap and may overlap the Linked Data Platform WG too bh: I write the various entries with gov in mind even though things can be used elsewhere too ... 80%+ can apply to any LD project, yes - but people from gov will gravitate to it on w3.org <GofranShukair> Sorry ..I have to go ..bye everyone see you tomorrow <cygri> <sandro> sandro: I picture the cookbook as an FAQ, stak overflow type thing ... There are 30-40 questions that gov people will ask when asked to consider implementing LD bhyland: Mike_Pendleton gave me a bunch of questions when we began working with the EPA - yes, that makes sense <cygri> +1 to sandro. that made sense to me. s/stak/stack/ bh: Thanks for the feedback - that helps me see what needs to be done <olyerickson> +1 to stack overflow-like functionality (but that's not free anymore) cygri: So how can we collect those questions? <olyerickson> @bhyland I have to sign off now...apologies. Have a great day, everyone! <t_gheen> ACTION: bhyland gather top 30-40 questions for the FAQ [recorded in] <trackbot> Created ACTION-36 - Gather top 30-40 questions for the FAQ [on Bernadette Hyland - due 2012-02-01]. byland: dare I suggest an action item to collect the questions <cygri> mhausenblas, i'm not in charge of the agenda, but it says we stop at 8 <sandro> list of stackoverflow clones. we could install an instance of one of these.... <cygri> sandro, why? answers.semanticweb.com is already there. don't fragment <BartvanLeeuwen> cygri, +1 bhyland: Considers the day, whether we have achieved our targets ... reviews tomorrow's agenda <sandro> cygri, not sure, just brainstorming. are there tags there we can use to help get GLD folks started in the right direction there? bhyland: anyone not here tomorrow? t_gheen has to meet someone very senior in the West Wing <cygri> sandro, not really. it's for asking questions and getting them answered, not really for reading old answers <rreck> yes. i have posted the slides bhyland: We'll talk about stability tomorrow PhilA: Anne W might want to look at the outcome from the workshop on stability held last month <George_> cygri: more DCAT tomorrow cygri: Would like to talk about DCAT <George_> +1 cygri +1 on DCAT as the hope is to resolve to go to FPWD <boris> <George_> +1 more ADMS tomorrow morning too Current static version of DCAT is at <George_> agreed <George_> with a mandate! <DeirdreLee> Interoperability Solutions for European Public Administrations <DeirdreLee> Join up Thanks all round Meeting adjourned <bhyland> ping <bhyland> is someone in Galway publishing the minutes for today?? This is scribe.perl Revision: 1.136 of Date: 2011/05/12 12:01:43 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/hieratchy/hierarchy/ Succeeded: s/by/but/ Succeeded: s/Gishlain/Ghislain/ Succeeded: s/see/seek/ Succeeded: s/bhland/bhyland/ Succeeded: s/Melvin C/Toby Inkster/ Succeeded: s/about/about how/ FAILED: s/what olyerickson/what olyerickson said/ FAILED: s/ucing/using/ WARNING: Bad s/// command: s/data.gov.ie/ FAILED: s/worst/worse of all/ FAILED: s/cmusialekhas/cmusialek/ FAILED: s/fture/future/ FAILED: s/expecially/especially/ FAILED: s/names/named/ FAILED: s/stak/stack/ Found ScribeNick: mhausenblas Found ScribeNick: BenediktKaempgen Found Scribe: BenediktKaempgen Inferring ScribeNick: BenediktKaempgen Found Scribe: PhilA Inferring ScribeNick: PhilA Scribes: BenediktKaempgen, PhilA ScribeNicks: mhausenblas, BenediktKaempgen, PhilA WARNING: No "Present: ... " found! Possibly Present: AnneW Aside BartvanLeeuwen BenediktKaempgen BernHyland ChristopheGueret Cygri DanG DaveReynolds Deirdre DeirdreLee DruidSmith GUEST George George_ GeraldSteeman Gofran GofranS GofranShukair IPcaller MacTed Michael MichaelH Mike_Pendleton NB Olyerickson P0 P1 P10 P11 P4 P9 PROPOSAL PhilA Richard SpyrosKotoulas Washington Yigal aabb aacc aadd aaee aaff bern bh bhyland bhyland_ boris boris_ byland cgueret_work cmusialek csarven danbri davidwood_ dvilasuero fadi galway gld https joined member mhausenblas olyerrickson rreck sandro scribenick simonWall spyros stasinos t_gheen t_gheen_ tighten trackbot You can indicate people for the Present list like this: <dbooth> Present: dbooth jonathan mary <dbooth> Present+ amy Regrets: Hadley Beeman Agenda: WARNING: No meeting chair found! You should specify the meeting chair like this: <dbooth> Chair: dbooth Found Date: 25 Jan 2012 Guessing minutes URL: People with action items: bartvanleeuwen bhyland boris cygri leeuwen mhausenblas phila van[End of scribe.perl diagnostic output]
http://www.w3.org/2012/01/25-gld-minutes.html
CC-MAIN-2015-18
refinedweb
10,932
61.36
Monetary Policy and Asset Prices) - Citations (0) - Cited In (0) - Page 1 Review of Economic Dynamics 10 (2007) 761–779 Monetary policy and asset prices Athanasios Geromichalos, Juan Manuel Licari, José Suárez-Lledó∗ Department of Economics, University of Pennsylvania, Philadelphia, USA Received 1 December 2006; revised 19 March 2007 Available online 4 May 2007. JEL classification: E31; E50; E52; E58 Keywords: Liquidity; Monetary policy; Inflation; Asset pricing; Asset returns 1. Introduction We know that monetary policy controls the money supply, which determines the rate of infla- tion, and hence the rate of return on (or the cost of holding) currency.1However, we also know that agents often manage portfolios with assets other than money in their daily transactions. Even *Corresponding author at: University of Pennsylvania, Department of Economics, 160 McNeil Building, Philadelphia, USA. jlledo@econ.upenn.edu (J. Suárez-Lledó). 1In simple models, in steady state the growth rate of the money supply pins down the inflation rate, and through the arbitrage condition known as the Fisher equation, this pins down the nominal interest rate; it does not matter if policy controls money, inflation or the interest rate, since any one determines the other two. 1094-2025/$ – see front matter © 2007 Elsevier Inc. All rights reserved. doi:10.1016/j.red.2007.03.002 Page 2 762 A. Geromichalos et al. / Review of Economic Dynamics 10 (2007) 761–779 though ques- tions- period Page 3 A. Geromichalos et al. / Review of Economic Dynamics 10 (2007) 761–779 763 a mon- etary policy on the price of and the rate of return on these assets. Assets are valued for what they yield, which includes direct rate of returns, as is standard in finance, and potentially some liq- uidity services, as is standard in monetary theory.2This. 2. The model Time is discrete and each period consists of two subperiods. During the first subperiod trade occurs in a decentralized market, whereas in the second subperiod economic activity takes place in a centralized (Walrasian) market. There exists a [0,1] continuum of agents who live forever and discount future at rate β ∈ (0,1). Agents consume and supply labor in both subperiods. Preferences are given by U(x,h,X,H) where x and h (X and H) are consumption and labor in the decentralized (centralized) market, respectively. Following Lagos and Wright (2005), we use the specific functional form U(x,h,X,H) = u(x)−c(h)+U(X)−AH. We assume that u and U are twice continuously differentiable with u(0) = 0, u?> 0, u?(0) = ∞, U?> 0, u??< 0, and U??? 0. To simplify the presentation we assume c(h) = h, but this is not important for our substantive results. Let q∗denote the efficient quantity, i.e. u?(q∗) = 1, and suppose there exists X∗∈ (0,∞) such that U?(X∗) = 1 with U(X∗) > X∗. During the first subperiod, economic activity is similar to the standard search model. Agents interact in a decentralized market and anonymous bilateral trade takes place. The probability of meeting someone is α. The first subperiod good, x, comes in many specialized varieties. Agents can transform labor into a special good on a one-to-one basis, and they do not consume the variety that they produce. When two agents, say i and j, meet in the decentralized market, there are three possibilities. The probability that i consumes what j produces but not vice versa (single coincidence meeting) is σ ∈ (0,1 i produces but not vice versa is also σ. Finally, the probability that neither of the agents likes 2). By symmetry, the probability that j consumes what 2Applications of earlier monetary theory to finance include Bansal and Coleman (1996) and Kiyotaki and Moore (2005). In the former, the authors examine the joint distribution of asset returns, velocity, inflation, and money growth. In the latter, the analysis focusses on the interaction between liquidity, asset prices, and aggregate economic activity. 3Recent work by Lester et al. (2007) extends our framework by modeling different acceptabilities for the underlying assets. Since their model builds on ours, the main results in our paper are also verified in Lester et al. However, their main contribution is to go a step further and obtain acceptability endogenously. Therefore, in equilibrium, assets have different liquidity properties. Page 4 764 A. Geromichalos et al. / Review of Economic Dynamics 10 (2007) 761–779 what the other agent produces is 1 − 2σ. In a single coincidence meeting, if i consumes what j produces, we will call i the buyer and j the seller. During the second subperiod agents trade in a centralized market. With centralized trade it is irrelevant whether the good comes in one or many varieties. We assume that at the second sub- period all agents consume and produce the same general good. Agents in the centralized market can transform one unit of labor into w units of the general good, where w is a technological constant. We normalize that constant to w = 1 without loss of generality. It is also assumed that both the general and the special goods are non-storable. There is another object, called (fiat) money, that is perfectly divisible and can be stored at any quantity m ? 0. We let φ denote its value in the centralized market. The key new feature of our model is the introduction of a real asset. One can think of this asset as a Lucas tree. We assume that this tree lives forever, and that agents can buy its shares in the centralized market at price ψ. Let T > 0 denote the total stock of the real asset. We assume that T is exogenously given and constant. As opposed to fiat money, the asset yields a real return in terms of the general consumption good. We let the gross return (dividend) of the asset be denoted by R > 0. An agent that owns shares of the tree can consume the fruit (which here is just the general good) and sell the shares in the Walrasian market. She can also carry shares of the tree into the decentralized market in order to trade. Hence, in this economy money and the asset can potentially compete as a media of exchange. 3. Equilibrium in a model without money We first consider an economy without money. Analyzing this simpler version of the model, provides intuition for the next section, where money and the asset can coexist as media of exchange. We begin with the description of the value functions, treating the prices and the distri- bution of asset holdings as given. These objects will be endogenously determined in equilibrium. Agents are allowed to keep any positive quantity of assets at home before they visit the decen- tralized market.4The state variables for a representative agent are the units of the asset that she brings into the decentralized market, b, and the units of the asset that she keeps at home, a. To reduce notation we define ω ≡ (a,b). First, consider the value function in the centralized market for an agent with portfolio ω. We normalize the price of the general good to 1. The Bellman’s equation is given by ?U(X)−H +βV(ω+1)? s.t. X +ψ(b+1+a+1) = H +(R +ψ)(b +a), where b+1, a+1are the units of the asset carried into the next period’s decentralized market and left at home, respectively.5It can be easily verified that, at the optimum, X = X∗. Using this fact and replacing H from the budget constraint into W yields ?U(X∗)−X∗−ψ(b+1+a+1)+(R +ψ)(b +a)+βV(ω+1)?. W(ω) = max X,H,ω+1 W(ω) = max ω+1 (1) 4As opposed to money, the asset here serves as a store of value. Moreover, the terms of trade for an agent may depend on the amount of the asset that she carries into the decentralized market. Therefore, it may be prudent to keep some assets at home. As we shall see in what follows, this is precisely what happens in equilibrium, whenever the supply of assets is sufficiently large to satisfy the demand for liquidity in the economy. 5We impose non-negativity on all the control variables except H, which is allowed to be negative. Once equilibrium has been found, one can introduce conditions that guarantee H ? 0 (see Lagos and Wright, 2005). Page 5 A. Geromichalos et al. / Review of Economic Dynamics 10 (2007) 761–779 765 This expression implies the following results. First, the choice of ω+1does not depend on ω. In other words, there are no wealth effects. This result relies on the quasi-linearity of U. Second, W is linear, W(ω) = Λ+(R +ψ)(b +a). We now turn to the terms of trade in the decentralized market. Consider a single-coincidence meeting between a buyer and a seller with state variables ω and ˜ ω, respectively. We use the generalized Nash solution, where the bargaining power of the buyer is denoted by θ ∈ (0,1]. Let q represent the quantity of the special good and dbthe units of the asset that change hands during trade. The bargaining problem is ?u(q)+W(a,b −db)−W(ω)?θ?−q +W(˜ a,˜b +db)−W(˜ ω)?1−θ subject to db? b. Using the linearity property of W, the problem simplifies to ?u(q)−(R +ψ)db subject to db? b. Clearly, the linearity of W implies that the solution to the bargaining problem does not depend on the variables a, ˜ a,˜b. It depends on b only if the constraint binds. The solution to this problem is a variation of the standard bargaining result obtained in this type of models. max q,db max q,db ?θ?−q +(R +ψ)db ?1−θ Lemma 1. The bargaining solution is the following: ?q(b) = ˆ q(b), If b ? b∗, then db(b) = b∗, where b∗solves (R + ψ)b = z(q∗) = θq∗+ (1 − θ)u(q∗), ˆ q(b) solves (R + ψ)b = z(q), and z(q) is defined by z(q) ≡θu?(q)q +(1−θ)u(q) θu?(q)+(1−θ) Proof. It is straightforward to verify that the suggested solution satisfies the necessary first-order conditions, which are also sufficient in this problem . If b < b∗, then db(b) = b. ?q(b) = q∗, (2) . (3) 2 Lemma 2. For all b < b∗, we have ˆ q?(b) > 0 and ˆ q(b) < q∗. Proof. See Appendix A. 2 Next, consider the value function of an agent in the decentralized market. Let F(b) be the distribution of asset holdings in this market. We set ξ ≡ ασ. The Bellman’s equation is6 6The first term is the payoff from buying q(b) and going to the centralized market with state variables (a,b −db(b)). The second term is the expected payoff from selling q(˜b) and going to the centralized market with state variables (a,b+ db(˜b)). Both expressions reflect the fact that the only relevant variable for the determination of the terms of trade is the amount of assets that the buyer brings into the decentralized market. The last term is the payoff from going to the centralized market without trading in the decentralized market.
http://www.researchgate.net/publication/24046872_Monetary_Policy_and_Asset_Prices
CC-MAIN-2013-20
refinedweb
1,887
57.37
Break and Continue #include <iostream.h> void main(){ int i; for(i=1; i<= 10; i++){ if(i%2==0){ continue; } cout<<i<<" "; } } The output of the program is 1, 3, 5, 7, 9. Because when i=2, 4, 6, 8, 10 then the continue statement get exexuted and forced the loop to go to next iteration i.e i=3, 5, 7, 9; also it does not execute the "cout" statement. Break: You have seen this statement used in switch statement to stop the progrom control to go to the next case same way the break statement is also used with loop to send the program control out of the loop. Simple words it terminates/ finishes the loop. See the example below- #include <iostream.h> void main(){ int i; for(i=1; ; i++){ cout<<i<<" "; if(i==10){ break; } } } See in the above program looping condition is not given, still it is not infinite loop. See in the loop body when the value of i=10 then the break statement will be executing and terminating the loop. The output is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
https://www.mcqtoday.com/CPP/flowloop/break-and-continue.html
CC-MAIN-2022-27
refinedweb
191
79.19
unable to read memory I use opencv 3.1.0 and have a function at myClass.cpp below; void initialize(Mat frame); and i call the function from main like; myClass temp = myClass::myClass(); temp.initialize(current_frame); constructer works and assigns correct values to temp also current_frame is initialized and its values are correct at main class but when i call the function the program breaks and when i debugged i saw at myClass.cpp the function cannot read the values of frame as i give the parameter to the function. At the inside of initialize(Mat frame) it says "unable to read memory" for all parameters of frame(e.g size, coloumns, rows ...). any help or suggestion? Edit: I added a sample code that i get the same error below; Main.cpp #include "Modifier.hpp" using namespace cv; using namespace std; Mat image; int main(int argc, char* argc){ string imageName("../image.png"); if (argc > 1) { imageName = argv[1]; } image = imread(imageName.c_str(), IMREAD_COLOR); if(image.empty()){ cout << "image is empty" << endl; return -1; } Modify mdf(image); if(mdf.getImage().empty()){ cout << "image is empty" << endl; return -1; } // recently added line mdf.myFunc(); } Modifier.cpp #include "Modifier.hpp" using namespace cv; Modify::Modify(Mat img){ this->image.upload(img); } GpuMat Modify::getImage(){ return this->image; } //recently added line void Modify::myFunc(){ } Modifier.hpp #include <opencv2\core.hpp> #include <opencv2\highgui.hpp> #include <opencv\imgcodecs.hpp> #include <opencv2\imgproc.hpp> #include <opencv2\core\cuda.hpp> using namespace cv; using namespace cv::cuda; class Modify { public: Modify(Mat img); GpuMat getImage(); //recently added line void myFunc(); protected: GpuMat image; since it is unable to read the frame's values cannot assign values to parameters. hope it helps. your code is a bit incomplete, we don't see, what happens inside void initialize(Mat frame); could you update it ? I am not allowed to copy the code but i can say that the error occurs at the beggining of the function; first line is "vidSize = current_frame.size();" and cannot even execute this line. then, how can we help you ? try to make a minimal example, (without copying anything) what is current? sorry, i missed out. currentis one of the global variables of myClass, its type is GpuMat. If you need more info i can provide as much as i am able to Please, either add your code here or either accept that people cannot help out. How can we figure out errors if your not allowed to add a minimal code sample containing the error ... BTW is there a reason why you have a seperate initialize function and you just don't initialize everything in the constructor of the class? It could be reduced to myClass temp = myClass::myClass(current_frame);fairly easy. Also, I suggest you to make clones of the data to ensure that it is not some sketchy pointer accessing problem ... initialize() method is for initializing another features of the object and runs some different algorithms, i've just name it as initialize. Sorry for the mess, i'm editing the code, writing a sample that i get the same error.
https://answers.opencv.org/question/87205/unable-to-read-memory/
CC-MAIN-2019-43
refinedweb
521
59.5
flea 8.0.3 Functional testing for WSGI applications: a library to drive WSGI apps from your test suite Flea is a library that helps you write functional tests for WSGI applications. Flea uses CSS selectors and XPath to give you a simple but powerful tool to navigate and test the HTML responses generated Changes Version 8.0.3 - Added flea.html.first, flea.html.last, flea.html.by_index and flea.html.random_choice to support filling select and radio buttons etc. For example: from flea import first, last, random_choice agent('form').fill(payment_option=first, expiry_year=last, expiry_month=by_index(-2), card_type=random_choice) - Bugfix: select elements with <optgroup> children no longer return the wrong default submission value Version 8.0.2 - Bugfix: keys placed into the WSGI environment are no longer propagated between requests. Version 8.0.1 - Bugfix: accessing the selected property of an <option> element no longer raises an exception. Thanks to Andrew Nelis for the patch. Version 8.0 - Renamed flea.testagent.TestAgent to flea.agent.Agent. This avoids conflicting with the usual naming convention for test modules and classes. - Test suite now uses py.test - Fixed bug where the flea Agent would register a Fresco request object in the WSGI environ, preventing the application under test from later creating a custom request class instance Version 7.5.0 - Changed licensing to the Apache License - Internal refactoring to break into multiple modules (you will need to modify your import statements if you are importing anything other than flea.TestAgent) - Added a TestAgent.environ property Version 7.4.8 - Bugfix: options.selected property getter method had an erroneous argument Version 7.4.7 - Fixed errors when running under python 3.2 Version 7.4.6 - Added a fill_sloppy method that doesn’t raise an exception when fields don’t exist Version 7.4.5 - Bugfix: the order of inputs in a form is now respected in the submitted data - Bugfix: improved handling of unicode values in form.fill() - Bugfix: TestAgent.reload now always replays the original WSGI environ dict - Bugfix: mutations of the WSGI environ made by the application under test are no longer propagated between requests - Bugfix: fixed exception raised when calling TestAgent.new_session() - Added html, pretty, striptags and __contains__ convenience methods to the TestAgent object Version 7.4.4 - Bugfix: cookies are now isolated between requests - Bugfix: no longer raise an exception when called with an absolute url for the first request Version 7.4.3 - Improvements to TestAgent.serve that make it possible to use through a proxy server Version 7.4.2 TestAgent.post now accepts data as a byte string (in addition to a dict or iterable) Added shortcut methods for other common HTTP methods: HEAD, PUT, PATCH and DELETE The environ_defaults dict is now persisted between instances. This is useful for setting default values that will be applied to all subsequent requests, eg: agent = TestAgent(app) agent.environ_defaults['REMOTE_ADDR'] = '' agent.environ_defaults['REMOTE_USER'] = 'alice' Version 7.4.1 - Bugfix: Fixed error in TestAgent.serve() - Improved unicode handling for WSGI environ values Version 7.4.0 - Switch to fresco from pesto - Experimental Python 3 support - Bugfix: ensure WSGI response iterator’s close method is always called Version 7.3.6 - Bugfix for broken TestAgent.serve - Improvements to TestAgent.serve that make it possible to use through a proxy server Version 7.3.5 - Backported changes and fixes from version 7.4.2, with the exception of Python 3 support and support for fresco. See notes above for the changes in this version. Version 7.3.4 - Updated setup.py to require cssselect Version 7.3.3 - Included logging facility to allow easy tracing of calls to the application under test - Added a flea.testing WSGI environ key so that the AUT can tell when it is running in a test environment - Fixed a bug in post_multipart that caused an error when passing a data dict Version 7.3.2 - Fixed bug in fill method, which was not clearing checkbox elements Version 7.3.1 - Fixed bug in TestAgent.follow Version 7.3.0 - New API for form filling, with each control type having a fill method. The value attribute is no longer overloaded. - You can now traverse the DOM by calling the TestAgent object directly with either a CSS selector or XPath expression. - TestAgent.click() now takes an argument that selects links by their textual content, eg agent.click('view results'). If you want the old behaviour, you need to pass a second argument, eg agent.click('//a[.="view results"]', 'xpath'). Version 7.2.1 - The value property now does the right thing with respect to checkbox and radio groups. For checkbox groups, .value will get/set a list of values corresponding to the selected checkboxes. For radio buttons, .value will get/set the selected radio button. Fixed error following links containing a fragment identifier Version 7.2.0 - Added .reload and .new_session methods to TestAgent Version 7.1.1 - Fixed check_status argument not being accepted in get, post, click, submit etc methods Version 7.1.0 Added .fill - fill multiple form fields in a single call. Added .show - show the current response in a web browser - Added .serve - start an HTTP server for the the application under test and open a browser at the current page - Added check for HTTP status success or redirect codes (2xx or 3xx), anything else raises an AssertionError by default Changed default behaviour to follow HTTP redirects Changed version numbering scheme to <major>.<minor> Version 7 Fixed error when accessing the ‘checked’ property of an input box - Prevented raising of ValueError on non-matching xpaths when accessed by .find() (__getitem__ will however still raise an error). Version 6 - Requires pesto 16 or higher Version 5 - Updated setup.py for compatibility with pesto==15 Version 4 - Added support for file upload fields - Allow TestAgent.get/post etc to take a relative URI as an argument Version 3 - Updated setup.py for compatibility with pesto==14 Version 2 - EXSLT regular expression namespace is bound to re prefix by default, allowing regexps in xpath expressions. Bug fixes for form element handling Version 1 - Initial release - Author: Oliver Cope - Documentation: flea package documentation - Keywords: wsgi testing test browser - License: Apache - Categories - Development Status :: 4 - Beta - Environment :: Web Environment - Intended Audience :: Developers - License :: OSI Approved :: BSD License - Operating System :: OS Independent - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3.3 - Programming Language :: Python :: 3.4 - Topic :: Internet :: WWW/HTTP :: WSGI - Topic :: Software Development :: Testing - Package Index Owner: olly - DOAP record: flea-8.0.3.xml
https://pypi.python.org/pypi/flea
CC-MAIN-2017-13
refinedweb
1,096
50.23
When addressing the question of what it means for an algorithm to learn, one can imagine many different models, and there are quite a few. This invariably raises the question of which models are “the same” and which are “different,” along with a precise description of how we’re comparing models. We’ve seen one learning model so far, called Probably Approximately Correct (PAC), which espouses the following answer to the learning question: An algorithm can “solve” a classification task using labeled examples drawn from some distribution if it can achieve accuracy that is arbitrarily close to perfect on the distribution, and it can meet this goal with arbitrarily high probability, where its runtime and the number of examples needed scales efficiently with all the parameters (accuracy, confidence, size of an example). Moreover, the algorithm needs to succeed no matter what distribution generates the examples. You can think of this as a game between the algorithm designer and an adversary. First, the learning problem is fixed and everyone involved knows what the task is. Then the algorithm designer has to pick an algorithm. Then the adversary, knowing the chosen algorithm, chooses a nasty distribution over examples that are fed to the learning algorithm. The algorithm designer “wins” if the algorithm produces a hypothesis with low error on when given samples from . And our goal is to prove that the algorithm designer can pick a single algorithm that is extremely likely to win no matter what the adversary picks. We’ll momentarily restate this with a more precise definition, because in this post we will compare it to a slightly different model, which is called the weak PAC-learning model. It’s essentially the same as PAC, except it only requires the algorithm to have accuracy that is slightly better than random guessing. That is, the algorithm will output a classification function which will correctly classify a random label with probability at least for some small, but fixed, . The quantity (the Greek “eta”) is called the edge as in “the edge over random guessing.” We call an algorithm that produces such a hypothesis a weak learner, and in contrast we’ll call a successful algorithm in the usual PAC model a strong learner. The amazing fact is that strong learning and weak learning are equivalent! Of course a weak learner is not the same thing as a strong learner. What we mean by “equivalent” is that: A problem can be weak-learned if and only if it can be strong-learned. So they are computationally the same. One direction of this equivalence is trivial: if you have a strong learner for a classification task then it’s automatically a weak learner for the same task. The reverse is much harder, and this is the crux: there is an algorithm for transforming a weak learner into a strong learner! Informally, we “boost” the weak learning algorithm by feeding it examples from carefully constructed distributions, and then take a majority vote. This “reduction” from strong to weak learning is where all the magic happens. In this post we’ll get into the depths of this boosting technique. We’ll review the model of PAC-learning, define what it means to be a weak learner, “organically” come up with the AdaBoost algorithm from some intuitive principles, prove that AdaBoost reduces error on the training data, and then run it on data. It turns out that despite the origin of boosting being a purely theoretical question, boosting algorithms have had a wide impact on practical machine learning as well. As usual, all of the code and data used in this post is available on this blog’s Github page. History and multiplicative weights Before we get into the details, here’s a bit of history and context. PAC learning was introduced by Leslie Valiant in 1984, laying the foundation for a flurry of innovation. In 1988 Michael Kearns posed the question of whether one can “boost” a weak learner to a strong learner. Two years later Rob Schapire published his landmark paper “The Strength of Weak Learnability” closing the theoretical question by providing the first “boosting” algorithm. Schapire and Yoav Freund worked together for the next few years to produce a simpler and more versatile algorithm called AdaBoost, and for this they won the Gödel Prize, one of the highest honors in theoretical computer science. AdaBoost is also the standard boosting algorithm used in practice, though there are enough variants to warrant a book on the subject. I’m going to define and prove that AdaBoost works in this post, and implement it and test it on some data. But first I want to give some high level discussion of the technique, and afterward the goal is to make that wispy intuition rigorous. The central technique of AdaBoost has been discovered and rediscovered in computer science, and recently it was recognized abstractly in its own right. It is called the Multiplicative Weights Update Algorithm (MWUA), and it has applications in everything from learning theory to combinatorial optimization and game theory. The idea is to - Maintain a nonnegative weight for the elements of some set, - Draw a random element proportionally to the weights, - So something with the chosen element, and based on the outcome of the “something…” - Update the weights and repeat. The “something” is usually a black box algorithm like “solve this simple optimization problem.” The output of the “something” is interpreted as a reward or penalty, and the weights are updated according to the severity of the penalty (the details of how this is done differ depending on the goal). In this light one can interpret MWUA as minimizing regret with respect to the best alternative element one could have chosen in hindsight. In fact, this was precisely the technique we used to attack the adversarial bandit learning problem (the Exp3 algorithm is a multiplicative weight scheme). See this lengthy technical survey of Arora and Kale for a research-level discussion of the algorithm and its applications. Now let’s remind ourselves of the formal definition of PAC. If you’ve read the previous post on the PAC model, this next section will be redundant. Distributions, hypotheses, and targets In PAC-learning you are trying to give labels to data from some set . There is a distribution producing data from , and it’s used for everything: to provide data the algorithm uses to learn, to measure your accuracy, and every other time you might get samples from . You as the algorithm designer don’t know what is, and a successful learning algorithm has to work no matter what is. There’s some unknown function called the target concept, which assigns a label to each data point in . The target is the function we’re trying to “learn.” When the algorithm draws an example from , it’s allowed to query the label and use all of the labels it’s seen to come up with some hypothesis that is used for new examples that the algorithm may not have seen before. The problem is “solved” if has low error on all of . To give a concrete example let’s do spam emails. Say that is the set of all emails, and is the distribution over emails that get sent to my personal inbox. A PAC-learning algorithm would take all my emails, along with my classification of which are spam and which are not spam (plus and minus 1). The algorithm would produce a hypothesis that can be used to label new emails, and if the algorithm is truly a PAC-learner, then our guarantee is that with high probability (over the randomness in which emails I receive) the algorithm will produce an that has low error on the entire distribution of emails that get sent to me (relative to my personal spam labeling function). Of course there are practical issues with this model. I don’t have a consistent function for calling things spam, the distribution of emails I get and my labeling function can change over time, and emails don’t come according to a distribution with independent random draws. But that’s the theoretical model, and we can hope that algorithms we devise for this model happen to work well in practice. Here’s the formal definition of the error of a hypothesis produced by the learning algorithm: It’s read “The error of with respect to the concept we’re trying to learn and the distribution is the probability over drawn from that the hypothesis produces the wrong label.” We can now define PAC-learning formally, introducing the parameters for “probably” and for “approximately.” Let me say it informally first: An algorithm PAC-learns if, for any and any distribution , with probability at least the hypothesis produced by the algorithm has error at most . To flush out the other things hiding, here’s the full definition. Definition (PAC): An algorithm is said to PAC-learn the concept class over the set if, for any distribution over and for any and for any target concept , the probability that produces a hypothesis of error at most is at least . In symbols, . Moreover, must run in time polynomial in and , where is the size of an element . The reason we need a class of concepts (instead of just one target concept) is that otherwise we could just have a constant algorithm that outputs the correct labeling function. Indeed, when we get a problem we ask whether there exists an algorithm that can solve it. I.e., a problem is “PAC-learnable” if there is some algorithm that learns it as described above. With just one target concept there can exist an algorithm to solve the problem by hard-coding a description of the concept in the source code. So we need to have some “class of possible answers” that the algorithm is searching through so that the algorithm actually has a job to do. We call an algorithm that gets this guarantee a strong learner. A weak learner has the same definition, except that we replace by the weak error bound: for some fixed . the error . So we don’t require the algorithm to achieve any desired accuracy, it just has to get some accuracy slightly better than random guessing, which we don’t get to choose. As we will see, the value of influences the convergence of the boosting algorithm. One important thing to note is that is a constant independent of , the size of an example, and , the number of examples. In particular, we need to avoid the “degenerate” possibility that so that as our learning problem scales the quality of the weak learner degrades toward 1/2. We want it to be bounded away from 1/2. So just to clarify all the parameters floating around, will always be the “probably” part of PAC, is the error bound (the “approximately” part) for strong learners, and is the error bound for weak learners. What could a weak learner be? Now before we prove that you can “boost” a weak learner to a strong learner, we should have some idea of what a weak learner is. Informally, it’s just a ‘rule of thumb’ that you can somehow guarantee does a little bit better than random guessing. In practice, however, people sort of just make things up and they work. It’s kind of funny, but until recently nobody has really studied what makes a “good weak learner.” They just use an example like the one we’re about to show, and as long as they get a good error rate they don’t care if it has any mathematical guarantees. Likewise, they don’t expect the final “boosted” algorithm to do arbitrarily well, they just want low error rates. The weak learner we’ll use in this post produces “decision stumps.” If you know what a decision tree is, then a decision stump is trivial: it’s a decision tree where the whole tree is just one node. If you don’t know what a decision tree is, a decision stump is a classification rule of the form: Pick some feature and some value of that feature , and output label if the input example has value for feature , and output label otherwise. Concretely, a decision stump might mark an email spam if it contains the word “viagra.” Or it might deny a loan applicant a loan if their credit score is less than some number. Our weak learner produces a decision stump by simply looking through all the features and all the values of the features until it finds a decision stump that has the best error rate. It’s brute force, baby! Actually we’ll do something a little bit different. We’ll make our data numeric and look for a threshold of the feature value to split positive labels from negative labels. Here’s the Python code we’ll use in this post for boosting. This code was part of a collaboration with my two colleagues Adam Lelkes and Ben Fish. As usual, all of the code used in this post is available on Github. First we make a class for a decision stump. The attributes represent a feature, a threshold value for that feature, and a choice of labels for the two cases. The classify function shows how simple the hypothesis is. class Stump: def __init__(self): self.gtLabel = None self.ltLabel = None self.splitThreshold = None self.splitFeature = None def classify(self, point): if point[self.splitFeature] >= self.splitThreshold: return self.gtLabel else: return self.ltLabel def __call__(self, point): return self.classify(point) Then for a fixed feature index we’ll define a function that computes the best threshold value for that index. def minLabelErrorOfHypothesisAndNegation(data, h): posData, negData = ([(x, y) for (x, y) in data if h(x) == 1], [(x, y) for (x, y) in data if h(x) == -1]) posError = sum(y == -1 for (x, y) in posData) + sum(y == 1 for (x, y) in negData) negError = sum(y == 1 for (x, y) in posData) + sum(y == -1 for (x, y) in negData) return min(posError, negError) / len(data) def bestThreshold(data, index, errorFunction): '''Compute best threshold for a given feature. Returns (threshold, error)''' thresholds = [point[index] for (point, label) in data] def makeThreshold(t): return lambda x: 1 if x[index] >= t else -1 errors = [(threshold, errorFunction(data, makeThreshold(threshold))) for threshold in thresholds] return min(errors, key=lambda p: p[1]) Here we allow the user to provide a generic error function that the weak learner tries to minimize, but in our case it will just be minLabelErrorOfHypothesisAndNegation. In words, our threshold function will label an example as if feature has value greater than the threshold and otherwise. But we might want to do the opposite, labeling above the threshold and below. The bestThreshold function doesn’t care, it just wants to know which threshold value is the best. Then we compute what the right hypothesis is in the next function. def buildDecisionStump(drawExample, errorFunction=defaultError): # find the index of the best feature to split on, and the best threshold for # that index. A labeled example is a pair (example, label) and drawExample() # accepts no arguments and returns a labeled example. data = [drawExample() for _ in range(500)] bestThresholds = [(i,) + bestThreshold(data, i, errorFunction) for i in range(len(data[0][0]))] feature, thresh, _ = min(bestThresholds, key = lambda p: p[2]) stump = Stump() stump.splitFeature = feature stump.splitThreshold = thresh stump.gtLabel = majorityVote([x for x in data if x[0][feature] >= thresh]) stump.ltLabel = majorityVote([x for x in data if x[0][feature] < thresh]) return stump It’s a little bit inefficient but no matter. To illustrate the PAC framework we emphasize that the weak learner needs nothing except the ability to draw from a distribution. It does so, and then it computes the best threshold and creates a new stump reflecting that. The majorityVote function just picks the most common label of examples in the list. Note that drawing 500 samples is arbitrary, and in general we might increase it to increase the success probability of finding a good hypothesis. In fact, when proving PAC-learning theorems the number of samples drawn often depends on the accuracy and confidence parameters . We omit them here for simplicity. Strong learners from weak learners So suppose we have a weak learner for a concept class , and for any concept from it can produce with probability at least a hypothesis with error bound . How can we modify this algorithm to get a strong learner? Here is an idea: we can maintain a large number of separate instances of the weak learner , run them on our dataset, and then combine their hypotheses with a majority vote. In code this might look like the following python snippet. For now examples are binary vectors and the labels are , so the sign of a real number will be its label. def boost(learner, data, rounds=100): m = len(data) learners = [learner(random.choice(data, m/rounds)) for _ in range(rounds)] def hypothesis(example): return sign(sum(1/rounds * h(example) for h in learners)) return hypothesis This is a bit too simplistic: what if the majority of the weak learners are wrong? In fact, with an overly naive mindset one might imagine a scenario in which the different instances of have high disagreement, so is the prediction going to depend on which random subset the learner happens to get? We can do better: instead of taking a majority vote we can take a weighted majority vote. That is, give the weak learner a random subset of your data, and then test its hypothesis on the data to get a good estimate of its error. Then you can use this error to say whether the hypothesis is any good, and give good hypotheses high weight and bad hypotheses low weight (proportionally to the error). Then the “boosted” hypothesis would take a weighted majority vote of all your hypotheses on an example. This might look like the following. # data is a list of (example, label) pairs def error(hypothesis, data): return sum(1 for x,y in data if hypothesis(x) != y) / len(data) def boost(learner, data, rounds=100): m = len(data) weights = [0] * rounds learners = [None] * rounds for t in range(rounds): learners[t] = learner(random.choice(data, m/rounds)) weights[t] = 1 - error(learners[t], data) def hypothesis(example): return sign(sum(weight * h(example) for (h, weight) in zip(learners, weights))) return hypothesis This might be better, but we can do something even cleverer. Rather than use the estimated error just to say something about the hypothesis, we can identify the mislabeled examples in a round and somehow encourage to do better at classifying those examples in later rounds. This turns out to be the key insight, and it’s why the algorithm is called AdaBoost (Ada stands for “adaptive”). We’re adaptively modifying the distribution over the training data we feed to based on which data learns “easily” and which it does not. So as the boosting algorithm runs, the distribution given to has more and more probability weight on the examples that misclassified. And, this is the key, has the guarantee that it will weak learn no matter what the distribution over the data is. Of course, it’s error is also measured relative to the adaptively chosen distribution, and the crux of the argument will be relating this error to the error on the original distribution we’re trying to strong learn. To implement this idea in mathematics, we will start with a fixed sample drawn from and assign a weight to each . Call the true label of an example. Initially, set to be 1. Since our dataset can have repetitions, normalizing the to a probability distribution gives an estimate of . Now we’ll pick some “update” parameter (this is intentionally vague). Then we’ll repeat the following procedure for some number of rounds . - Renormalize the to a probability distribution. - Train the weak learner , and provide it with a simulated distribution that draws examples according to their weights . The weak learner outputs a hypothesis . - For every example mislabeled by , update by replacing it with . - For every correctly labeled example replace with . At the end our final hypothesis will be a weighted majority vote of all the , where the weights depend on the amount of error in each round. Note that when the weak learner misclassifies an example we increase the weight of that example, which means we’re increasing the likelihood it will be drawn in future rounds. In particular, in order to maintain good accuracy the weak learner will eventually have to produce a hypothesis that fixes its mistakes in previous rounds. Likewise, when examples are correctly classified, we reduce their weights. So examples that are “easy” to learn are given lower emphasis. And that’s it. That’s the prize-winning idea. It’s elegant, powerful, and easy to understand. The rest is working out the values of all the parameters and proving it does what it’s supposed to. The details and a proof Let’s jump straight into a Python program that performs boosting. First we pick a data representation. Examples are pairs whose type is the tuple (object, int). Our labels will be valued. Since our algorithm is entirely black-box, we don’t need to assume anything about how the examples are represented. Our dataset is just a list of labeled examples, and the weights are floats. So our boosting function prototype looks like this # boost: [(object, int)], learner, int -> (object -> int) # boost the given weak learner into a strong learner def boost(examples, weakLearner, rounds): ... And a weak learner, as we saw for decision stumps, has the following function prototype. # weakLearner: (() -> (list, label)) -> (list -> label) # accept as input a function that draws labeled examples from a distribution, # and output a hypothesis list -> label def weakLearner(draw): ... return hypothesis Assuming we have a weak learner, we can fill in the rest of the boosting algorithm with some mysterious details. First, a helper function to compute the weighted error of a hypothesis on some exmaples. It also returns the correctness of the hypothesis on each example which we’ll use later. # compute the weighted error of a given hypothesis on a distribution # return all of the hypothesis results and the error def weightedLabelError(h, examples, weights): hypothesisResults = [h(x)*y for (x,y) in examples] # +1 if correct, else -1 return hypothesisResults, sum(w for (z,w) in zip(hypothesisResults, weights) if z < 0) Next we have the main boosting algorithm. Here draw is a function that accepts as input a list of floats that sum to 1 and picks an index proportional to the weight of the entry at that index. def boost(examples, weakLearner, rounds): distr = normalize([1.] * len(examples)) hypotheses = [None] * rounds alpha = [0] * rounds for t in range(rounds): def drawExample(): return examples[draw(distr)] hypotheses[t] = weakLearner(drawExample) hypothesisResults, error = computeError(hypotheses[t], examples, distr) alpha[t] = 0.5 * math.log((1 - error) / (.0001 + error)) distr = normalize([d * math.exp(-alpha[t] * h) for (d,h) in zip(distr, hypothesisResults)]) print("Round %d, error %.3f" % (t, error)) def finalHypothesis(x): return sign(sum(a * h(x) for (a, h) in zip(alpha, hypotheses))) return finalHypothesis The code is almost clear. For each round we run the weak learner on our hand-crafted distribution. We compute the error of the resulting hypothesis on that distribution, and then we update the distribution in this mysterious way depending on some alphas and logs and exponentials. In particular, we use the expression , the product of the true label and predicted label, as computed in weightedLabelError. As the comment says, this will either be or depending on whether the predicted label is correct or incorrect, respectively. The choice of those strange logarithms and exponentials are the result of some optimization: they allow us to minimize training error as quickly as possible (we’ll see this in the proof to follow). The rest of this section will prove that this works when the weak learner is correct. One small caveat: in the proof we will assume the error of the hypothesis is not zero (because a weak learner is not supposed to return a perfect hypothesis!), but in practice we want to avoid dividing by zero so we add the small 0.0001 to avoid that. As a quick self-check: why wouldn’t we just stop in the middle and output that “perfect” hypothesis? (What distribution is it “perfect” over? It might not be the original distribution!) If we wanted to define the algorithm in pseudocode (which helps for the proof) we would write it this way. Given rounds, start with being the uniform distribution over labeled input examples , where has label . Say there are input examples. - For each : - Let be the weak learning algorithm run on . - Let be the error of on . - Let . - Update each entry of by the rule , where is chosen to normalize to a distribution. - Output as the final hypothesis the sign of , i.e. . Now let’s prove this works. That is, we’ll prove the error on the input dataset (the training set) decreases exponentially quickly in the number of rounds. Then we’ll run it on an example and save generalization error for the next post. Over many years this algorithm and tweaked so that the proof is very straightforward. Theorem: If AdaBoost is given a weak learner and stopped on round , and the edge over random choice satisfies , then the training error of the AdaBoost is at most . Proof. Let be the number of examples given to the boosting algorithm. First, we derive a closed-form expression for in terms of the normalization constants . Expanding the recurrence relation gives Because the starting distribution is uniform, and combining the products into a sum of the exponents, this simplifies to Next, we show that the training error is bounded by the product of the normalization terms . This part has always seemed strange to me, that the training error of boosting depends on the factors you need to normalize a distribution. But it’s just a different perspective on the multiplicative weights scheme. If we didn’t explicitly normalize the distribution at each step, we’d get nonnegative weights (which we could convert to a distribution just for the sampling step) and the training error would depend on the product of the weight updates in each step. Anyway let’s prove it. The training error is defined to be . This can be written with an indicator function as follows: Because the sign of determines its prediction, the product is negative when is incorrect. Now we can do a strange thing, we’re going to upper bound the indicator function (which is either zero or one) by . This works because if predicts correctly then the indicator function is zero while the exponential is greater than zero. On the other hand if is incorrect the exponential is greater than one because when . So we get and rearranging the formula for from the first part gives Since the forms a distribution, it sums to 1 and we can factor the out. So the training error is just bounded by the . The last step is to bound the product of the normalization factors. It’s enough to show that . The normalization constant is just defined as the sum of the numerator of the terms in step D. i.e. We can split this up into the correct and incorrect terms (that contribute to or in the exponent) to get But by definition the sum of the incorrect part of is and for the correct part. So we get Finally, since this is an upper bound we want to pick so as to minimize this expression. With a little calculus you can see the we chose in the algorithm pseudocode achieves the minimum, and this simplifies to . Plug in to get and use the calculus fact that to get as desired. This is fine and dandy, it says that if you have a true weak learner then the training error of AdaBoost vanishes exponentially fast in the number of boosting rounds. But what about generalization error? What we really care about is whether the hypothesis produced by boosting has low error on the original distribution as a whole, not just the training sample we started with. One might expect that if you run boosting for more and more rounds, then it will eventually overfit the training data and its generalization accuracy will degrade. However, in practice this is not the case! The longer you boost, even if you get down to zero training error, the better generalization tends to be. For a long time this was sort of a mystery, and we’ll resolve the mystery in the sequel to this post. For now, we’ll close by showing a run of AdaBoost on some real world data. The “adult” census dataset The “adult” dataset is a standard dataset taken from the 1994 US census. It tracks a number of demographic and employment features (including gender, age, employment sector, etc.) and the goal is to predict whether an individual makes over $50k per year. Here are the first few lines from the training set. 37, Private, 284582, Masters, 14, Married-civ-spouse, Exec-managerial, Wife, White, Female, 0, 0, 40, United-States, <=50K We perform some preprocessing of the data, so that the categorical examples turn into binary features. You can see the full details in the github repository for this post; here are the first few post-processed lines (my newlines added). >>> from data import adult >>> train, test = adult.load() >>> train[:3] [((39, 1, 0, 0, 0, 0, 0, 1, 0, 0, 13, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2174, 0, 40, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), -1), ((50, 1, 0, 1, 0, 0, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), -1), ((38, 1, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 40, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), -1)] Now we can run boosting on the training data, and compute its error on the test data. >>> from boosting import boost >>> from data import adult >>> from decisionstump import buildDecisionStump >>> train, test = adult.load() >>> weakLearner = buildDecisionStump >>> rounds = 20 >>> h = boost(train, weakLearner, rounds) Round 0, error 0.199 Round 1, error 0.231 Round 2, error 0.308 Round 3, error 0.380 Round 4, error 0.392 Round 5, error 0.451 Round 6, error 0.436 Round 7, error 0.459 Round 8, error 0.452 Round 9, error 0.432 Round 10, error 0.444 Round 11, error 0.447 Round 12, error 0.450 Round 13, error 0.454 Round 14, error 0.505 Round 15, error 0.476 Round 16, error 0.484 Round 17, error 0.500 Round 18, error 0.493 Round 19, error 0.473 >>> error(h, train) 0.153343 >>> error(h, test) 0.151711 This isn’t too shabby. I’ve tried running boosting for more rounds (a hundred) and the error doesn’t seem to improve by much. This implies that finding the best decision stump is not a weak learner (or at least it fails for this dataset), and we can see that indeed the training errors across rounds roughly tend to 1/2. Though we have not compared our results above to any baseline, AdaBoost seems to work pretty well. This is kind of a meta point about theoretical computer science research. One spends years trying to devise algorithms that work in theory (and finding conditions under which we can get good algorithms in theory), but when it comes to practice we can’t do anything but hope the algorithms will work well. It’s kind of amazing that something like Boosting works in practice. It’s not clear to me that weak learners should exist at all, even for a given real world problem. But the results speak for themselves. Next time Next time we’ll get a bit deeper into the theory of boosting. We’ll derive the notion of a “margin” that quantifies the confidence of boosting in its prediction. Then we’ll describe (and maybe prove) a theorem that says if the “minimum margin” of AdaBoost on the training data is large, then the generalization error of AdaBoost on the entire distribution is small. The notion of a margin is actually quite a deep one, and it shows up in another famous machine learning technique called the Support Vector Machine. In fact, it’s part of some recent research I’ve been working on as well. More on that in the future. If you’re dying to learn more about Boosting, but don’t want to wait for me, check out the book Boosting: Foundations and Algorithms, by Freund and Schapire. Until next time! Good post! I came here knowing nothing about Adaboost but now I think i understand the concept 🙂 . But I think you should make some clarifications: The “epsilon t” in the proof, which you simply refer to as ” the error of ht on Dt” is actually the weighted training error (sum of all D which are misclassified), while the “training error” that you mentioned in the second part of the proof is the “real error” (the number of misclassified examples). Just my two cents 🙂 And by the way, I just realized that they chose the “decision stump” as a weak learner for a reason: you know, given a data “x”, the decision stump evaluates w*x (think of it as a simple linear classifier), then if w*x >= threshold, return 1, else return -1. With this definition, it can be shown that we can always have a decision stump that correctly classifies at least half of the data (therefore satisfying the weak learner criterion) as follows: suppose the results are not more than 50% correct, then we make another decision stump: w*x = threshold, return 1 , else return -1. So the decision stump can always be considered a weak learner. I wonder if this is correct? 😦 You’re right that decision stumps will always get >= 50% of the data right, but unfortunately that’s not sufficient to make them weak learners. By way of counterexample: take as your dataset the set of all binary strings of length , and the goal is to learn the parity (whether there’s an odd or even number of 1’s in the string). With high probability, a sample drawn from this dataset will have positive labels for a fraction no matter which bit you use in the decision stump!, and as n tends to infinity this tends to 1/2. To be a weak learner, you need a *constant* advantage over random guessing, not one that diminishes as n grows. But why O(1/n) ? I thought the probability for odd number of 1’s is equal to the probability for even number number of 1’s (e.g, if you have 001 , which is odd, you flip the bits to get 110 which is even, therefore the fractions must be equal?) 😦 The 1/n is the error term. What I mean is that in a learning problem you draw a random (small) sample of items to learn from, and in the random choices made to create that sample, you might not get exactly half. But you’ll still get very close. Hi, I really like your explanation with mathematic formulation and code and I wonder when the next post about boosting will come. And just one question, since we can connect weak learner with strong learner in a clever way like adaboost, I wonder if there is any algorithm can do the same but achieve other error bound or any other variants. the sequel to this post is at: How can we proof that the draw() function in utils.py can pick the indexes proportionately by their weights? Great post again. I have had the sudden realization that one of the reasons I find your posts easier to understand than the CS (or ML or stats) literature is because you have a math background. Its the same reason I shut down reading physics books by physicists but have no trouble following math ones (like arnold). I used to think its a notational thing but its not. This might sound strange but I think because math people are much let anxious about symbolic usage and let the notations follow the narrative, on other hand quantitative fields try too hard to get ‘mathy’ and overdo it with the symbol pushing (econ is the worst offender here). I’m not sure I understand the minLabelErrorOfHypothesisAndNegation function. It seems to count the number of misclassifications (posError) and the number of correct classifications (negError). Then it returns the minimum of a posError or negError rate. This seems to be used as the default error function in the code. But how is this an error rate when negError < posError? Since that counts correctly classified examples, wouldn't it be 1-error rate? I'm likely missing something obvious here and appreciate any light anyone can shed. Thank you for an excellent post on boosting.
https://jeremykun.com/2015/05/18/boosting-census/?like_comment=54945&_wpnonce=a8be5d15ec
CC-MAIN-2019-51
refinedweb
6,414
60.75
Connect to Java You can connect both components and data between Java and the UI made with Designer. In practice, this is accomplished with a Java class that enables Vaadin Flow to connect your Java code to the UI. In other words, you access the UI defined in a design programmatically through the companion class for the design. TL;DR To connect a component to Java: Make sure you have a companion Java class with @JsModule and @Tag annotations matching the design. Set the id attribute for the element. Click on the connect button for the element in the Outline. The Java Companion File The Java companion file contains the class that connects your Java code to the UI defined in the design. There can be only one companion class for a design. You may have already created the companion file at the time you created the design using the new design wizard. If that is the case you are all set. You can start connecting components and data. When the design has a companion file, the name of the companion file is displayed next to the design’s name in the toolbar. main-viewhas a companion class called MainView. You can navigate to the companion file by clicking on its name in the toolbar. The file will open in your IDE. If you do not have a companion file for your design yet, you can create one manually. Here is a code snippet for a companion file that is a valid starting point for any design. It has been written as if it was a companion to an imaginary my-design.js. You have to adapt it by providing the correct values for your design to the Tag and JsModule annotations. The class names are not relevant for Designer. import com.vaadin.flow.templatemodel.TemplateModel; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.polymertemplate.PolymerTemplate; @Tag("my-design") @JsModule("./src/views/my-design.js") public class MyDesign extends PolymerTemplate<MyDesign.MyDesignModel> { public MyDesign() { // You can initialise any data required for the connected UI components here. } public interface MyDesignModel extends TemplateModel { // Add setters and getters for template properties here. } } In general, any Java class will be picked up by Designer as a companion file for the design, as long as the class meets the following requirements: It is a descendant of com.vaadin.flow.component.Component It is annotated with com.vaadin.flow.component.Tag annotation. The annotation’s value matches the design’s tag in custom element definition (e.g. customElements.define('my-design', MyDesign)) The value of the com.vaadin.flow.component.dependency.JsModule annotation matches the design path. So, if you have a specific need, you can freely customize the companion class to match your demands. You can learn more about connecting designs and Java classes in Flow documentation. Connecting Components Designer helps to connect the components used in the design to Java but before that can happen you need three things: You need a companion file for the design. See the The Java Companion File for how to get one. The component you want to connect to Java should have its id property set to a unique value (among all the id property values in the same design). If its id is empty, Designer will generate one for you. The project must have Vaadin Flow component integrations as dependencies. Those are needed to correctly set the type of the new field. When a companion file for the design exists, you can connect components to Java using the Outline view. When you hover over a component in the Outline and the component has a Java API, a connection button will appear on the same row with the component name. By clicking the connection button, you can connect the component to Java. This is shown in the following picture. When the vaadin-button in the previous picture is connected, the following field is added to the companion class: @Id("vaadinButton") private Button vaadinButton; If the component has alternative Java APIs, you can right-click the connection button and choose an API from the context menu. For example, you might have your own Java class MyButton that extends Vaadin’s Button to provide some extra functionality. MyButton will be available in the context menu. Flow uses the @Id annotation to connect the UI component to the field. The value in the annotation must match the id property of the component in the design. Otherwise, you are free to change the type, name and visibility of the field. Just be careful not to break it for Flow. Take a look at the Flow documentation to learn more about binding components in Flow. You can disconnect a component by clicking the connection button of a connected component. Disconnecting a component will erase the corresponding field from the companion class along with its @Id annotation. You should not have more than one companion class for a design, or more than one field annotated with the same @Id value, but if you do, all of them will be shown in the Java checkbox tooltip so that you can easily locate them to fix the problem manually. Connecting Data You can also bind data from Java to the UI. Designer provides you with a starting point by adding the template model inner class into the companion file when the file is created. You can learn more about binding data to designs in Flow documentation.
https://vaadin.com/docs/latest/tools/designer/using-designer/java
CC-MAIN-2021-49
refinedweb
920
56.35
Colin Maunder CMaunder Subtext 2009-01-12T12:14:57Z Controlling the WSDL created from a .Net Web Service 2009-01-12T12:03:33-06:00:00 2009-01-12T12:14:57Z <ul class="Download"><li><a href="">Download DataBindingAndWebService - 26.41 KB</a> </li></ul> <h2>Introduction</h2> <p>Its good practice to design the interface to a web service by applying the same standards that would normally be applied to an XML Schema. It should be versioned, extensible and be well structured allowing for good reuse. </p> <h2>Background</h2> <p>Within a Web Service all the messages are described using an XML Schema (XSD), so it makes sense to design our interface in terms of an XML Schema, and then embed this into our web service. <a href="">Liquid XML Studio</a> is an ideal editor for this, as it’s free and easy to use.</p> <p>The following example shows the messages we would like our simple web service to exchange. Our simple Web Service will provide information about a given product, when provided with a product code, we will also need to provide login details to the service. </p> <p><a href=""><img height="93" border="0" width="550" src="" /></a></p> <p>The information returned describes the product, pricing, and stock levels.</p> <p><a href=""><img height="115" border="0" width="550" src="" /></a></p> <p>So we would like to build a web service with a web method that takes a ProductDetailsRequestType and returns a ProductDetailsResponseType. </p> <p>So that’s what we’re after, now lets look at how to achieve this.</p> <h2>Using the standard .Net Framework Serialisation.</h2> <p>We could create a class for each entity in the schema, give them the appropriate properties and let the standard .Net framework [WebMethod] serialisation do the rest. This is an acceptable approach for small projects, but if you want to pass complex objects or objects from 3<sup>rd</sup> party standards (HL7, FpML, ebXML, etc) this starts to become overwhelming. </p> <p>Another approach I've seen used a lot is just to pass the XML data via a string parameter. This has a number of drawbacks, the XML will all be escaped so it expands (< becomes &lt;.</p> <p. </p> <p>It is however possible to apply the techniques to allow an XmlElement to be passed via a web service and have it fully described in the WSDL. But more about this later. </p> <h2>The XML Data Binding Approach</h2> <p>A really easy way to deal with XML within your application is <a href="">XML Data Binding</a>..</p> <p>These objects can be generated using a Data Binding tool, Liquid XML Studio has an XML Data Binding tool which will create .Net code for 1.1, 2.0, 3.5 & Silverlight both in C# and VB.Net. </p> <p>Once we have generated our Data Bound class library, we can pull together our web service. The first thing to do is declare our web method. </p> <pre>namespace ProductEnquiryWebService { [WebService(</p> <p>So in order to call it you need to either build yourself a test harness or use a test tool. Liquid XML Studio contains a handy tool for calling web services. This will automatically generate the request envelope and message, allowing you to modify can call it.</p> <p><img height="454" width="550" alt="CallWebService_640x529.png" src="" /></p> <h3>Sample Request</h3> <pre><?xml version="1.0" encoding="utf-8"?> <SOAP-ENV:Envelope xmlns: <SOAP-ENV:Body> <tnsa:RequestProductDetails> </pre> <h3>Sample Response </h3> <pre><?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns: <soap:Body> <RequestProductDetailsResponse xmlns=""> <RequestProductDetailsResult> <!--Created by Liquid XML Data Binding Libraries (<a href="%22"></a>) --> > </pre> <h2>Examining the WSDL</h2> <p>Because we have taken control of the serialisation process the WSDL describing the web service contains the contents of the schemas that you added in via the MySchema method. </p> <p><a href="">Download the WSDL - 4.62 KB</a></p> <p>It is also possible to explore this graphically using the Web service Call Composer in Liquid XML Studio</p> <p><a href=""><img height="205" border="0" width="550" src="" /></a></p> <h2>Conclusion </h2> <p. </p><p. </p> <p>Using this approach makes it possible to include parts of complex standards within your web service and still have them properly described in the WSDL, enabling other tools to properly understand and use the interface. </p><p> </p><h2>Resources </h2><ul><li><a href=""><span><span class="selflink">IXmlSerializable</span></span> interface</a></li><li><a href="">XmlSchemaProvider Attribute</a></li><li>Liquid XML Studio - <a href="">Free XML Schema Editor</a> </li><li>Liquid XML Studio - <a href="">XML Data Binder for C#</a></li><li><a href="">WSDL Standard</a></li><li><a href="">XSD Standard</a></li></ul><h2>History </h2> <p>Created : 12/1/2009 </p><img src="" width="1" height="1" /> 1 Problems Parsing DTD's 2009-01-08T18:44:56-06:00:00 2009-01-08T18:50:27Z <p. </p> <p.</p> <p><br /> Using the following example.</p> <pre>1: <?xml version='1.0'?> 2: <!DOCTYPE test [ 3: <!ELEMENT test (#PCDATA) > 4: <!ENTITY % xx '&#37;zz;'> 5: <!ENTITY % zz '&#60;!ENTITY tricky "error-prone" >' > 6: %xx; 7: ]> 8: <test>This sample shows a &tricky; method.</test></pre> <p> </p> <p>The first pass through, expands the entity %xx; defined in line 4, into its definition in line 6 giving (&#37; expands to %)</p> <p> </p> <pre>1: <?xml version='1.0'?> 2: <!DOCTYPE test [ 3: <!ELEMENT test (#PCDATA) > 4: <!ENTITY % xx '&#37;zz;'> 5: <!ENTITY % zz '&#60;!ENTITY tricky "error-prone" >' > 6: %zz; 7: ]> 8: <test>This sample shows a &tricky; method.</test></pre> <p> </p> <p>The second pass through expands %zz; defined in line 5 into line 6 (&#60; expands to <)</p> <p> </p> <pre>1: <?xml version='1.0'?> 2: <!DOCTYPE test [ 3: <!ELEMENT test (#PCDATA) > 4: <!ENTITY % xx '&#37;zz;'> 5: <!ENTITY % zz '&#60;!ENTITY tricky "error-prone" >' > 6: <!ENTITY tricky "error-prone" > 7: ]> 8: <test>This sample shows a &tricky; method.</test></pre> <p> </p> <p>And finally the &tricky; in the XML is expanded to "error-prone"</p> <p> </p> <pre>1: <?xml version='1.0'?> 2: <!DOCTYPE test [ 3: <!ELEMENT test (#PCDATA) > 4: <!ENTITY % xx '&#37;zz;'> 5: <!ENTITY % zz '&#60;!ENTITY tricky "error-prone" >' > 6: <!ENTITY tricky "error-prone" > 7: ]> 8: <test>This sample shows a error-prone method.</test></pre> <h4> </h4> <h4>Useful tools</h4> <ul> <li><a href="">Liquid XML Studio - Free DTD Editor.</a> </li> <li><a href="">Wutka Java DTD Parser</a> </li> <li><a href="">Matrs Java DTD Parser</a> </li> </ul> <p> </p><img src="" width="1" height="1" /> 0 XML Editor 2009-01-05T18:55:58-06:00:00 2009-01-05T18:55:58Z <p><font face="Arial">We've been doing some work with <a href="">FpML</a> (Financial Products Markup Language) which is an XML standard for describing trades between investment banks, swaps, futures etc. Its a complicated standard in the form of an XSD (<a href="">XML Schema</a>). So producing XML that is valid against the FpML schema is not entirely straight forward. <br /> </font><font face="Arial"></font></p> <p><font face="Arial". <br /> </font></p> <p><font face="Arial".<br /> </font></p> <p><font face="Arial">Eventually one of the team found Liquid <a href="">XML Editor</a>, this is a free text based editor that is schema aware, and even shipped with the FpML standards so when we opened our XML file it automatically loaded the schema, and told us about our errors. <br /> <br /> <a href=""><img height="328" alt="Liquid XML Editor showing errors in XML document" width="550" border="0" src="/images/geekswithblogs_net/CMaunder/EditorErrors.png" /></a></font></p> <p><font face="Arial".<br /> <br /> <a href=""><img height="238" alt="XML Editor intellisense and schema docs" width="560" border="0" src="/images/geekswithblogs_net/CMaunder/Intellisense.png" /></a></font></p> <p><font face="Arial" <a href="">XML schema editor</a>, that allows you to <a href="">create HTML documentation from an XML Schema</a>, we later discovered this documentation was already online see <a href="">FpML online documentation</a>. This gave us a good feel for the shape of our target XML document. We then used Liquid XML studio's XML editor to finish prototyping our XML documents. <br /> </font></p> <p><font face="Arial">Our final problem was the target system could not cope with the XML documents we produced. Initially we figured our XML was wrong, but after running our XML through a number of validation applications, and digging through the <a href="">XSD standard</a>.<br /> </font></p> <p><font face="Arial".<br /> </font></p><img src="" width="1" height="1" /> 0 Web Service Interoperability 2008-12-29T16:57:18-06:00:00 2008-12-29T16:57:18Z <font size="2"> <p><a></a>Our company has a pretty wide mix of systems Windows mostly VB & .Net and Solaris Java & C++. </p> <h3>Standards without standards.</h3> .</p> <p>Although all these teams work within the <a href="">Web Service standards</a>, the resulting interfaces can me more or less proprietary. </p> <h3>.Net & Web Services</h3> <p.</p> <p.</p> <h3>Java & Web Services</h3> <p).</p> <p>On the flip side, the java proxy generation tools are typically better than there .Net counterparts, and while you can end up with some ugly looking objects, they tend to cope with more complex schemas.</p> <h3>Conclusions when designing a web service.</h3> <p>If interoperability is something that would be valuable to your project now or in the future, then think about the interface. Ultimately this is expressed as an XSD embedded within your WSDL. If its structured correctly, from the outset your life will be much simpler. </p> <h3>Tips for examining your web services structure.</h3> <strong>Visualising the Web Service</strong> <p <a href="">XML schema viewer</a> for this.</p> <p><a href=""><img height="163" alt="" width="485" border="0" src="" /></a></p> <p><strong>Visualising the request/response from the Web Service.</strong></p> <p>Ultimately it all comes down to an XML request and response. These are structured according to the XSD within the WSDL. You can easily build sample request, and see the web service output using Liquid XML Studios <a href="">web service call composer</a>. This allows you to <a href="">call a web service without having to write an application</a>. It constructs a sample request that you can change to add in more appropriate values, then shows the results.</p> <p><a href=""><img height="380" alt="" width="600" border="0" src="" /></a></p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> </font><img src="" width="1" height="1" /> 0 Building XPath Queries 2008-12-19T07:13:23-06:00:00 2008-12-30T02:07:45Z <p.<br /> <br />.<br /> <br /> So I went in search of a good XPath tutorial, and I was somewhat disappointed with what I found. There are a few - but they are a bit lacking, the <a href="">W3Schools XPath Article</a> one was the most complete, and an <a href="">XPath article on Google Knol</a> had some nice examples. If anyone comes across a really good XPath tutorial let me know!<br /> <br /> <a href="">Liquid XML Studio</a> XPath viewer also added itself to Visual Studio 2008 which made my life even easier.</p> <p><a href=""><img height="253" width="400" border="0" alt="" src="/images/geekswithblogs_net/CMaunder/ScreenShot_XPath_Flat_400x253.png" /></a><br /> <a href="">Liquid XML Studio XPath Viewer</a> </p><img src="" width="1" height="1" /> 4
http://geekswithblogs.net/CMaunder/Atom.aspx
crawl-003
refinedweb
1,978
56.76
Introduction MySQL is a free database included with many web hosting services on linux and Windows platforms. C# ASP .NET developers, using a MySQL database back-end, may notice an unnecessarily large list of sleeping connections that remain online in MySqlAdministrator. This can cause wasteful use of memory on the server, degrade performance, and ultimately, create an error in your C# .NET web application. For example, if you go over the limit set by the database administrator for number of connections, your application will receive a "Too Many Connections" error in MySQL. This can cause your application to fail to display data, fail to load pages, or just freeze up on users viewing the .NET site. Too Many MySQL Connections Open MySqlAdministrator, click on the Server Connections link, and view the active Threads. Web-based ASP .NET applications seem to incorrectly handle connection pooling, and thus leave too many connections in a Sleep state while the Time elapsed continues increasing. These connections would normally be reused by the .NET database driver, and occassionally they are. However, sometimes new connections are opened and existing sleeping connections are forgotten. They will either time out by the server's default connection timeout or simply remain until you pass the connection limit and your application fails. Connection Pooling in MySQL with .NET All .NET database drivers implement connection pooling in MySQL. This includes ODBC, ADO, MySQLConnector, and MySQLDriver. However, there appears to be a flaw in how pooling is handled. Normally, a connection is opened when you call MyConn.Open(). You will see the connection active in MySQLAdministrator and a query is executed. The connection is then placed in the Sleep state upon calling MyConn.Close() (rather than actually being closed), awaiting another query from the ASP .NET application. When a new request arrives with the MyConn.Open(), the existing MySQL connection is used, without having to open a new connection. This increases database performance and speed. The problem in web-based .NET applications is that the driver appears to lose pointers to existing database connections and fails to close them properly. Setting a flag in the database connection string to disable MySQL connection pooling does not appear to work in a web-based ASP .NET application. ie. MySQL ODBC Connection String Driver={MySQL ODBC 3.51 Driver};Server=yourserver.com;Database=yourdatabase;User=databaseuser;Password=databasepassword;Pooling=false; Taking Matters into Your Own Hand Since .NET won't properly close connections that have timed out nor handle the pooled connections properly, we need to implement code that will manage the sleeping connections ourselves. This is required to prevent ASP .NET MySQL applications from failing with the "Too Many Connections" error. There are two possible solutions: 1. Killing the connection after closing it - the idea is that each time you open and close a connection, you add a block of code to physically kill the MySQL process ID. One drawback of this is that you, in effect, remove the advantage of MySQL connection pooling. This may also add an additional burden on the MySQL database of killing the connections each and every time you open one. MyConn.Open();...MyConn.Close();MyConn.Kill(); // This routine would be coded by you 2. A better solution is to write a connection management routine that occasionally scans for sleeping connections which have surpassed a realistic timeout value, and kill them ourselves. The good news is that MySQL offers the "show processlist" and "kill process_id" command, which allows us to take control of the problem in ASP .NET. For example:show processlistkill 9012345 Killing Sleeping Connections in C# ASP .NET The code routine below searches all MySQL connections under your username and kills all sleeping connections which have elapsed a specific number of seconds. For example, all connections in a Sleep state that have a Time value greater than 100 seconds should be closed, and are thus in a good position to be killed. The code example below assumes you are using ODBC to connect to MySQL, but can be easily changed to your desired database driver with a search and replace. using System.Data.Odbc;using System.Data; /// <summary> /// This function checks for any sleeping connections beyond a reasonable time and kills them. /// Since .NET appears to have a bug with how pooling MySQL connections are handled and leaves /// too many sleeping connections without closing them, we will kill them here. /// </summary> /// iMinSecondsToExpire - all connections sleeping more than this amount in seconds will be killed. /// <returns>integer - number of connections killed</returns> static public int KillSleepingConnections(int iMinSecondsToExpire) { string strSQL = "show processlist"; System.Collections.ArrayList m_ProcessesToKill = new ArrayList(); OdbcConnection myConn = new OdbcConnection(Global.strDBServer); OdbcCommand myCmd = new OdbcCommand(strSQL, myConn); OdbcDataReader MyReader = null; try { myConn.Open(); // Get a list of processes to kill. MyReader = myCmd.ExecuteReader(); while (MyReader.Read()) { // Find all processes sleeping with a timeout value higher than our threshold. int iPID = Convert.ToInt32(MyReader["Id"].ToString()); string strState = MyReader["Command"].ToString(); int iTime = Convert.ToInt32(MyReader["Time"].ToString()); if (strState == "Sleep" && iTime >= iMinSecondsToExpire && iPID > 0) { // This connection is sitting around doing nothing. Kill it. m_ProcessesToKill.Add(iPID); } } MyReader.Close(); foreach (int aPID in m_ProcessesToKill) { strSQL = "kill " + aPID; myCmd.CommandText = strSQL; myCmd.ExecuteNonQuery(); } } catch (Exception excep) { } finally { if (MyReader != null && !MyReader.IsClosed) { MyReader.Close(); } if (myConn != null && myConn.State == ConnectionState.Open) { myConn.Close(); } } return m_ProcessesToKill.Count; }// Call it with the following code to kill sleeping connections >= 100 seconds.KillSleepingConnections(100); The above code first calls a "show processlist", which tells MySQL to return a recordset containing all active connections. These connections can be in a variety of states such as: Opening, Closing, Executing Query, Sleep, etc. The function specifically looks for connections in the Sleep state. It then checks the Time value returned by the query to see how long the connection has been sleeping. The process ID (thread id) of connections which exceed the timeout value are recorded in an array list. We then close the process list connection and now loop through the array list of connections that need to be killed. We issue a "kill processid" command which effectively closes and deletes the connection from the MySQL database. This function should be routinely called from a page within your C# ASP .NET web application. For example, it may be included in your default.aspx page or a less popular page. It can even be included within a scheduler task. The idea is that each time the page loads, your MySQL database is checked for sleeping connections that have timed out and have not been killed. Conclusion The above code sample can effectively manage your sleeping MySQL connections in C# ASP .NET, allowing you to take control into your own hands. Always remember to properly close all data readers and database connections, in addition to managing sleeping connections, to have a smooth running ASP .NET web application. About the Author This article was written by Kory Becker, founder and chief developer of Primary Objects, a software and web application development company. You can contact Primary Objects regarding your software development needs at
http://www.primaryobjects.com/CMS/Article69.aspx
crawl-002
refinedweb
1,177
57.37
Google Cloud Platform Kubernetes best practices: Organizing with Namespaces Editor’s note: Today is the second installment in a seven-part video and blog series from Google Developer Advocate Sandeep Dinesh on how to get the most out of your Kubernetes environment. As you start to build more and more services on top of Kubernetes, simple tasks start to get more complicated. For example, teams can’t create Kubernetes Services or Deployments with the same name. If you have thousands of pods, just listing them all would take some time, let alone actually administering them! And these are just the tip of the iceberg. In this episode of Kubernetes Best Practices, let’s take a look at how Kubernetes Namespaces can make managing your Kubernetes resources easier. What is a Namespace?You can think of a Namespace as a virtual cluster inside your Kubernetes cluster. You can have multiple namespaces inside a single Kubernetes cluster, and they are all logically isolated from each other. They can help you and your teams with organization, security, and even performance! The “default” NamespaceIn most Kubernetes distributions, the cluster comes out of the box with a Namespace called “default.” In fact, there are actually three namespaces that Kubernetes ships with: default, kube-system (used for Kubernetes components), and kube-public (used for public resources). kube-public isn’t really used for much right now, and it’s usually a good idea to leave kube-system alone, especially in a managed system like Google Kubernetes Engine. This leaves the default Namespace as the place where your services and apps are created. There is absolutely nothing special about this Namespace, except that the Kubernetes tooling is set up out of the box to use this namespace and you can’t delete it. While it is great for getting started and for smaller production systems, I would recommend against using it in large production systems. This is because it is very easy for a team to accidentally overwrite or disrupt another service without even realizing it. Instead, create multiple namespaces and use them to segment your services into manageable chunks. Creating NamespacesDon’t be afraid to create namespaces. They don’t add a performance penalty, and in many cases can actually improve performance as the Kubernetes API will have a smaller set of objects to work with. Creating a Namespace can be done with a single command. If you wanted to create a Namespace called ‘test’ you would run: kubectl create namespace test Or you can create a YAML file and apply it just like any other Kubernetes resource. test.yaml: kind: Namespace apiVersion: v1 metadata: name: test labels: name: test kubectl apply -f test.yaml Viewing NamespacesYou can see all the Namespaces with the following command: kubectl get namespace You can see the three built-in Namespaces, as well as the new Namespace called ‘test.’ Creating Resources in the NamespaceLet’s take a look at a simple YAML to create a Pod: apiVersion: v1 kind: Pod metadata: name: mypod labels: name: mypod spec: containers: - name: mypod image: nginx You might notice that there is no mention of namespaces anywhere. If you run a `kubectl apply` on this file, it will create the Pod in the current active namespace. This will be the “default” namespace unless you change it. There are two ways to explicitly tell Kubernetes in which Namespace you want to create your resources. One way is to set the “namespace” flag when creating the resource: kubectl apply -f pod.yaml --namespace=test You can also specify a Namespace in the YAML declaration. apiVersion: v1 kind: Pod metadata: name: mypod namespace: test labels: name: mypod spec: containers: - name: mypod image: nginx If you specify a namespace in the YAML declaration, the resource will always be created in that namespace. If you try to use the “namespace” flag to set another namespace, the command will fail. Viewing resources in the NamespaceIf you try to find your Pod, you might notice you can’t! $ kubectl get pods No resources found. This is because all commands are run against the currently active Namespace. To find your Pod, you need to use the “namespace” flag. $ kubectl get pods --namespace=test NAME READY STATUS RESTARTS AGE mypod 1/1 Running 0 10s This can get annoying quickly, especially if you are a developer working on a team that uses its own Namespace for everything and don’t want to use the “namespace” flag for every command. Let’s see how we can fix that. Managing your active NamespaceOut of the box, your active namespace is the “default” namespace. Unless you specify a Namespace in the YAML, all Kubernetes commands will use the active Namespace. Unfortunately, trying to manage your active Namespace with kubectl can be a pain. Fortunately, there is a really good tool called kubens (created by the wonderful Ahmet Alp Balkan) that makes it a breeze! When you run the ‘kubens’ command, you should see all the namespaces, with the active namespace highlighted: To switch your active namespace to the ‘test’ Namespace, run: kubens test Now you can see that the ‘test’ Namespace is active: Now, if you run kubectl commands, the Namespace will be ‘test’ instead of ‘default’! This means you don’t need the namespace flag to see the pod in the test namespace. $ kubectl get pods NAME READY STATUS RESTARTS AGE mypod 1/1 Running 0 10m Cross Namespace communicationNamespaces are “hidden” from each other, but they are not fully isolated by default. A service in one Namespace can talk to a service in another Namespace. This can often be very useful, for example to have your team’s service in your Namespace communicate with another team’s service in another Namespace. When your app wants to access a Kubernetes sService, you can use the built-in DNS service discovery and just point your app at the Service’s name. However, you can create a service with the same name in multiple Namespaces! Thankfully, it’s easy to get around this by using the expanded form of the DNS address. Services in Kubernetes expose their endpoint using a common DNS pattern. It looks like this: <Service Aame>.<Namespace Name>.svc.cluster.local Normally, you just need the Service’s name and DNS will automatically resolve to the full address. However, if you need to access a Service in another Namespace just use the Service name plus the Namespace name. For example, if you want to connect to the “database” service in the “test” namespace, you can use the following address: database.test If you want to connect to the “database” service in the “production” namespace, you can use the following address: database.production Warning: If you create a Namespace that maps to a TLD like “com” or “org”, and then create a Service that has the same name as a website, like “google” or “reddit”, Kubernetes will intercept requests to “google.com” or “reddit.com” and send them to your Service. This can often be very useful for testing and proxying, but can also easily break things in your cluster! Note: If you do want to isolate Namespaces, you should use Network Policies to accomplish this. Stay tuned for more on this in a future episode! Namespace granularityA common question I get is how many Namespaces to create and for what purpose. What exactly are manageable chunks? Create too many Namespaces and they get in your way, but make too few and you miss out on the benefits. I think the answer lies in what stage your project or company is in—from small team, to mature enterprise, each has its own organizational structure. Depending on your situation, you can adopt the relevant Namespace strategy. The small teamIn this scenario, you are part of a small team that is working on 5-10 microservices and can easily bring everyone into the same room. In this situation, it makes sense to launch all production services into the “default” Namespace. You might want to have a “production” and “development” namespace if you want to get fancy, but you are probably testing your development environment on your local machine using something like Minikube. Rapidly growing team(s)In this scenario, you have a rapidly growing team that is working on 10+ microservices. You are starting to split the team into multiple sub-teams that each own their own microservices. While everyone might know how the complete system works, it is getting harder to coordinate every change with everyone else. Trying to spin up the full stack on your local machine is getting more complicated every day. It is necessary at this point to use multiple clusters or namespaces for production and development. Each team may choose to have their own namespace for easier manageability. The large companyIn a large company, not everyone knows everyone else. Teams are working on features that other teams might not know about. Teams are using services contracts to communicate with other microservices (e.g., gRPC) and service meshes to coordinate communication (e.g., istio). Trying to run the whole stack locally is impossible. Using a Kubernetes-aware Continuous Delivery system (e.g., Spinnaker) is highly recommended. At this point, each team definitely needs its own namespace. Each team might even opt for multiple namespaces to run its development and production environments. Setting up RBAC and ResourceQuotas is a good idea as well. Multiple clusters start to make a lot of sense, but might not be necessary. Note: I’ll deep dive into gRPC, Istio, Spinnaker, RBAC, and resources in future episodes! EnterpriseAt this scale, there are groups that don’t even know about the existence of other groups. Groups might as well be external companies, and services are consumed through well-documented APIs. Each group has multiple teams that have multiple microservices. Using all the tools I mentioned above are necessary; people should not be deploying services by hand and should be locked out of Namespaces they don’t own. At this point, it probably makes sense to have multiple clusters to reduce the blast radius of poorly configured applications, and to make billing and resource management easier.
https://cloud.google.com/blog/products/gcp/kubernetes-best-practices-organizing-with-namespaces
CC-MAIN-2019-18
refinedweb
1,695
62.07
Created on 2008-12-29 17:21 by beazley, last changed 2011-07-06 04:59 by anacrolix. This issue is now closed. The email.generator.Generator class does not work correctly message objects created with binary data (MIMEImage, MIMEAudio, MIMEApplication, etc.). For example: >>> from email.mime.image import MIMEImage >>> data = open("IMG.jpg","rb").read() >>> m = MIMEImage(data,'jpeg') >>> s = m.as_string() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tmp/lib/python3.0/email/message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "/tmp/lib/python3.0/email/generator.py", line 76, in flatten self._write(msg) File "/tmp/lib/python3.0/email/generator.py", line 101, in _write self._dispatch(msg) File "/tmp/lib/python3.0/email/generator.py", line 127, in _dispatch meth(msg) File "/tmp/lib/python3.0/email/generator.py", line 155, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) TypeError: string payload expected: <class 'bytes'> >>> The source of the problem is rather complicated, but here is the gist of it. 1. Classes such as MIMEAudio and MIMEImage accept raw binary data as input. This data is going to be in the form of bytes. 2. These classes immediately encode the data using a base64 encoder. This encoder uses the library function base64.b64encode(). 3. base64.b64encode() takes a byte string as input and returns a byte string as output. So, even after encoding, the payload of the message is of type 'bytes' 4. When messages are generated, the method Generator._dispatch() is used. It looks at the MIME main type and subtype and tries to dispatch message processing to a handler method of the form '_handle_type_subtype'. If it can't find such a handler, it defaults to a method _writeBody(). For image and audio types, this is what happens. 5. _writeBody() is an alias for _handle_text(). 6. _handle_text() crashes because it's not expecting a payload of type 'bytes'. Suggested fix: I think the library function base64.b64encode() should return a string, not bytes. The whole point of base64 encoding is to take binary data and encode it into characters safe for inclusion in text strings. Other fixes: Modify the Generator class in email.generator to properly detect bytes and use a different _handle function for it. For instance, maybe add a _handle_binary() method. > I think the library function base64.b64encode() should return > a string, not bytes. Yes, in the email module, the payload is an unicode string, not a bytes string. We have to be able to concatenate headers (eg. "Content-Type: image/fish\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\n") and encoded data (eg. "R0lGO"). Attached patch implements this fix: encode_base64() returns str (and not bytes). The patchs fixes the unit tests and adds a new regression test for MIMEImage.as_string(). Hello, This patch has never been commited. I tested today with the 3.1 branch (and checked in the lib code). Is there a better way to attach images in an email ? Thanks in advance for your help, Regards, Stac Hi, I think the bug is also present in the function encode_quopri which should look like this : def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata = _qencode(orig) data = str(encdata, "ASCII") msg.set_payload(data) msg['Content-Transfer-Encoding'] = 'quoted-printable' I wrote a patch for base64.b64encode() to accept str (str is encoded to utf-8): patch attached to #4768. It should fix this issue, but we can add the tests of email_base64_bytes.patch. Attaching patch from reported duplicate issue8896. Note that my patch is roughly the same as the original posted by haypo. Yes, but yours was better formatted, so I used it :) Thanks for the patch. Applied in r81685 to py3k, and r81686. @garazi111: if you have an example where quopri fails, please open a new issue for it. I suspect you are right that there is a problem there.
http://bugs.python.org/issue4768
crawl-003
refinedweb
668
61.43
Hello, <address@hidden> writes: > On Fri, Apr 10, 2009 at 08:51:03PM +0300, Sergiu Ivanov wrote: >> <address. > > Not at all -- the idea is to use something completely different instead > of unionfs, if we require different functionality... > > Having the merging code in a separate component (be it unionfs or > something more specialized), would indeed make it easier to use > different policies. However, the complexity involved makes me object to > such an approach, at least in the initial implementation. This was the thing that made me a better adept of the forking idea. > Note that at the beginning of the namespace based translator selection > project, I suggested handling various special syntax in external > components (like the filter), instead of hard-coding it in nsmux, to > gain more flexibility. I believed it would simplify the design, because > this way we wouldn't have to think about the various policies when > working on nsmux itself. I wasn't aware how much the added complexity of > the modular approach will make it harder to figure out the basics; how > much it will frustrate progress... Yes, I remember our discussion on that matter... > We are in a very similar situation here -- but I have learned from last > time. Go for the simple approach first, and only later think about a > more flexible solution. We have a deadline to meet. OK. I think I've got the idea :-) >> >>. > > Ah, I wasn't aware that you were talking about monolitic implementation > vs. external implementation of internal nodes here... In that case, I > totally agree. > > I thought you referred to individual processes for each internal node > vs. a central server for them -- which, as I said elsewhere, doesn't > make much of a difference I believe. I see... I cannot see why it should make difference, either. Regards, scolobb
http://lists.gnu.org/archive/html/bug-hurd/2009-04/msg00074.html
CC-MAIN-2013-20
refinedweb
301
64.3
Text Editor Application Using Tkinter In this tutorial, we will help you to build a simple Text Editor Application using Tkinter which is a very good beginner project for Tkinter. Text Editor Application is an application where you can write your text, open any text file, you can edit any text file and you can also save a file if you want. In this tutorial, we will build a Text Editor Application from scratch. Essential Elements for the Text editor application are as follows: There is a Button widget called btn_openthat is used for opening a file for editing Second one is a Button widget called btn_savefor saving a file Third, there is a Text widget called txt_editfor creating and editing any text file. The arrangement of three widgets is done in a way such that the two buttons are on the left-hand side of the window, and the text box is on the right-hand side. The minimum height of the whole window should be 900 pixels and txt_edit should have a minimum width of 900 pixels. And The whole layout should be responsive if the window is resized, then txt_edit is resized as well. The width of the Frame that holds the buttons should not change. Let us show you with a rough sketch of how this text editor will look like: The desired layout of the Text Editor Application can be achieved using the .grid() geometry manager. And this layout contains a single row and two columns: On the left side, there is A narrow column for the buttons On the right side, there is A wider column for the text box In order to set the minimum sizes for the window and txt_edit, you just need to set the minsize parameters of the window methods .rowconfigure() and .columnconfigure() to 900. In order to handle the resizing, the weight parameters of these methods will be set to 1. If you want both the buttons in the same column then you’ll need to create a Frame widget called fr_buttons. According to the above-shown sketch, the two buttons should be stacked vertically inside of this frame, having btn_open on top. This can be done either by .grid() or .pack() geometry manager. For now, you’ll just need to stick with .grid() as it is easier to work with it. Let us start with the code for building the Application: 1. Creating all the needed widgets The code snippet that is used is as follows: import tkinter as tk window = tk.Tk() window.title("Text Editor Application") window.rowconfigure(0, minsize=900, weight=1) window.columnconfigure(1, minsize=900, weight=1) txt_edit = tk.Text(window) fr_buttons = tk.Frame(window) btn_open = tk.Button(fr_buttons, text="Open") btn_save = tk.Button(fr_buttons, text="Save As...") Explanation of the above code: The first command is used to import the tkinter. Then the next two lines are used to create a new window with the title "Text Editor Application". The next two lines of code are used to set the row and column configurations. Then the lines from 9 to 12 will create the four widgets you’ll need for the text box, the frame, and the open and save buttons. window.rowconfigure(0, minsize=900, weight=1) The above-given line in the code indicates The minsize parameter of .rowconfigure() is set to 900 and weight is set to 1.The first argument is 0, which is used to set the height of the first row to 900 pixels and makes sure that the height of the row grows proportionally to the height of the window. There’s only one row in the application layout, so these settings are applied to the entire window. Then take a look at this line in the code : window.columnconfigure(1, minsize=900, weight=1) In the above code the .columnconfigure() to set the width and weight attributes of the column with index 1 to 900 and 1, respectively. Keep it in mind that, row and column indices are zero-based, so these settings apply only to the second column. By configuring the second column, the text box will expand and contract naturally when the window is resized, while the column containing the buttons will always remain at a fixed width. 2.Creation of Application Layout btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5) btn_save.grid(row=1, column=0, sticky="ew", padx=5) The above two lines of code will create a grid with two rows and one column in the fr_buttons frame since both btn_open and btn_save have their master attribute set to fr_buttons. btn_open is put in the first row and btn_save will be in the second row so that btn_open appears above btn_save in the layout, as planned in the above sketch. The btn_openand btn_saveboth have their stickyattributes set to "ew", which forces the buttons to expand horizontally in both directions and in order to fill the entire frame. It makes sure both buttons are of the same size. You place 5 pixels of padding around each button just by setting the padxand padyparameters to 5. The btn_openhas vertical padding. Because it’s on top, the vertical padding offsets the button down from the top of the window a bit and makes sure that there’s a small gap between this and btn_save. Now the fr_buttons is laid out and ready to go, you can just set up the grid layout for the rest of the window now: fr_buttons.grid(row=0, column=0, sticky="ns") txt_edit.grid(row=0, column=1, sticky="nsew") These above two lines of code are used to create a grid with one row and two columns for window. You place fr_buttons in the first column and txt_edit in the second column so that fr_buttons appears to the left of txt_edit in the window layout. The sticky parameter for fr_buttons will be set to "ns", which forces the whole frame to expand vertically and fill the entire height of its column. txt_edit is used to fill its entire grid cell because you set its sticky parameter to "nsew", which forces it to expand in every direction. Now we have just created the buttons but these do not work until we add functioning to them So let's start adding the Functioning of Buttons: 1. Function to Open the File The code snippet for open_file is as follows:}") Explanation: The Lines from 3 to 5 use the askopenfilenamedialog from the tkinter.filedialogmodule to display a file open dialog and store the selected file path to filepath. Lines 6 and 7 checks to see if the user closes the dialog box or clicks the Cancel button. If so, then filepathwill be None, and the function will returnwithout executing any of the code to read the file and set the text of txt_edit. Line 8 clears the current contents of txt_editusing .delete(). Lines 9 and 10 are used to open the selected file and .read()its contents before storing the textas a string. Line number 11 assigns the string textto txt_editusing .insert(). Line 12 sets the title of the window so that it contains the path of the open file. 2. Function to Save the File The code snippet for save_file is as follows:}") Explanation: Lines 3 to 6 use the asksaveasfilenamedialog box to get the desired save location from the user. The selected file path is stored in the filepathvariable. Lines 7 and 8 checks to see if the user closes the dialog box or clicks the Cancel button. If so, then filepathwill be None, and the function will return without executing any of the code to save the text to a file. Line 9 creates a new file at the selected file path. Line 10 extracts the text from txt_editwith .get()method and assigns it to the variable text. Line 11 writes textto the output file. Line 12 updates the title of the window so that the new file path is displayed in the window title. Complete Source code is: import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename}") window = tk.Tk() window.title("Text Editor Application") window.rowconfigure(0, minsize=800, weight=1) window.columnconfigure(1, minsize=800, weight=1) txt_edit = tk.Text(window) fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2) btn_open = tk.Button(fr_buttons, text="Open", command=open_file) btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file) btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5) btn_save.grid(row=1, column=0, sticky="ew", padx=5) fr_buttons.grid(row=0, column=0, sticky="ns") txt_edit.grid(row=0, column=1, sticky="nsew") window.mainloop() As you can see in the output, we have a basic text editor application in which we can write something and then save the text in a new file or use the Open button to open a file in the editor and then edit it.
https://www.studytonight.com/tkinter/text-editor-application-using-tkinter
CC-MAIN-2021-04
refinedweb
1,494
64.3
It’s interesting to see the varying emotions people have had in reaction to the standardization of the Office Open XML formats. It was obviously an immense amount of work, and it resulted in a 6,000 page standard. As you all know by now, the reason there was so much information in the specification was that we absolutely had to ensure that all the information people currently had in their existing set of Office binary documents could be ported over into the new format (with no loss). In addition to that, we wanted to make sure we did our best to ensure that anyone coming trying to build support for the OpenXML formats in their solution had all the information they would need for consuming and producing those documents. This meant we had to go beyond the basics, and document all the pieces of the format we could. This is where you start to see the differences between the approach taken with the ODF standard and the OpenXML standard. In the ODF standard, the decision was made to leave a lot of the pieces out of the standard and to instead have them be application defined. This means you have a simpler standard, but it also means that interoperability is much more difficult to achieve. Let me explain: As you start to document a specific feature in a file format, you have a few choices: Fully document – This means you define the syntax for representing the feature, and all the information people would need to interpret it. - Pros: Everyone can build support for the feature using the specification. - Cons: None really (other than it makes the spec bigger) Partially document – This means you define the syntax for representing the feature, but don’t provide all the details for implementation. - Pros: If two application already have the behavior, it means they have a prescribed method for persisting that in the file format. So while the spec doesn’t tell you how to implement the behavior, it does help you interoperate with others who already know the behavior. - Cons: It’s not as interoperable as when you fully document something, but it still allows for more interoperability than the next approach. Application defined – This means you allow the specification to be extended by an implementer to represent the feature as they choose. Usually you provide a way in which they can use their own namespace for identifying it as not being part of the standard but instead an extension. - Pros: This is the only option to account for things not yet in use when the standard was written. - Cons: There is no way to interoperate using the spec. You need to look at the implementation for any applications you will be interacting with and see how they extended the spec. One of the sections people have been wondering about in the Open XML spec is section 2.15 in part 4 (Markup Language Reference). That section defines a couple hundred document level settings. Some of for application behaviors like “don’t check spelling.” Others are for display behaviors like “show gridlines on tables.” And others are for layout behaviors like “align tables row by row.” The important thing for people to realize is that many of these settings are common in a number of Wordprocessing applications. KOffice, OpenOffice, and Microsoft Office all have a similar set of document settings. In ODF, they took the “application defined” approach for the settings, rather than either partially or fully documenting (similar to the original approach with spreadsheet formulas). So, if you save out a blank text document or spreadsheet from OpenOffice you’ll get the following set of extended properties, and not a single one of these appear in the ODF standard (many of these directly impact the interoperability of the document in terms of layout and display): OpenOffice extensions to ODF standard using the namespace If you were to use KOffice to open the document, it wouldn’t understand any of these settings as they are all in the namespace and not defined in the ODF standard. The OpenOffice folks most likely document many of these on their own site so KOffice could use that material when trying for interoperability, but at that point they’ve had to go beyond the ISO standard and start to rely on application specific information that OASIS and ISO have no say over. In KOffice they also have document settings (although it doesn’t appear to be nearly as much as OpenOffic) So with KOffice, you would get a different set of properties (here are a few I found): KOffice extensions to ODF standard using empty namespace Settings in OpenXML Let’s compare that with the OpenXML specification where the large majority are fully documented, and only a few are partially documented (none are application defined). Also note that all of these are completely optional for implementation, and even within Microsoft Office we try to move our customers toward turning many of them off (especially the application specific legacy behaviors). Obviously there may be more settings out there in other applications than what we’ve specified, and the spec is fully extensible to allow for those as well. We wanted to try to cover all of those currently in use, and as we find new ones we can add them to the spec if needed: -Brian You have done what appears to be some thoughtful research on the issue, will you be sending this back to the ODF team ? This would have been valuable feedback during the development of ODF 1.0 and might still be. The ODF team seems to be open to external input and I am sure they would at least pay attention to your input. I also noticed this recent blog article that covers the same subject a bit more opinionated: @Scot I think the Ecma would have wished for some the input that was given to their final draft and the standardized version a in a bit earlier sstage as well earlier as well. Especially a lot of the minor or non-issues found by Groklaw that could have been dealt with with minor changes or a better explanation in the spec. It seems that the OOXML spec might have suggested that these tags next to trying to emulate rendering can alternativly be used to inform a user that a converted document might be created using a application that used an alternative rendering for <fill in item description>. That is a much easier to implement and will suffice for virtually all implementaions and converted documents. It’s nice to see how Microsoft changed since the time (no so long ago) when they did all they could to AVOID interoperability (remember Java, IE behaviour, ActiveX… ?). Now Microsoft has become the champion of interoperabity, and decided to create OOXML because they were deceived by the poor interoperability offered by ODF. Thank you, Microsoft. Albert – I have seen almost nothing in the Groklaw work that was not commented about long before Ecma approved OOXML. The Groklaw team did a great job of pulling it all together and pointing out specifics, but there is little new that they found. What is frustrating (and you can see from old posts here and elsewhere) is that there seemed to be a resistance to "fixing" any of those issues raised, and there was much more emphasis on defending whatever had been done in OOXML, no matter howw indefensible. BTW, I like the new direction Brian is taking with more positive posts. I think they are both more effective and more interesting than some of the earlier, slightly knee-jerk responses. This post, in particular, is well researched and presented. Even if one does not entirely agree with the premise, and I have mixed feelings about it, it is a much, much more effective post because it seeks to explain a way of thinking that is encapsulated in the specifications rather than just attack or defend. Brian – Nice work! – Ben @Ben How much comments did you see before the 1.4 final draft was released. Strangly the 1.3 draft (which was released to ISO in may 2006) or even the earlier versions was much less commented on. Especially IBM seemed to have a ‘small’ team working on looking at possible issues in the specs and blogging about it (or Rob is really good). Simular to I guess Brian probalby has some people that researched this article But those issues were mostly mentioned after the release of the final draft and I do think that the Office release was indeed a mayby to important date to strive for to make any more changes after that because it would have delayed the spec for a minimum of 6 months. Dans la guerre des formats entre ODF et Open XML, il est dur de trouver de l’information fiable et surtout I just noticed that Rob Weir has reacted to this post. He asks himself how an application can define it’s own application defined settings that are not part of section 2.15 of the OOXML specs. A good point. I think he must have missed that in OOXML you can add custom tags simular to ODF office settings. However in OOXML custom tags require a custom schemaname. That at least provides a source for the custom tags and makes them unique. The custum config items in ODF’s office settings do not have a source so you cannot see what they do nor can you see which application added them to the ODF file nor are config items unique. application can create duplicate office settings names in ODF. This makes them inoperable by design. It does leave a question for Brian why OOXML did not put the 2.15 section tags into it’s custom tags together with adding a custom MS Office schema for the items ? Unfortunately I haven’t had the time lately to catch up on any of Rob Wier’s posts. He seems to like have gone further and further into the theoretical arena, while I like to stay more practical. Otherwise it just becomes a huge waste of time. I have limited cycles in the day to focus on file formats, and I’d much rather spend that time discussing the goals behind real world scenarios. Let’s look at those goals and then determine whether or not the technologies in question can meet them. We aren’t philosophers; we’re geeks who build software to solve people’s problems… In response to your question though, there are a number of ways in which applications can extend the schema, and they are all very well documented between parts 4 and 5 of the standard. The extensions are there not just for other folks implementing the standard, but also to allow future versions of the standard to stay compliant with version 1.0. That way we won’t break any existing solutions when version 2.0 is released. -Brian Hi, Maybe you have read about projects for supporting UOF . Similar approach to the ODF support. You For those of you not only reading my blog, but also the other content provided by the Info Support blog
https://blogs.msdn.microsoft.com/brian_jones/2007/02/20/beyond-the-basics/
CC-MAIN-2016-44
refinedweb
1,880
57.1
This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python. import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline x1 = np.random.randn(80) x2 = np.random.randn(80) x3 = x1 * x2 y1 = .5 + 2 * x1 - x2 + 2.5 * x3 + 3 * np.random.randn(80) y2 = .5 + 2 * x1 - x2 + 2.5 * np.random.randn(80) y3 = y2 + np.random.randn(80) plt.figure(figsize=(4,3)); sns.violinplot([x1,x2, x3]); regplot) to perform and display a linear regression between two variables. plt.figure(figsize=(4,3)); sns.regplot(x2, y2); DataFrame. df = pd.DataFrame(dict(x1=x1, x2=x2, x3=x3, y1=y1, y2=y2, y3=y3)) sns.corrplot(df); You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).
http://nbviewer.jupyter.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter06_viz/02_seaborn.ipynb
CC-MAIN-2017-47
refinedweb
166
62.64
Originally posted by Shivaji Marathe: Sonir : public class TestClass implements Runnable{ int x = 5; public void run() { this.x = 10; } public static void main(String[] args) { TestClass tc = new TestClass(); new Thread(tc).start(); // 1 System.out.println(tc.x); } } When you call the start method a new thread object is handed over to the thread scheduler. After this,the rest of the main method maycontinue execution. If this happens the value printed will be the original value of x, i.e. 5. OR the thread schduler may start running the newly created thread in which case the value of x will be 10. Based on the operating system's scheduling algorithms and on the other threads that are running/ready at the time you run this code, the output may differ. HTH [ January 17, 2002: Message edited by: Shivaji Marathe ]
http://www.coderanch.com/t/236167/java-programmer-SCJP/certification/method
CC-MAIN-2015-35
refinedweb
141
65.42
I copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class PersonalLoan string AccountNumber { get; set; } public float LoanAmount { get; set; } public bool IsLoanApproved { get; set; } public Loan(string accountNumber) { Console.WriteLine("Loan loading started"); this.AccountNumber = accountNumber; this.LoanAmount = 1000; this.IsLoanApproved = true; Console.WriteLine("Loan loading started"); } } I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that Personal loan has a Loan This, however, is unlikely the relationship that they are trying to model: in reality, Personal loan is a Loan The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this: public class PersonalLoan : Loan { public PersonalLoan(string accountNumber) : base(accountNumber) { ... } ... } Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber. This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this: class Address { public string Country {get;set;} public string City {get;set;} ... // And so on } class Borrower { public Address MailingAddress {get;set;} ... // } This model is perfectly valid, because Borrower has an Address.
https://codedump.io/share/p4qdeeFFvFgO/1/declaring-class-as-properties-inside-another-class
CC-MAIN-2018-26
refinedweb
293
53.92
In IR and many other research domains, we always have to use statistical Test to evaluate whether a newly proposed model can bring significant improvement over baselines. I do not want to judge it is a good means. Here I just introduce how to conduct statistical Test using R, python, etc. ————————————————– ————————————————– Wil. > library(MASS) # load the MASS package > head(immer) Loc Var Y1 Y2 1 UF M 81.0 80.7 2 UF S 105.4 82.3 ….. Problem >cox.test(immer$Y1, immer$Y2, paired=TRUE) Wilcoxon signed rank test with continuity correction data: immer$Y1 and immer$Y2 V = 368.5, p-value = 0.005318 alternative hypothesis: true location shift is not equal to 0 V = 368.5, p-value = 0.005318 alternative hypothesis: true location shift is not equal to 0 Warning message: In wilcox.test.default(immer$Y1, immer$Y2, paired = TRUE) : cannot compute exact p-value with ties Answer In wilcox.test.default(immer$Y1, immer$Y2, paired = TRUE) : cannot compute exact p-value with ties Answer At .05 significance level, we conclude that the barley yields of 1931 and 1932 from the data set immer are nonidentical populations. ————————————- Wilcoxon Signed Test with Python. It would be even easier for the Wilcoxon Test with Python. Just the following lines: import scipy.stats as stat wvalue = stat.wilcoxon(diffs) print “wilcoxon value:”, wvalue A tool of Wilcoxon Signed Test for TREC evaluation is provided in the following link:
http://blog.so8848.com/2012/09/wilcoxon-signed-rank-test-for-r-and.html
CC-MAIN-2017-39
refinedweb
242
59.7
Adding a optional parameter is a breaking change. This topic came up more frequently around the time the feature was introduced but, I haven’t seen it brought up in a while. I mentioned it on a code review recently so, now it’s fresh on my mind. The “breaking” nature of optional parameters is a fun one because it is not entirely obvious. How is it breaking when the consuming code doesn’t need to change? Well, like anything in software development, there is a logical explanation. Lets take a look at the following code. Imagine we have a library that contains a message queue. We might have something like the IMessageQueue interface below. public interface IMessageQueue { void Publish<T>(Message<T> message); } Next, as part of our business requirements, we need to have the ability to send emails. We remember our super cool message queue so, we decide to use it. This leaves us with the following EmailService. public class EmailService { private readonly IMessageQueue _queue; public EmailService(IMessageQueue queue) { _queue = queue; } public void Send(Email email) { _queue.Publish(new Message<Email>(email)); } } Some time goes by and we want to enhance our message queue. We know that there are a couple other libraries that are using it so, we make sure to add default values to all our new parameters. With the following code, our consumers can still invoke the Publish method exactly as they have before. public interface IMessageQueue { void Publish<T>(Message<T> message, MessagePriority priority = MessagePriority.Normal); } So where’s the breaking change?!? The code looks exactly the same. The secret lies in the IL code that is generated. Let’s look at the the following line of code _queue.Publish(new Message<Email>(email)); Prior to our code changes, we get IL that looks like the following: callvirt instance void EspressoCoder.Samples.Defaults.IMessageQueue::Publish<class EspressoCoder.Samples.Defaults.Email>(class EspressoCoder.Samples.Defaults.Message`1<!!0/*class EspressoCoder.Samples.Defaults.Email*/>) IL_0012: nop After we add the default parameter, we notice the IL changes: ldc.i4.1 IL_000e: callvirt instance void EspressoCoder.Samples.Defaults.IMessageQueue::Publish<class EspressoCoder.Samples.Defaults.Email>(class EspressoCoder.Samples.Defaults.Message`1<!!0/*class EspressoCoder.Samples.Defaults.Email*/>, valuetype EspressoCoder.Samples.Defaults.MessagePriority) IL_0013: nop Why does .NET compile these changes changes differently? It is because .NET determines the default values at compile time. When the function is invoked, it is called with all default parameter values even though you do not see this in code. Pay special attention to the line IL_000d: ldc.i4.1. The last character in this line is ‘1’ which is the numeric representation of the MessagePriority.Normal default value. On the following line, we can then see that the full function (with all parameters) is invoked. What does this mean? It means anytime we modify the parameter list, with required OR optional parameters, the consumers need to be updated. Even if that means merely recompiling against the updated function. For example, if these two classes are in the same project or even the same solution you will not have an issue. Unfortunately, this is not always possible. Compiled libraries are often delivered as nuget packages from either internal or external repositories. With the previous example, it would be perfectly reasonable to have our two classes in separate nuget packages. In this case, a runtime error will occur. This doesn’t mean these sorts of changes CANT or SHOULDN’T be made. What it does mean is if they are, appropriate versioning must be made otherwise, pain will ensue.
https://espressocoder.com/2018/09/10/dont-break-consumers-with-optional-parameters/
CC-MAIN-2020-40
refinedweb
596
50.84
trywith Resource Statement JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management. It is also referred to as automatic resource management. Syntax: try(resource-specification(there can be more than one resource)) { //use the resource } catch() { ... } This try statement contains a parenthesis in which one or more resources is declared. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement of the try block. You do not have to explicitly close the resources. trywith Resource Statement import java.io.*; class Test { public static void main(String[] args) { try { String str; //opening file in read mode using BufferedReader stream BufferedReader br = new BufferedReader(new FileReader("d:\\myfile.txt")); while((str=br.readLine())!=null) { System.out.println(str); } br.close(); //closing BufferedReader stream } catch(IOException ie) { System.out.println("exception"); } } } trywith Resource Statement import java.io.*; class Test { public static void main(String[] args) { try(BufferedReader br = new BufferedReader(new FileReader("d:\\myfile.txt"))) { String str; while((str = br.readLine()) != null) { System.out.println(str); } } catch(IOException ie) { System.out.println("exception"); } } } NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.
https://www.studytonight.com/java/try-with-resource-statement.php
CC-MAIN-2020-05
refinedweb
251
52.05
In this step, you will create a new custom control. You will also insert a method into the control that calls a method on one of the controls you imported earlier. Through the preceding steps, you should have created the following two Java files in the controls folder: These files contain only a default framework at this point. You will add a method in the following steps. import model.Customer; public Customer[] getLocalCustomers() { return customerControl.getCustomersByState("CA"); } To correct this situation place the editor's cursor anywhere in the name of the method (getLocalCustomers) and press Ctrl+1. Select Create in super type 'MailingListControl' and press Enter. MailingListControl.java opens in the editor with the new method definition in place. The getLocalCustomers method on this control uses the imported controls to query a sample database for all customers in a given state. In this example, we have hard-coded the state to be California. The data returned from the database is returned to the calling method as an array of Customer objects. Click one of the following arrows to navigate through the tutorial:
http://docs.oracle.com/cd/E13224_01/wlw/docs100/guide/webservices/WSTutorial/tutWebSvcStep6.html
CC-MAIN-2016-18
refinedweb
183
56.55
Download on your machine from here. You can check whether Node.js is installed by running the command, - node –version To start with creating a folder and change directory to that folder. In the directory create package.json file using the command: - npm init Just keep pressing the return key (Enter) for all the questions to create a default package.json file. After that Install all dependencies for TypeScript and Express - npm install -D typescript - npm install -D tslint - npm install express -S - npm install @types/express -D In the npm command -D flag is for –save-dev and -S flag is for –save. After successfully installing the dependencies, create a tsconfig.json file in the root of the project directory. Inside the tsconfig.json file put the following information, { "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "moduleResolution": "node", "sourceMap": true, "outDir": "dist" }, "lib": ["es2015"] } We have set various compiler options such that TypeScript code should be transpile to the ES6 standard of JavaScript and it should follow node.js module resolution. You can learn more about various options here After configuring TypeScript compiler options, add a file with name tslint.json in the root folder and add this code, { "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "jsRules": {}, "rules": { "no-console":false }, "rulesDirectory": [] } We have enabled console in the rules for better debugging. After this, modify the package.json file. Just modify the main section and start the script as shown below. { "name": "typescriptinnode", "version": "1.0.0", "description": "", "main": "dist/app.js", "scripts": { "start": "tsc && node dist/app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Dhananjay Kumar <debugmode@outlook.com> ()", "license": "ISC", "devDependencies": { "@types/express": "^4.17.2", "tslint": "^5.20.1", "typescript": "^3.7.4" }, "dependencies": { "express": "^4.17.1" } } In the package.json file main entry specifies the entry point of the application. TypeScript trasnpiles the *.ts file and put them inside dist folder with extension *.js, as we have specified that in previous steps. So, the app.ts file would be trasnpiled as an app.js file and would be saved in the dist folder. The start entry in the script section specifies that the first TypeScript compiler will run and then the node will run the app.js file from the dist folder. In this configuration, the app.ts file is going to be the main file. If you want to make index.js as the main entry of application, modify the main and start entry in package.json file accordingly. As of now, we have configured the Node.js project to work with TypeScript and Express. Next, create an src folder and add two files inside that app and product ts files. After adding these two files, your project structure should look like below, To test whether you have performed all steps correctly, in the app.ts file put the below code, class Product { public Title ; } let p = new Product(); p.Title = "Pen"; console.log(p); On then run the command npm start, you should get p object printed. Alright, next to create REST API using Express, in the product.ts file add below code, export class Product { public Id : string; public Title : string; public Price : number; public inStock : boolean; } After that in the app.ts file, put the below code: import express from 'express'; import {Product } from './product'; const app = express(); const port = 3000; function getProduct(){ let p = new Product(); p.Id = "1"; p.Price= 100; p.Title="Cricket Bat"; p.inStock = true; return p; } app.get('/products', (req, res) => { res.send(getProduct()); }); app.listen(port, err => { if (err) { return console.error(err); } return console.log(`server is listening on ${port}`); }); Let us walk through the code, - Importing Express and product module. Due to TypeScript, we can use ES6 module export import instead of Node.js require - getProducts() function returns list of products - express get() method get executed when client will perform HTTP request operations on /products url. - Listening to the express server at port 3000. Now run the application again with npm start, you should get console message that server is listening on 3000. Navigate to localhost:3000/products, and you should able to get list of products returned. Download or clone source code from here So, you have successfully created a Node.js application using TypeScript. In another blog post, I will discuss in detail about express and TypeScript. I hope you find this post useful. Thanks for reading. 2 thoughts on “Step by Step using TypeScript in a Node.js Application”
https://debugmode.net/2019/12/31/step-by-step-using-typescript-in-node-js-application/
CC-MAIN-2022-05
refinedweb
752
61.22
Issues returning the sorted set of sources in _Automoc::__call__ actually returns a list sorted on object pointers Originally reported by Danny Valente: in the method _Automoc::call, a sorted set of sources are returned from the emitter. The call to "sorted" is done on a set of Entry objects however. A cmp argument is needed to be passed to the sorted function in order to sort on the file names correctly instead. Changing the line to this: return (target, sorted(set(out_sources), lambda x,y: cmp(str(x),str(y)))) fixes the poblem. Otherwise, the scons builds again because the dependencies order has changed in most cases. Hi Danny, and thanks a lot for the bug report. I'll have a look... Best regards, Dirk I checked in a new revision #18, it corrects the problem by specifying a key() for proper comparison of file/entry names. A new testcase for this bug was added too. Dirk
https://bitbucket.org/dirkbaechle/scons_qt4/issues/7/returning-the-sorted-set-of-sources-in
CC-MAIN-2017-39
refinedweb
158
63.39
. Initially, all the three values will be as zero, but as you move your breadboard you can observe these values getting changed. If they change it means your connection is correct, else check your connections. Take some time here notice how the three values Pitch Roll and Yaw vary according to the way you tilt your sensor. If you get confused press the reset button on the Arduino and the values will be initialized to zero again, then tilt the sensor in one direction and check which values are varying. The below picture will help you to understand better. Out of these three parameters we are interested only in Roll and Pitch. The Roll value will tell us about the inclination in X-axis and the Pitch value will tell us about the inclination in Y-Axis. Now that we have understood the basics lets actually start programming the Arduino to read these values send it over to Arduino via Bluetooth. As always let's start by including all the libraries needed for this project #include <Wire.h> //Lib for IIC communication #include <MPU6050.h> //Lib for MPU6050 #include <SoftwareSerial.h>// import the serial library Then we initialize the software serial for the Bluetooth module. This is possible because of the Software Serial library in Arduino, the IO pins can be programmed to work as Serial pins. Here we are using the digital pins D10 and D11, where D10 id Rx and D11 is Tx. SoftwareSerial BT(10, 11); // RX, TX Followed by that we initialize the variables and objects needed for the program and move onto the setup() function where we specify the baud rate for Serial monitor and Bluetooth. For HC-05 and HC-06 the baud rate is 9600 so it is mandatory to use the same. Then we check if the IIC bus of Arduino is connected to MPU6050 if not we print a warning message and remain there as long as the device is connected. After that, we calibrate the Gyro and set its threshold values using its respective functions as shown below. } The line “mpu.calibrateGyro();” calibrate the MPU6050 for the position it is currently placed at. This line can be called multiple times inside the program whenever the MPU6050 needs to be calibrated and all values are to be set to zero. “mpu.setThreshold(3);” this function controls how much the value varies for the movement on sensor a too low value will increase the noise so be careful while fiddling around with this. Inside the void loop(), we repeatedly read the values of Gyroscope and Temperature sensor calculate the value of pitch, roll and yaw, send it to the Bluetooth module. The following two lines will read the raw Gyro values and the temperature value Vector norm = mpu.readNormalizeGyro(); temp = mpu.readTemperature(); Next, we calculate the pitch, roll, and yaw by multiplying with time step and adding it up to the previous values. A timeStep is nothing but the interval between successive readings. pitch = pitch + norm.YAxis * timeStep; roll = roll + norm.XAxis * timeStep; yaw = yaw + norm.ZAxis * timeStep; To understand time step better let’s take a look at the below line. This line is placed to read the values from MPU6050 exactly at an interval of 10mS or 0.01 Second. So we declare the value of timeStep as 0.01. And use the line below to hold the program if there if there is more time left. (millis() – timer()) gives the time taken for the program to execute so far. We just subtract it with 0.01 seconds and for the remaining time we just hold our program there using the delay function. delay((timeStep*1000) - (millis() - timer)); Once we are done reading and calculating the values, we can send them over to our phone via Bluetooth. But there is a catch here. Bluetooth module that we are using can send only 1 byte (8 bits) which allows us to send numbers only from 0 to 255. So we have to split our values and map it inside this range. This is done by the following lines if (roll>-100 && roll<100) x = map (roll, -100, 100, 0, 100); if (pitch>-100 && pitch<100) y = map (pitch, -100, 100, 100, 200); if (temp>0 && temp<50) t = 200 + int(temp); As you can figure it out, the value of roll is mapped into 0 to 100 into the variable x and pitch is mapped to 100 to 200 into the variable y and temp is mapped into 200 and above into the variable t. We can use the same information to retrieve the data from what we have sent. Finally we write these values via the Bluetooth using the following lines. BT.write(x); BT.write(y); BT.write(t); If you have understood the complete program, scroll down to have a look at the program and upload it to the Arduino board. Preparing the Android Application using Processing: The android application for this Arduino Inclinometer was developed using the Processing IDE. This is very much similar to Arduino and can be used to create system application, Android application, web designs and much more. We have already used processing to develop some of our other cool projects that are listed below - Ping Pong Game using Arduino - Smart Phone Controlled FM Radio using Processing. - Arduino Radar System using Processing and Ultrasonic Sensor However, it is not possible to explain the complete code on how to create this application. So you have two ways to go over this. Either you can download the APK file from the below link and install the android application directly on your phone. Or scroll below to find the complete processing code and learn by yourself how it works Android APK File for Arduino Inclinometer (Right Click and Save Link As...) Note: The application by default only connects to Bluetooth devices named as “HC-06” Understanding the Processing Code: For those who chose the later of understanding the processing code, I would like to explain few important points. The code requires Android mode of processing to be functioning which in turn needs the Android SDK files. The installation is a bit bulky but it is all worth it. Second, if you are trying to use this code given below then you will need the following ZIP file which contains the data file along with the code Processing program ZIP file for Arduino Inclinometer Inside the ZIP file, you can find a folder called data which consists of all the images and other sources that is to be loaded into the android application. The below line decides to which name the Bluetooth should automatically connect to bt.connectToDeviceByName("HC-06"); Inside the draw() function, the things will be executed repeatedly here we draw the images, display the text and animate the bars based on the values form the Bluetooth module. You can check what happens inside each function by reading through the program. void draw() //The infinite loop { background(0); imageMode(CENTER); image(logo, width/2, height/1.04, width, height/12); load_images(); textfun(); getval(); } Finally, there is one more important thing to explain, remember that we split the value of pitch, roll and temp to 0 to 255. So here we again bring it back to normal values by reverse mapping it to normal values. if (info<100 && info>0) x = map(info, 0, 100, -(width/1.5)/3, +(width/1.5)/3);//x = info; else if (info<200 && info>100) y = map(info, 100, 200, -(width/4.5)/0.8, +(width/4.5)/0.8);//y = info; else if (info>200) temp = info -200; println(temp,x,y); There are much better ways to get data from a Bluetooth module to phone, but since this is just a hobby project we have ignored them, you can dig deep if interested. Working of Arduino Inclinometer: After you get ready with the Hardware and Application, it’s time to have fun with what we have built. Upload the Arduino Code to the board, you can also remove the comments on Serial.println lines and check if the hardware is working as expected using the serial monitor. Anyway, that is completely optional. Once the code is uploaded, launch the Android application on your mobile phone. The application should automatically connect to your HC-06 module and it will display “Connect to: HC-06” on the top of the application as shown below. Initially, all the values will be zero except for the temperature value. This is because the Arduino has calibrated the MPU-6050 for this position as a reference, now you can tilt the hardware and check that the values on the mobile application are also changing along with the animation. The complete working of the application can be found at the video given below. So now you can place the breadboard anywhere and check if the surface is perfectly leveled. Hope you understood the project and learned something useful out of it. If you have any doubt please use the comment section below or the forums to get it resolved. /* MPU6050 Librarey: (c) 2014 by Korneliusz Jarzebski */ #include <Wire.h> //Lib for IIC communication #include <MPU6050.h> //Lib for MPU6050 #include <SoftwareSerial.h>// import the serial library SoftwareSerial BT(10, 11); // RX, TX MPU6050 mpu; unsigned long timer = 0; unsigned long timer2 = 0; float timeStep = 0.01; float pitch = 0; float roll = 0; float yaw = 0; float temp =0; } void loop() { timer = millis(); //Read Gyro and Temperature sensor values Vector norm = mpu.readNormalizeGyro(); temp = mpu.readTemperature(); // Calculate Pitch, Roll and Yaw pitch = pitch + norm.YAxis * timeStep; roll = roll + norm.XAxis * timeStep; yaw = yaw + norm.ZAxis * timeStep; // Print values Serial.print(" Pitch = "); Serial.print(pitch); Serial.print(" Roll = "); Serial.print(roll); Serial.print(" Yaw = "); Serial.print(yaw); Serial.print(" Temp = "); Serial.print(temp); Serial.println(" *C"); delay((timeStep*1000) - (millis() - timer)); //makes sure we read only at a an interval of 0.01 secounds if ((millis()-timer2) > 200) send_BT(); } void send_BT() { int t; int x; int y; if (roll>-100 && roll<100) x = map (roll, -100, 100, 0, 100); if (pitch>-100 && pitch<100) y = map (pitch, -100, 100, 100, 200); if (temp>0 && temp<50) t = 200 + int(temp); BT.write(x); BT.write(y); BT.write(t); timer2 = millis(); } Apr 03, 2018 It is really useful for my project thank you Feb 24, 2019 Hello I'm Norbert It is a great project I trid to make it, but i have got a problem I built it, and on the serial monitor everything is fine. I connected to my mobile, the app is connected, but nothing happens, What do i wrong? looking forward to your message. Norbert. (Sorry for my bad english) Feb 25, 2019 Make sure the bluetooth module is working. You can use other bluetooth terminal apps like BT terminlal to check if you are getting any data from the arduino Feb 27, 2019 Ok ,thanks. That was the problem. Th bt module is connevted, but not do anything. I do a reset (factory default) and than its work. Thanks Sep 08, 2019 Hello, I'm a student from Korea and this post has helped me a lot. You are a real gem in the internet-arduino world. I was wondering, can you tell me how to compile the source files of the apk to apk again? I want to modify some images and test it on my smartphone.
https://circuitdigest.com/microcontroller-projects/arduino-inclinometer-using-mpu6050
CC-MAIN-2020-34
refinedweb
1,915
62.58
Drag a Node from a BeanTreeView onto a Node By Geertjan-Oracle on Mar 16, 2009 When you hold down the Ctrl key and drag a Node from the list of boy names, you can drop it onto a name in the list of girl names, which will cause the boy name to be added to the list of girl names: Do the following: - Take the steps outlined in yesterday's blog entry. That's the starting point for the steps that follow. - In the NodeChildFactory, which defines the list of boy names (shown yesterday), remove the drag() override. Yesterday, we were dragging Customer objects. Today, we want to be dragging the Node instead, which is the default behavior of the drag() method. We want to drag the Node instead of the Customer, because later we will be using org.openide.nodes.NodeTransfer to retrieve a Node from the Transferable. - Next, open the second TopComponent. Yesterday it contained a JLabel, with a text that changed on the drop of the Customer onto the TopComponent. Today, remove the JLabel and replace it with a BeanTreeView, which means you need to implement ExplorerManager.Provider. Also remove the DropTargetListener, because we will be using the BeanTreeView's own DropTargetListener, which delegates to the Node. Create the Node like this in the constructor: em.setRootContext(new AbstractNode(Children.create(new DummyChildFactory(), true))); Then define the children of the Node as follows, taking special note of the section in bold below: import java.awt.datatransfer.Transferable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openide.nodes.AbstractNode; import org.openide.nodes.ChildFactory; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.NodeTransfer; import org.openide.util.datatransfer.PasteType; class DummyChildFactory extends ChildFactory<String> { ArrayList<String> names = new ArrayList<String>(); public DummyChildFactory() { names.add( "Jane"); names.add( "Judy"); names.add( "Paula"); } @Override protected boolean createKeys(List<String> list) { for (String name : names) { list.add(name); } return true; } @Override protected Node createNodeForKey(String name) { Node node = new AbstractNode(Children.LEAF){ @Override public PasteType getDropType(Transferable t, int arg1, int arg2) { final Node node = NodeTransfer.node(t, arg1); return new PasteType() { @Override public Transferable paste() throws IOException { names.add(node.getDisplayName()); refresh(true); return null; } }; } }; node.setDisplayName(name); return node; } } Optionally, instead of the Node, you can drop a Customer object instead, assuming you've overridden the drag() as explained yesterday (take note of the two lines in bold below, which are the only ones different to the dropping of the Node described above): @Override public PasteType getDropType(Transferable t, int arg1, int arg2) { try { final Customer c = (Customer) t.getTransferData(Customer.DATA_FLAVOR); //final Node node = NodeTransfer.node(t, arg1); return new PasteType() { @Override public Transferable paste() throws IOException { names.add(c.getName()); refresh(true); return null; } }; } catch (UnsupportedFlavorException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } Make sure to drop onto a girl name, not between them, because in between the Nodes is handled by the root Node, which is the AbstractNode defined in the TopComponent, in this case. So, to support the in between bits, you'd have to also add drop functionality to a custom root Node. I.e., create a new Node that extends AbstractNode and then use that Node as the root of your children. Thanks to Stan Aubrecht for helping with this scenario. I've just noticed that you finally switched to GTK LAF on Ubuntu. If you like the Default Ubuntu Human theme, but also would like NetBeans to look even cooler, then select: System -> Preferences -> Appearance -> Theme -> Human-Clearlooks Posted by Laszlo Kishalmi on March 16, 2009 at 09:17 PM PDT # Honestly, I prefer Metal. I've never understood what's so wrong with it. I only don't use it when I can't be bothered to set the requisite switch in the IDE that enables it. Posted by Geertjan Wielenga on March 16, 2009 at 09:20 PM PDT # I have implemented pretty much what you have suggested. I am using a BeanTree View and wanting to just support the moving and copying of nodes within the Tree itself. What I am doing differently is that the data each node contains is actually part of a separate collection so I have to maintain that myself in the paste mehtod. I notice that when getDropType is called that the action value is a large number whenever a move is performed and the correct value when a copy is performed. Second, when a move is performed the icon doesn't change to show that it is allowed to be dropped but always remains as not allowed. I have gone over and over your tutorials and I can't see that you are doing anything that would enable or disable support for moving so I would assume yours just works so what could I be doing wrong? Thanks in advance. Posted by Blaine on March 23, 2009 at 04:32 AM PDT # Posted by Dave Rigsby's Blog on August 26, 2009 at 02:17 PM PDT # Posted by Dave Rigsby's Blog on August 26, 2009 at 02:19 PM PDT # Posted by Dave Rigsby's Blog on August 26, 2009 at 02:20 PM PDT # Posted by Dave Rigsby's Blog on August 26, 2009 at 02:24 PM PDT # Posted by Dave Rigsby's Blog on August 26, 2009 at 02:26 PM PDT # Posted by Dave Rigsby's Blog-o-Code on August 26, 2009 at 02:32 PM PDT # Posted by Dave Rigsby's Blog-o-Code on August 26, 2009 at 02:33 PM PDT # Dear geertjan, I searched the whole internet and the netbeans communities to find a way to be able to drag some nodes from palette to explorer's views such IconView or ListView. There is no solution out there. After spending hours on this issue i finally succeeded on that. I wanted you to know that i would be happy to give my solution to you so it will be published as a tutorial on your site. ( I think there are so many people with this problem) Regards Sam Sepassi Posted by guest on October 24, 2011 at 08:17 AM PDT # Here's where you can publish it:. Let me know if you need help (and write to me at geertjan dot wielenga at oracle dot com). Posted by Geertjan on October 24, 2011 at 10:00 AM PDT #
https://blogs.oracle.com/geertjan/entry/drag_a_node_from_a1
CC-MAIN-2016-07
refinedweb
1,085
62.58
Announcing Minderbinder v0.2.0> <groupId>fogus</groupId> <artifactId>minderbinder</artifactId> <version>0.2.0</version> </dependency> Examples Minderbinder includes unit conversions for the following units of measure: - Time: via #unit/time, base is :milliseconds, ns is minderbinder.time - Length: via #unit/length, base is :meters, ns is minderbinder.length - Information: via #unit/info, base is :byte, ns is minderbinder.information Using Minderbinder’s unit reader form (ns minderbinder.test.core (:require minderbinder.time)) (== #unit/time [1 :second] #unit/time [1000 :ms]) ;;=> true (== #unit/time [1 :minute 30 :seconds] #unit/time [90 :seconds]) ;;=> true Using Minderbinder’s unit parse functions (ns minderbinder.test.core (:require [minderbinder.length :as mbr])) (mbr/parse-length-unit [1 :km]) ;;=> 1000 (mbr/parse-length-unit [1 :ramsden-link]) ;;=> 381/1250 Defining custom conversion rules Defining a unit conversion is accomplished via Minderbinder’s defunits-of macro. The body of the macro expects the following structure: (defunits-of unit-name base-unit-tag docstring conversion-spec) The conversion spec part of the body currently allows pairs of mappings defined in reletive terms. The pairs always start with a keyword used as the unit tag. However, the right-hand side of the pair can be one of the following: - Number – defines the value of the unit relative to the base unit - Vector – defines the value of the unit relative to another contained unit - Keyword – defines a single alias for a unit - Set – defined one or more aliases for a unit A simplified version of Minderbinder’s length conversion definition serves as an example: (defunits-of length :meter "The meter is the length of the path traveled by light in vacuum during a time interval of 1/299,792,458 of a second." :m :meter ;; an alias for the base unit :km 1000 ;; a larger value relative to the base unit :km #{kilometer kilometers} ;; multiple aliases for a unit :cm 1/100 ;; a smaller value relative to the base :mm [1/10 :cm]) ;; a value relative to another unit Generated vars The defunits-of macro will define three things in the namespace where the defunits-of macro appears: parse-XXX-unit– a function that parses the unit vector according to the conversion spec, returning the total value relative to the base. unit-of-XXX– a macro that allows the for (unit-of-XXX 1 :foo)that returns the total value relative to the base. XXX-table– a map describing the unit conversion rules. Plans - ClojureScript integration - More conversions included by default - Base unit changing - Cross-unit conversions via function results - More plans not yet thought up. :F 3 Comments, Comment or Ping Colin Jones Awesome name :) Oct 16th, 2012 Jon Millett How does this compare to frinj? Oct 16th, 2012 Scott Nice use of the reader. I was sad though to see you hadn’t implemented temperature. Temperature unit conversions is an elegant demonstration of some of the benefits of Lisp syntax and zippers. The code’s old and ugly but here’s the basic idea: Oct 17th, 2012 Reply to “Announcing Minderbinder v0.2.0”
http://blog.fogus.me/2012/10/16/announcing-minderbinder-v0-2-0/
CC-MAIN-2019-35
refinedweb
508
51.18
candlestick plot from pandas dataframe, replace index by dates python interactive candlestick chart candlestick chart python plotly dash candlestick chart python python candlestick patterns how to make a stock chart in python candlestick chart creator mpl_finance This code gives plot of candlesticks with moving averages but the x-axis is in index, I need the x-axis in dates. What changes are required? import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_finance import candlestick2_ohlc #date format in data-> dd-mm-yyyy nif = pd.read_csv('data.csv') #nif['Date'] = pd.to_datetime(nif['Date'], format='%d-%m-%Y', utc=True) mavg = nif['Close'].ewm(span=50).mean() mavg1 = nif['Close'].ewm(span=13).mean() fg, ax1 = plt.subplots() cl = candlestick2_ohlc(ax=ax1,opens=nif['Open'],highs=nif['High'],lows=nif['Low'],closes=nif['Close'],width=0.4, colorup='#77d879', colordown='#db3f3f') mavg.plot(ax=ax1,label='50_ema') mavg1.plot(color='k',ax=ax1, label='13_ema') plt.legend(loc=4) plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0) plt.show() Output: I also had a lot of "fun" with this in the past... Here is one way of doing it using mdates: import pandas as pd import pandas_datareader.data as web import datetime as dt import matplotlib.pyplot as plt from matplotlib.finance import candlestick_ohlc import matplotlib.dates as mdates ticker = 'MCD' start = dt.date(2014, 1, 1) #Gathering the data data = web.DataReader(ticker, 'yahoo', start) #Calc moving average data['MA10'] = data['Adj Close'].rolling(window=10).mean() data['MA60'] = data['Adj Close'].rolling(window=60).mean() data.reset_index(inplace=True) data['Date']=mdates.date2num(data['Date'].astype(dt.date)) #Plot candlestick chart fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = fig.add_subplot(111) ax3 = fig.add_subplot(111) ax1.xaxis_date() ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y')) ax2.plot(data.Date, data['MA10'], label='MA_10') ax3.plot(data.Date, data['MA60'], label='MA_60') plt.ylabel("Price") plt.title(ticker) ax1.grid(True) plt.legend(loc='best') plt.xticks(rotation=45) candlestick_ohlc(ax1, data.values, width=0.6, colorup='g', colordown='r') plt.show() Output: Hope this helps. Plot Candlestick Charts in Python, In this tutorial we are going to learn how to plot these with Python. four relevant columns in the right order and replacing our current data frame. So what we do is, we drop the index and map the date2num function onto our Date column. I didn't notice I was using the wrong function (candlestick_ohlc instead of candlestick2_ohlc), which explained why I didn't manage to make work the documentation I looked about my issue. I tried to do the same as I found here: Overlapping Dates in Candlestick Plot from a Pandas DataFrame Clunky workaround here, derived from other post (if i can find again, will reference). Using a pandas df, plot by index and then reference xaxis tick labels to date strings for display. Am new to python / matplotlib, and this this solution is not so flexible, but it works basically. Also using a pd index for plotting removes the blank 'weekend' daily spaces on market price data. Matplotlib xaxis index as dates import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_finance import candlestick2_ohlc from mpl_finance import candlestick_ohlc %matplotlib notebook # for Jupyter # Format m/d/Y,Open,High,Low,Close,Adj Close,Volume # csv data does not include NaN, or 'weekend' lines, # only dates from which prices are recorded DJIA = pd.read_csv('yourFILE.csv') #Format m/d/Y,Open,High, Low,Close,Adj Close,Volume print(DJIA.head()) fg, ax1 = plt.subplots() cl =candlestick2_ohlc(ax=ax1,opens=DJIA['Open'], highs=DJIA['High'],lows=DJIA['Low'], closes=DJIA['Close'],width=0.4, colorup='#77d879', colordown='#db3f3f') ax1.set_xticks(np.arange(len(DJIA))) ax1.set_xticklabels(DJIA['Date'], fontsize=6, rotation=-90) plt.show() ENH: Add ohlc / candlestick plotting option for DataFrame · Issue , Mixing ordinal and datetime index plots on the same axes wouldn't work. The module itself is If we were to change the plot functions to lookup kind Candlestick plot, Pandas and Seaborn mwaskom/seaborn#387. Closed. I would like create a daily candlestick plot from data i downloaded from yahoo using pandas. Plotting candlestick data from a dataframe in Python and plots it Simple df: Using plotly: import plotly.figure_factory fig = plotly.figure_factory.create_candlestick(df.open, df.high, df.low, df.close, dates=df.ts) fig.show() will automatically parse the ts column to be displayed correctly on x. Pandas dataframe candlestick, The . plotting import figure, show, output_file df = pd. dates. Must have the same index as df. technicals: A list of additional data series to Replace method in Firstly, we have made the necessary imports, we will be using matplotlib.pyplot() to plot the chart, candlestick_ohlc() from mpl_finance to plot the Matplotlib Candlestick chart, Pandas to extract datetime-CSV data using read_csv() method, matplotlib.dates for formatting the datetime data in Matplotlib. We are using the style ‘ggplot’. How to plot simple and Candlestick chart using Python, Simple timeseries plot and candlestick are basic graphs used by technical analyst for identifying the trend. Simple time Series Chart using Python – pandas matplotlib. Here is the Converting date to pandas datetime format. df['Date'] ax.plot(ohlc.index, df['SMA100'], color = 'blue', label = 'SMA100'). I have a pandas DataFrame that looks like this training.head() The DataFrame has been sorted by date. I'd like to make a scatterplot where the date of the campaign is on the x axis and the rate of success is on the y axis. I was able to get a line graph by using training.plot(x='date',y='rate'). Plot Candlestick Charts in Research, It makes a candlestick chart from the dataframe returned by get_pricing. I wrote this to use in my research notebooks and it has made me Replace values given in to_replace with value. Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. How to find the values that will be replaced. First, if to_replace and value are both lists, they must be the same Matplotlib 2.x By Example, FacetGrid, factor plot, and pair plot may take up a lot of space when we need to handy if you want the maximize space efficiency--Heatmaps and Candlestick plots. function expects a 2D list, 2D Numpy array, or pandas DataFrame as input. names as columns, date as index, and the change in closing price as values. pandas.DataFrame.set_index¶ DataFrame.set_index (self, keys, drop=True, append=False, inplace=False, verify_integrity=False) [source] ¶ Set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it. - if my reply below helped you achieve what you needed, would appreciate if you accepted my answer..
http://thetopsites.net/article/50559200.shtml
CC-MAIN-2020-45
refinedweb
1,172
51.14
Although powerful, these resource definitions can become unwieldy. Puppet has ways around this too. Create a directory under manifests called services, and create a file in this directory called ntpclient.pp with the following contents: class ntpclient { package { ntp: ensure => installed } file { "ntp.conf": mode => 644, owner => root, group => root, path => "/etc/ntp.conf", source => "puppet://puppet.example.com/files/etc/ntp.conf", } service { ntpd: ensure => true, enable => true, subscribe => [ File["ntp.conf"], Package [ntp] ], } } This new file contains the three resources you created earlier, surrounded by a class definition. A class groups several resources, which simplifies your configuration and promotes manifest sharing. Now, replace your site.pp with this simplified manifest: import "services/*" include ntpclient The import line reads in all the files inside the services directory. The include line evaluates the class, which means that the class will be applied to the node. This configuration has the same effect as the one before, except the NTP client functionality now has been bundled into the class. So far, the manifest has assumed that all clients get the same configuration. The easiest way to give different configurations to different clients is with a node definition. A node definition applies a series of configuration directives to a given set of nodes. Replace your site.pp as follows: import "services/*" node test2, test3 { include ntpclient } node default { } With this policy in place, only test2 and test3 will have the ntp client class applied. Any other client will be caught by the default statement, which has no resources defined. Facter is another way to differentiate hosts. Facter generates facts about a machine, such as the operating system, hostname and processor. Simply type facter to see a list of the currently known facts. Here is a subset of the facts generated on one of my test machines: architecture => i386 domain => ertw.com facterversion => 1.3.8 fqdn => test2.ertw.com hardwareisa => i686 hardwaremodel => i686 hostname => test2 id => root ipaddress => 192.168.1.143 ipaddress_eth0 => 192.168.1.143 kernel => Linux kernelrelease => 2.6.18-8.el5xen lsbdistcodename => Final lsbdistdescription => CentOS release 5 (Final) lsbdistid => CentOS lsbdistrelease => 5 macaddress => 00:16:3E:5D:22:17 macaddress_eth0 => 00:16:3E:5D:22:17 memoryfree => 159.17 MB memorysize => 256.17 MB operatingsystem => CentOS operatingsystemrelease => 2.6.18-8.el5xen processor0 => Intel(R) Pentium(R) 4 CPU 1.80GHz processorcount => 1 ps => ps -ef puppetversion => 0.24.2 Facts are exposed in the manifest as variables. The operatingsystem fact is seen as $operatingsystem. A common use of this is to make the same resource behave differently, depending on the operating system: file { "foo" name => $operatingsystem ? { solaris => "/usr/local/etc/foo.conf", default => "/etc/foo.conf" } } The above example uses a Puppet selector to set the name attribute instead of a static string. A selector is much like a case statement in that it can return different values depending on the input. This file resource refers to /usr/local/etc/foo.conf on Solaris systems and /etc/foo.conf on other systems. The system type is determined from the input to the selector, which is the $operatingsystem Facter variable. You can add your own facts by writing a Ruby script. See Resources for links to documentation for adding custom facts. My first experience with configuration management was with a product called cfengine. With cfengine, I was able to manage a Web cluster of 14 servers easily and reduce the time to install a new node from several hours to a matter of minutes. Puppet's author has a great deal of cfengine experience and built Puppet to address many shortcomings of cfengine. Given that cfengine has a much wider install base than Puppet, why would one choose Puppet? After comparing the two, I've discovered several reasons. First, Puppet has a much cleaner configuration than cfengine. In the cfengine world, you are concerned with the ordering of certain operations, whereas Puppet handles ordering with the subscribe attribute (and some others). Cfengine has many commands for adding and removing lines from files, which don't exist natively in Puppet. Puppet addresses this by providing native resource types for many of the systems that I found myself editing by hand, such as mountpoints. Using a dedicated resource type means the manifest is clear and simple. Cfengine is open source, but it has a more closed community than Puppet. You can extend cfengine through modules, much akin to Puppet's recipes and facts, but it is nowhere near as integrated. Puppet seems designed from the start to be extensible, where cfengine feels like an afterthought. Puppet also promotes recipe sharing by making them modular, where sharing cfengine code is more difficult because the resources are in different parts of the cfengine policy. Puppet is written in Ruby, and cfengine is written in C. Initially, I thought this was an advantage for cfengine, but after getting into Puppet, I realized it's not a big deal. Puppet's author takes great pains to abstract Puppet's configuration from the Ruby language, so no knowledge of Ruby is needed. I found the learning curve for cfengine to be the steepest. Granted, I had no understanding of configuration management when starting with cfengine, and I had some cfengine experience by the time I started with Puppet, but many of my stumbling blocks have been fixed in Puppet. Both projects offer support over their IRC channels. Cfengine has an extensive on-line manual and a fair bit of third-party documentation on other Web sites. Puppet has an excellent wiki and a comparable amount of third-party documentation. Although Puppet is younger compared to cfengine, its openness and extensibility are what make it a better choice than cfengine.
http://www.linuxjournal.com/magazine/automate-system-administration-tasks-puppet?page=0,2&quicktabs_1=1
CC-MAIN-2013-48
refinedweb
953
58.38
cin >> iwhere i is of type int and cin encounters non-numbers in the input stream it does not extract that input from the stream. After all, you're asking for an int, not anything else. What it does do is go into an error state. using namespace std;you are adding in a whole bunch of things you mainly never will use in your program. So generally people will do this, they will use using std::cout;when they intend to use cout frequently, and for other things they will only use once in a while they will do std::endl;.
http://www.cplusplus.com/forum/beginner/93769/
CC-MAIN-2014-42
refinedweb
102
77.37
On 23/09/2009, at 7:57 PM, Martin Sudmann wrote: > > 2009-09-23 11:49:11,014 [http-9090-2] WARN > org.apache.struts2.components.Form - No configuration found for the > specified action: 'none' in namespace: ''. Form action defaulting to > 'action' attribute's literal value. This could be a bug in the page that you should report, but I don't think it's the cause of the problem > I also get a lot of SCM warnings (don't know if this is related > though): > > 2009-09-23 11:40:53,695 [Thread-30] WARN > org.apache.continuum.scm.manager.Slf4jScmLogger - Could not figure > out of: > tags: V37_0_0 The SCM problem seems the one relevant to your builds getting stuck. This is coming from the bazaar SCM provider that it doesn't understand the output line "tags: V37_0_0". It shouldn't block it though, so I'm not sure. Do the logs state what bzr command is being run? - Brett
http://mail-archives.apache.org/mod_mbox/continuum-users/200909.mbox/%3CB4854497-1880-4172-97A6-D23D4C577091@apache.org%3E
CC-MAIN-2015-22
refinedweb
161
72.05
Sudoku quietly appeared on the scene in the United States in the last couple of years, and then became a phenomenon, just as it had in Japan, where it originated. It's a simple game, similar to crossword puzzles in that it uses a grid, but different because it uses numbers, and requires no external clues. The idea is that you have a grid with several numbers supplied, such as shown in Figure 1. Figure 1. A sample Sudoku game The idea is to fill the board so that every row, column, and 3 x 3 box (as delimited by the lines in this figure) has each of the digits from one to nine exactly once, as shown in Figure 2. Figure 2. A solved Sudoku puzzle There are many ways to accomplish this, most of which are beyond the scope of this article, but the basic idea is to use process of elimination to decide where each of the numbers goes. (See the Resources section for some good sources of information.) But as all of the ads will tell you, there is no math required. In this article, we are going to build a basic grid that displays a game and enables you to input your answers using select lists. Using XPath, you can determine whether or not the puzzle has been solved. In part two, you will enhance the game with loading and saving abilities, and perhaps tweak the interface a little bit. To start with, you are going to need some data. The way to do this is to create a "grid" within the data itself. In other words, one "row" of data -- the contents of the r(ow) element -- maps to one row of the game board. Each number lives in its own box, with nine of them making up a row. Nine rows make up the game. The resulting structure looks something like Figure 3. Figure 3. The data structure Notice that you have the rows and columns closely approximating what they would look like on the board. In this case, the zero entries correspond to empty boxes the user will have to fill in. Because of the way XForms works, when the user fills in a box on the form, that data gets added to this XML document. You can then check the structure of the document using carefully constructed XPath statements to determine whether or or not the puzzle has been solved. Let's start by creating a basic page. The basic page needs to have several elements. These include the structure of the actual page, including namespaces and so on, as well as the XForms model (see Listing 1). Listing 1. The basic page Several namespaces that you'll be using later just to make things a little simpler have been left in. Also notice that the data has been created in its own instance, changing the XML structure to be a little more human readable. (The names are, of course, completely arbitrary.) A small graphic has also been included to remind the user of what they're trying to accomplish. What you're left with is a simple page (see Figure 4). Figure 4. The empty page Now let's look at adding some controls to that page. In order to create the game board, you will need nine rows of drop-down lists, each of which contains the numbers one through nine and a blank space representing zero. Fortunately, this is not difficult to achieve. The easiest way is to create a second instance that provides a template (see Listing 2). Listing 2. Using the template Despite its visual appearance, the template actually represents a single row, with each "box" having a value to be inserted into the main game instance and a separate display value. For each row in the game, you loop through each box in the row. For each box in a row, you create a select list by displaying each of the entries in the template. By manipulating cascading style sheets just a little bit (setting the contents of the div to be displayed inline, rather than each to its own line) you can get the basic game board (see Figure 5). Figure 5. The basic game board Now you need to set each of these lists to start with the supplied value, if there is one. Setting the original numbers Because of the way these lists have been structured, setting an initial value is pretty straightforward (see Listing 3). Listing 3. Setting the initial values The form displays a select list for each box element, so all you need to do is have the list reference the current box element. You can see the results in Figure 6. Figure 6. Setting initial values Notice, however, that there's nothing to stop you from simply changing the original values if they are inconvenient. This, of course, defeats the whole purpose of the game. Making the original numbers read only In order to stop the user from simply changing the original values, you will make the supplied values "read-only." Now, it may seem that the easiest way to do that would be to simply tell the form not to let the user change any value that is not "0," but remember that once the user starts playing the game, he or she will be changing those zeroes into other values, and it's not a good idea for you to stop them from changing values that they themselves have selected. To solve this problem, we will need to add a little bit of data to the instance (see Listing 4). Listing 4. Adding information to the instance Adding attributes to your original values gives you the opportunity to use a binding condition to specify that these values should be read only. In other words, the user will not be able to change the value of these select lists. In an ideal world, you would be able to use "pseudo classes" to set a style for these values so users can easily see which numbers they themselves have chosen and which were originally supplied. I've added that code into the page, but unfortunately, it is not yet supported by Firefox. If you reload the page, you will see that while you can change the blank values, you cannot change the original values. All right, now that you've got the board, how do you know how you're doing? You can start the scoring with the easiest topic, finding rows that have been solved. In order to determine whether a row has been solved, you simply need to determine whether it contains an instance of all nine digits. Because there are only nine spots, this will also ensure that there are no duplicates. You can do this with a simple XPath statement. To start with, if you wanted to find at how many rows were in the game, you could use the XPath statement: count(/s:game/s:row). This should give you the value of 9. However, you don't want all of the rows, you only want all of the rows that satisfy certain condition. For example, you can select only the rows that include a box with a value of 1: count(/s:game/s:row[s:box = '1']). Of those rows, you only want the ones that also have a box with a value of 2: count(/s:game/s:row[s:box = '1'][s:box = '2']). And so on for each of the nine digits. You can put it all together to check for all nine values to let you know where you stand (see Listing 5). Listing 5. Checking for correct rows By adding an element to the instance, you can easily see where you stand, because every time the value gets updated in the instance, it will be updated on the page. You can see this in Figure 7. Figure 7. Looking for correct rows The second row has exactly one instance of each digit, so you can see the value of 1 for correctRows. Creating an XPath expression to check for correct columns is a little more complicated. Rather than looking for a single row that satisfies multiple conditions, where looking for a single column that includes a row with each digit. For example, you can count the root element only if it includes a row that includes the digit 1 in the first column: count(/s:game[s:row[s:box[1]='1']]) In other words, it is counting the game element if and only if it has a row that satisfies the condition of having a box element in position 1 with a value of "1." It doesn't matter which row it is, as long as the 1 is in that first position. Similarly, you can count the game element only if it also has the numeral 2 in the first position: count(/s:game[s:row[s:box[1]='1']][s:row[s:box[1]='2']]) And so on and so forth. Unfortunately, this statement only checks for the correctness of column 1, which means you're going to need a new count() function for each column, but that's not too bad (see Listing 6). Listing 6. Looking for correct columns Now if you refresh the page, you'll see that the "correct rows" value updates when you complete a column, such as the third column in Figure 8. Figure 8. Correcting a row At this point, when you have solved all of the columns and rows, you should see a "correct rows" value of 18 (nine rows and nine columns). But you're not done yet. That wasn't too bad, but you do have one more step. Remember, in addition to the rows and columns, the user can only use the digits once in each of the 3 x 3 boxes shown in Figure 1. Unfortunately, there is no simple XPath statement that will enable you to easily determine whether or not all of the digits are present, because any statement you construct will have to specify specific boxes and specific digits. Fortunately,there is an option. What you can do is map each square to a row of data that you create explicitly for this purpose. For example, consider the XML element shown in Listing 7. Listing 7. Box element With nine box elements, it pretty much corresponds to a row. Try mapping the boxes with the following coordinates (see Listing 8). Listing 8. Coordinates for boxes You can see that the data fits, and you can use a simple XPath statement to determine how many squares are correct (see Listing 9). Listing 9. XPath statement to determine how many squares are correct Note that this is almost identical to the statement used to determine the original rows. The next thing you'll need to do is add all of this information to the existing game (see Listing 10). Listing 10. Adding the mapping instance to the game Of course, just adding the instance doesn't really do anything, which you can prove to yourself by completing a square and noticing that the "correct rows" value does not change. To make it work, you will have to complete the mapping. Various ways to set one element equal to the value of another element are built into XForms, but in this case, you are going to take direct control of the process. You are going to create a button that explicitly sets individual values when the user clicks it (see Listing 11). Listing 11. Setting values Now when the user clicks the Check it! button, all of these values will be set, which will trigger the "correct rows" calculation to be updated. You can see this when you reload the page and once more complete a square. The "correct rows" value will not change until you click the button, as seen in Figures 9 (before) and 10 (after). Figure 9. Before clicking the button Figure 10 shows the "correct rows" value after clicking the button. Figure 10. After clicking the button So now, with the addition of nine squares to be completed, the number of "correct rows" before the game is complete must be 27. Adding the submission button Finally, you need to add the submission button. Because you want this button to appear only one when the game is ready to submit, you need to set its relevance (see Listing 12). Listing 12. Setting the submit button's relevance Starting at the bottom, the submit button has been added and a new element referenced, the submitButtonElement element. A binding statement has also been added so that element does not appear unless the correctRows element is equal to 27. To test this, a "correct" data set has been temporarily added. When you first load the page, you see that all of the rows and columns are complete (see Figure 11). Figure 11. Loading the correct data Once you click the Check it! button, however, the correctRows value gets updated to 27, and the submit button appears, as you can see in Figure 12. Figure 12. The submit button appears At the moment, you don't have anywhere to submit the data to, but that will change in part 2. Because Sudoku is based on very specific data patterns, you can use XPath expressions to evaluate the progress the user has made in a specific game. You can also use these patterns to easily generate a game board that enables the user to play. In Part 1, you created the form and the mechanism of play; in Part 2, you will look at the data end, loading and saving games and performing other enhancements. Information about download methods Learn - Sudoku.com offers tips for beginners just learning how to play the game, while Michael Mepham, who provides puzzles for the Daily Telegraph and the Los Angeles Times provides analysis for solving more challenging puzzles. If you just want to get your feet wet and solve a few more while you're waiting for Part 2, WebSudoku has puzzles of various difficulties you can play online. - Get a basic introduction to XForms in Introduction to XForms, Part 1: The new Web standard for forms (developerWorks, September 2006). - Learn more about XForms in the IBM developerWorks XML zone. - all about XML at the developerWorks XML zone. - Hear the author discuss his obsession with Sudoku in this developerWorks podcast. Get products and technologies - Python Sudoku both generates and solves Sudoku puzzles. We'll be using this engine in Part 2 to generate new puzzles. - The XForms Recommendation is maintained by the W3C. - For more information on XPath, check out the XPath Recommendation. - Get MozzIE, an open-source control that allows you to render XForms in Internet Explorer. Discuss - Participate in the discussion forum. - developerWorks blogs:).
http://www.ibm.com/developerworks/xml/library/x-xformssudoku1/
crawl-002
refinedweb
2,490
67.89
Key Takeaways - Java 10 introduces a shiny new feature: type inference for local variables. For local variables, you can now use a special reserved type name “var” instead of actual type. -, such as when initialising Arrays and Streams. - Experiment with this hands-on tutorial on how to reduce the boilerplate code using new “var” type. In this article I am going to introduce, by example, the new Java SE 10 feature “var” type. You will learn how to use it properly in your code, and also when you can’t use it. Introduction Java 10 introduces a shiny new feature: type inference for local variables. For local variables, you can now use a special reserved type name “var” instead of actual type, as demonstrated by the following: var name = “Mohamed Taman”;. I am going to mention this after a while, just keep reading. Let’s go through some quick examples now. Hey, wait, wait and wait! Before jumping into the code, you will need to use an IDE to try out the new features as usual. The good news is that there are many in the market, so you can choose your favorite IDE that supports Java SE 10 among many IDEs like Apache NetBeans 9, IntelliJ IDEA 2018, or new Eclipse. Personally, I always prefer to use an interactive programming environment tool, to quickly learn Java language syntax, explore new Java APIs and its features, and even for prototyping complex code. This is instead of the tedious cycle of editing, compiling and executing code which typically involves the following process: - Write a complete program. - Compile it and fix any errors. - Run the program. - Figure out what is wrong with it. - Edit it. - Repeat the process. The great news again is that you are going to use the JShell tool that is built-in and shipped with Java SE JDK since Java SE 9, which was a flagship feature of that release. What is JShell Now Java has a rich REPL (Read-Evaluate-Print-Loop) implementation with JShell tool, referred as an Java Shell as an interactive programming environment. So, what’s the magic? It’s simple. JShell provides a fast and friendly environment that enables you to quickly explore, discover and experiment with Java language features and its extensive libraries. Using JShell, you can enter program elements one at a time, immediately see the result, and make adjustments as needed. Therefore JShell replaces the tedious cycle of editing, compiling and executing with its read-evaluate-print loop. Rather than complete programs, In JShell you write JShell commands and Java code snippets. When you enter a snippet, JShell immediately reads, evaluates, and prints its results. Then it loops to perform this process again for the next snippet. So, JShell and its instant feedback keeps your attention, enhances your performance and speeds up the learning and software development processes. That is enough introduction for JShell, and InfoQ have recently published a thorough introduction to the tool. To deep dive and learn more about all JShell features, I have recorded an entire video training about this topic titles “Hands-on Java 10 Programming with JShell [Video]” that should help you to master the topic, and can be reached either from Packt or Udemy. So now, let’s go through some quick examples to understand what can be done with this new var type feature using JShell. Required Software To work probably with JShell, I am assuming that you have Java SE or JDK 10+ installed and tools in JDK bin folder is configured to be accessible from anywhere in your system, if not here is the link to install the JDK 10+ latest release. Starting a JShell Session To start a JShell session in: - Microsoft Windows open a Command Prompt then type jshell and press Enter. - On Linux, open a shell window then type jshell and press Enter. - While on macOS (formerly OS X), open a Terminal window, then type the following command “jshell” and press Enter. Taraaa! This command executes a new JShell session, and displays this message at the jshell> prompt: | Welcome to JShell -- Version 10.0.1 | For an introduction type: /help intro jshell> Working with “var” type. Now you have JDK 10 installed, let’s start playing with JShell, so let’s jump right ahead to the terminal to start hacking var type feature capabilities with examples. Just enter each of upcoming snippets I am introducing next at the jshell prompt, and I will leave the result for you to explore as an exercise. If you had a sneaky look ahead at the code, you will notice that it looks wrong, as there is no semicolons. Try it and see if it works or not. Simple type inference case This is the basic usage of var type, in the following example, the compiler can infer the RHS as a String literal: var name = "Mohamed Taman" var lastName = str.substring(8) System.out.println("Value: "+lastName +" ,and type is: "+ lastName.getClass().getTypeName()) No semicolon is required because JShell is an interactive environment. A semicolon is only required when there are multiple statements on the same line, or statements inside a declared type or method, and you will see this the following examples. var type and inheritance Also, polymorphism still works. In the world of inheritance, a subtype of var type can be assigned to super type of var type as normal cases as the following: import javax.swing.* var password = new JPasswordField("Password text") String.valueOf(password.getPassword()) // To convert password char array to string to see the value var textField = new JTextField("Hello text") textField = password textField.getText() But a super type var cannot be assigned to subtype var as the following: password = textField This is because JPasswordField is a subclass of JTextField class. var and compile time safety So now, what about wrong assignment?It is an easy answer; incompatible variable types cannot be assigned to each other. Once compiler has inferred actual type of var, you cannot assign wrong value as the following: var number = 10 number = "InfoQ" So, what happens here? the compiler here has just replaced “var number = 10” with “int number = 10” for further checking, safety is still maintained. var with Collections & Generics Okay let’s see how var works with Collection element type inference and Generics. Let’s start first with collections. In the following case, the compiler can infer what the type of collection elements is: var list = List.of(10); There is no need to cast here, as compiler has inferred correct element type int int i = list.get(0); //equivalent to: var i = list.get(0); In following case the situation is different, the compiler will just take it as collection of objects (not integers) that's because when you use the diamond operator, Java already needs a type on the LHS (Left Hand Side) to infer type on the RHS, let’s see how; var list2 = new ArrayList<>(); list2.add(10); list2 int i = list2.get(0) //Compilation error int i = (int) list2.get(0) //need to cast to get int back In the case of generics, you better need to use a specific type (instead of diamond operator) on the RHS as the following: var list3 = new ArrayList<Integer>(); list3.add(10); System.out.println(list3) int i = list3.get(0) Let’s jump right to see how var type works inside the different kind of loops: var type inside for loops Let’s check first the index based normal For Loop for (var x = 1; x <= 5; x++) { var m = x * 2; //equivalent to: int m = x * 2; System.out.println(m); } And here is how it used with For Each Loop var list = Arrays.asList(1,2,3,4,5,6,7,8,9,10) for (var item : list) { var m = item + 2; System.out.println(m); } So now I have a question here, does var works with a Java 8 Stream? Let’s see with the following example; var list = List.of(1, 2, 3, 4, 5, 6, 7) var stream = list.stream() stream.filter(x -> x % 2 == 0).forEach(System.out::println) var type with Ternary operator What about the Ternary operator? var x = 1 > 0 ? 10 : -10 int i = x Now, what if you use different types of operands on RHS of the ternary operator? Let's see: var x = 1 > 0 ? 10 : "Less than zero"; System.out.println(x.getClass()) //Integer var x = 1 < 0 ? 10 : "Less than zero"; System.out.println(x.getClass()) // String Do those two examples show that the type of the var is decided during runtime?Absolutely not! Let's do the same thing in the old way: Serializable x = 1 < 0 ? 10 : "Less than zero"; System.out.println(x.getClass()) Serializable, It's a common compatible and the most specialized type for the two different operands (the least specialized type would be java.lang.Object). Both String and Integer implement Serializable. Integer auto-boxed from int. In other words, Serializable is the LUB(Least Upper Bound) of the two operands. So, this suggests that in our third last example, var type is also Serializable. Let’s move onto another topic: passing var type to methods. var type with methods Let’s first declare a method called squareOf with one argument of type BigDecimal, which return the square of this argument as the following: BigDecimal squareOf(BigDecimal number) { var result= number.multiply(number); return result; } var number = new BigDecimal("2.5") number = squareOf(number) Now let’s see how it works with generics; again let’s declare a method called toIntgerList with one argument of type List of type T(a generic type), which returns an integer-based list of this argument using the Streams API as the following: <T extends Number> List<Integer> toIntgerList(List<T> numbers) { var integers = numbers.stream() .map(Number::intValue) .collect(Collectors.toList()); return integers; } var numbers = List.of(1.1, 2.2, 3.3, 4.4, 5.5) var integers = toIntgerList(numbers) var with Anonymous Classes Finally, let’s look at using var with anonymous classes. Let’s take advantage of threading by implementing Runnable interface as the following: var message = "running..." //effectively final var runner = new Runnable(){ @Override public void run() { System.out.println(message); }} runner.run() So far I have introduced the shiny new Java 10 feature “var” type, which reduces the boilerplate coding while maintaining Java’s compile time type checking. And you went through examples shows what can be done with it. Now you will learn about the limitations of the var type, and where it is not allowed. “var” limitations Now you are going to take a look at some quick examples to understand what cannot be done with var type feature. So, let’s jump right ahead to the terminal to hack limitations with some examples. The results of jshell prompt will explain what is wrong with code, so you can take advantage of interactive instant feedback. You should initialize with a value The first, and easiest, thing is that a variable without an initializer is not allowed here; var name; You will get a compilation error; because the compiler cannot infer type for this local variable x. Compound declaration is not allowed Try to run this line; var x = 1, y = 3, z = 4 And you will get this error message, 'var' is not allowed in a compound declaration. No Definite Assignment Try to create a method called testVar as the following, just copy and paste the method into the JShell: void testVar(boolean b) { var x; if (b) { x = 1; } else { x = 2; } System.out.println(x); } It will not create the method, and will instead throw a compilation error. You cannot use 'var' on variable without an initializer. Even assignments like the following (known as Definite Assignment) do not work for var. Null Assignment Null assignment is not allowed, as shown in the following; var name = null; This will throw an Exception “variable initializer is 'null'” . Because null is not a type. Working with Lambdas Another example, with no Lambda initializer. This is just like diamond operator case, RHS already needs the type inference from LHS. var runnable = () -> {} This Exception will be thrown, “lambda expression needs an explicit target-type”. var and Method Reference No method reference initializer, similar case to lambda and diamond operator: var abs = BigDecimal::abs This Exception will be thrown: “method reference needs an explicit target-type” var and Array Initializations Not all array initializers work, let’s see how var with [] does not work: var numbers[] = new int[]{2, 4, 6} The error will be: 'var' is not allowed as an element type of an array. The following also does not work: var numbers = {2, 4, 6} The error is: “array initializer needs an explicit target-type” Just like the last example, var and [] cannot be together on LHS: var numbers[] = {2, 4, 6} error: 'var' is not allowed as an element type of an array Only the following array initialization works: var numbers = new int[]{2, 4, 6} var number = numbers[1] number = number + 3 No var Fields allowed class Clazz { private var name; } No var Method parameters allowed void doAwesomeStuffHere(var salary){} No var as Method return type var getAwesomeStuff(){ return salary; } No var in catch clause try { Files.readAllBytes(Paths.get("c:\temp\temp.txt")); } catch (var e) {} What happens behind the scene for var type at compile time? “var” really is just a syntactic sugar, and it does not introduce any new bytecode construct in the compiled code, and during runtime the JVM has no special instructions for them. Conclusion. Wrapping up the article, you have covered what the “var” type is and how this feature reduces the boilerplate coding, while maintaining Java’s compile time type checking. You then learned about the new JShell tool, Java’s REPL implementation, that help you to learn quickly Java language, and explore new Java APIs and its features. You can also prototype complex code using JShell, instead of the traditional tedious cycle of editing, compiling and executing code. Finally, you learned about all of the var type capabilities and limitations, such as where you can and can’t use it. It was fun writing this article for you, and so I hope you liked it and found it useful. If so, then please spread the word. Resources - JDK 10 Documentation - Hands-on Java 10 Programming with JShell. - Getting Started with Clean Code Java SE 9. - Overview of JDK 10 and JRE 10 Installation. - JEP 286: Local-Variable Type Inference. - Definite Assignment About the Author Mohamed Taman is Sr. Enterprise Architect / Sr. Software Engineer @WebCentric, Belgrade, Serbia | Java Champions | Oracle Developer Champions | JCP member | Author | EGJUG Leader | International Speaker. Tweeter Taman @_tamanm Community comments
https://www.infoq.com/articles/java-10-var-type/
CC-MAIN-2021-49
refinedweb
2,468
61.97
Why use Lua?! Minimal project setup Download LuaBridge from the repository You also need to download Lua. Add Lua include/ directory and LuaBridge to include directories and link lua52.lib to your project. Create script.lua with this code in it: testString = "LuaBridge works!" number = 42 Add main.cpp to your project: // main.cpp #include <LuaBridge.h> #include <iostream> extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" } using namespace luabridge; int main() { lua_State* L = luaL_newstate(); luaL_dofile(L, "script.lua"); luaL_openlibs(L); lua_pcall(L, 0, 0, 0); LuaRef s = getGlobal(L, "testString"); LuaRef n = getGlobal(L, "number"); std::string luaString = s.cast<std::string>(); int answer = n.cast<int>(); std::cout << luaString << std::endl; std::cout << "And here's our number:" << answer << std::endl; } Compile and run this program. You should see the following output LuaBridge works! And here's our number:42 Note: if your program doesn’t compile and you get something like “error C2065: ‘lua_State’ : undeclared identifier” in luahelpers.h, you need to do the following 1) Add this to the beginning of LuaHelpers.h extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" } 2) Change 460th line of Stack.h from this lua_pushstring (L, str.c_str(), str.size()); to this lua_pushlstring (L, str.c_str(), str.size()); Okay, here’s how the code works. #include <LuaBridge.h> #include <iostream> extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" } We include all important headers first. Nothing special here. using namespace luabridge; LuaBridge has its own namespace (you should probably put it only where you use luabridge, though) lua_State* L = luaL_newstate(); We create lua_State with this line. luaL_dofile(L, "script.lua"); This line opens our script. You don’t need to create new lua_State each time you open new file. You can load scripts using just one state. Then we load Lua’s libraries and call the script (you can find more explanation in the first part): luaL_openlibs(L); lua_pcall(L, 0, 0, 0); We can then create LuaRef object which can hold everything Lua variable can: int, float, bool, string, table, etc. LuaRef s = getGlobal(L, "testString"); LuaRef n = getGlobal(L, "number"); Then we can convert LuaRef to C++ string like this: std::string luaString = s.cast<std::string>(); int answer = n.cast<int>(); Error checking But some things can go wrong and you should handle errors gracefully. Let’s check some of the most important errors What if Lua script is not found? if (luaL_loadfile(L, filename.c_str()) || lua_pcall(L, 0, 0, 0)) { ... // script is not loaded } What if variable is not found? You can easily check if the variable you want to access is nil or not if (s.isNil()) { std::cout << "Variable not found!" << std::endl; } Variable is not of the type we expect to get If you want to be sure that the variable is string, for example, you can check this: if(s.isString()) { luaString = s.cast<std::string>(); } Tables Tables are not just arrays: they’re amazing structures that can hold every Lua type and even tables! Let’s write this in script.lua window = { title = "Window v.0.1", width = 400, height = 500 } And this code in C++: LuaRef t = getGlobal(L, "window"); LuaRef title = t["title"]; LuaRef w = t["width"]; LuaRef h = t["height"]; std::string titleString = title.cast<std::string>(); int width = w.cast<int>(); int height = h.cast<int>(); std::cout << titleString << std::endl; std::cout << "width = " << width << std::endl; std::cout << "height = " << height << std::endl; You should see the following output: Window v.0.1 width = 400 height = 500 As you can see we can access table elements using operator []. We can even write shorter: int width = t["width"].cast<int>(); You can also change table contents like this: t["width"] = 300 It doesn’t change the script, but if you try to get this variable again it will have another value: int width = t["width"].cast<int>(); // 400 t["width"] = 300 width = t["width"].cast<int>(); // 300 Suppose you have a table like this: window = { title = "Window v.0.1", size = { w = 400, h = 500 } } How can we get value of window.size.w? Here’s how: LuaRef t = getGlobal(L, "window"); LuaRef size = t["size"]; LuaRef w = size["w"]; int width = w.cast<int>();(This is the shortest way of doing it I’ve found. If someone knows how to do this better, shoot me an e-mail or write a comment, it will be very appreciated) You can go to the first part of my tutorial and find my implementation more convenient for getting data from tables because you can do something like this: int width = script->get<int>("window.size.w"); Functions Let’s write a simple function in C++ void printMessage(const std::string& s) { std::cout << s << std::endl; } Write this in script.lua printMessage("You can call C++ functions from Lua!") Now we need to register the function in C++: getGlobalNamespace(L). addFunction("printMessage", printMessage); Note: You must do this before loading the script using luaL_dofile. Note: C++ and Lua functions can have different names You just registered printMessage function. If you want to register it in some namespace you can do something like this: getGlobalNamespace(L). beginNamespace("game") .addFunction("printMessage", printMessage) .endNamespace(); You then need to call it from Lua like this: game.printMessage("You can call C++ functions from Lua!") Lua namespaces have nothing to do with C++ namespaces. They’re used for logical grouping and convenience mostly. Let’s now call Lua function from C++ -- script.lua sumNumbers = function(a,b) printMessage("You can still call C++ functions from Lua functions!") return a + b end // main.cpp LuaRef sumNumbers = getGlobal(L, "sumNumbers"); int result = sumNumbers(5, 4); std::cout << "Result:" << result << std::endl; You should see the following output: You can still call C++ functions from Lua functions! Result:9 Well, isn’t that cool? You don’t need to tell LuaBridge function arguments and what you expect to get returned. There are some thing to consider, though. You can’t have more that 8 arguments for one function. If you pass more arguments than function expects, LuaBridge will silently ignore them However, if something goes wrong LuaBridge will throw a LuaException. Be sure to catch and handle it! Here’s the full code of the functions example: -- script.lua printMessage("You can call C++ functions from Lua!") sumNumbers = function(a,b) printMessage("You can still call C++ functions from Lua functions!") return a + b end // main.cpp #include <LuaBridge.h> #include <iostream> extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" } using namespace luabridge; void printMessage(const std::string& s) { std::cout << s << std::endl; } int main() { lua_State* L = luaL_newstate(); luaL_openlibs(L); getGlobalNamespace(L).addFunction("printMessage", printMessage); luaL_dofile(L, "script.lua"); lua_pcall(L, 0, 0, 0); LuaRef sumNumbers = getGlobal(L, "sumNumbers"); int result = sumNumbers(5, 4); std::cout << "Result:" << result << std::endl; system("pause"); } What? There’s even more? Yes. There are some neat things which I’ll cover in next part: classes, object creation, object lifetime… That’s a lot of stuff! I also recommend you to check out my re:Creation dev logs which show how I use Lua scripts in the development. Lua makes my life as a gamedev much easier. Try it, maybe it will make yours easier too? Week #1: Things are getting bigger Follow me on twitter to get updates! @EliasDaler 46 thoughts on “Using Lua with C++. LuaBridge makes everything easier. Variables and functions” cam ơn bạn vì đã chia sẽ You’re welcome :) Very helpful, thank you. This is great! :) exactly what I was looking for. Lua makes a lot of sense now! I can’t wait to implement this myself and read on! Thanks! I am having a problem with LuaBridge, though :/ lua seems to have installed correctly. I downloaded LuaBridge from the linked source and got LuaBridge-master. I moved the contents of the LuaBridge directory (details folder; Luabridge.h … ) into my xcode includes folder and added #include to my main.cpp. Is this all I had to do? I’m getting annoying errors when I try to build your sample code. “Undefined symbols for architecture i386: “_luaL_checkinteger”, referenced from: luabridge::Stack::get(luabridge::lua_State*, int) in main.o Sorry, do you know what this means? I appreciate any help :) This is really strange. I’ve never encountered such errors in my programming experince, ha-ha. You should try other compilers. E-mail me if you have problems with them I ended up fixing this problem by changing a small setting, “Build Active Architecture Only”, to yes instead of no. (I am using XCode, if I did not mention this.) Apparently liblua.a is built as an archive and xcode ignores that type of library build when it searches for libraries to link; changing this setting allows xcode to see liblua.a and pick it up :) I think this is an xcode-specific problem. Am I able to ask you another question about your code? Ha ha I am getting a silly error. Glad to hear you fixed it. And yeah, feel free to ask Will you be continuing this tutorial? It’s extremely helpful! I’m looking forward to learning more about creating objects with components and behaviors, if you’re planning to cover it. Yes, I will. :) I’ll talk about C++ objects and classes in Lua. But I can’t really say when it’ll be done. Maybe two weeks. Maybe a month… :D Exactly what i was searching for ! You don’t know how much you helped me ! Thanks a lot ! I still have a question though, is there a way to call a C++ function that takes an array or vector (or any type of container) from Lua ? Something like this : — answer = choice(“Would you like to …”, {“Yes”, “No”}) — Because, after all a string is a sort of array, so is it possible ? If yes, how ? Thanks a lot for your help ! You’re welcome! Nice to hear that. :) Hmm, I don’t know how to do this, but I have some ideas. I’ll try it out and reply again later. Here, it works. Be sure to add some error and type checking, of course. Awesome ! So this way it’s possible to bypass the 8 arguments limit ! Thanks a lot for your help ! :) You’re welcome! Glad to help :) I am using LuaBridge for a project of mine, At first I was enthusiastic as you about LuaBridge, then after some plumbing and as my application grew mature, I see now that it has a lot of problems. The C++ inteface to Lua makes all calls without wrapping in pcall. It doesn’t matter if you don’t call functions, even a table creation can trigger an error (if a garbage collection cycle happens to be issued and a __gc metamethod fails), killing instantly your application. I don’t need this interface so I just removed it, but be warned. There are no clear semantics for references, and copy by value. It is debatable what the right approach would be to translate C++ semantics to Lua, as they are very different languages, but in in my opinion it should be arithmetic type and boolean => pass by value, rvalues (functions returning objects) => create userdata, anything else (references / pointers) => create references. There are several occasions where the vanilla LuaBridge fails: for example, functions that take references cause a copy of the object to be made (), const references to arithmetic types won’t work (), fields of structs that are non arithmetic or pointers are passed by valued and copied (). Every time a pointer of a reference is passed to Lua, a new proxy object is created, which is an unnecessary overhead. The wrapping object could be saved in the registry table with a weak reference, and reused when needed. It is not easy to implement this in a proper way (think what happens if you delete the object, then create a new object of the same type and maybe the malloc implementation returns the same piece of memory), but it would be a great performance gain. And yeah, missing array access sucks big time. Had to implement it as you did (). The way in which stuff is bound to Lua makes it very intense for the compiler, because of template instantiations. gcc takes almost 1GB of ram to compile my biggest compile unit (which is indeed quite a monster). gcc is to blame here partially, as clang performs much better, but It’s not clear to me whether there could be a way to arrange bindings in a more performing way. For sure getting rid of the boilerplate for different arity of functions with C++11 variadic templates (it’s almost 2015 now!) could simplify things and templates resolution. But you know, the library is not maintained anymore. After all, it’s been a good time with you LuaBridge. The big pros are that it’s easy and you can actually (almost) understand the code, but probably now I need to switch to something more polished. That’s some interesting things to know, thanks. Please, shoot me an e-mail if you find something better than LuaBridge. (eliasdaler@yandex.ru) Me too please. PD: great tutorial. Thanks! :) My lua works just fine, but when i include LuaBridge, i get 25 errors like: error: variable or field ‘lua_rawsetp’ declared void inline void lua_rawsetp (lua_State* L, int idx, void const* p) error: ‘lua_State’ was not declared in this scope And so on. Tried different versions of lua, still no result. What can be wrong with it? Now everything works, just included bridge after lua :\ When I include , I get luabridge\detail\userdata.h(409): error C2061: syntax error : identifier ‘lua_newuserdata’ But then if I switch to release mode, it compiles fine.. o_O Hi! It’s really hard to say what causes the problem without looking at your project, so the only thing I can advice is too look closely for differences between Debug and Release build options. :) I am too getting this error. Not sure what the problem is. Hmm… Do you use the master version of Luabridge from repository? Are you sure that you use correct Lua 5.2 for your compiler? how can i properly setup LuaBridge in VisualStudio 2013? Go to Project settings and add LuaBridge folder to your include directories. Then go to Linker->Input and add lua52.lib (get it here:) to Additional Libraries. Then change fix the line in luahelpers.h (described in the article) and you’re good to go. Console output: LuaBridge works! And here’s our number:42 Thanks a lot !! You’re welcome! You can also replace: lua_pushstring (L, str.c_str(), str.size()); with: lua_pushstring (L, str.c_str()); by simply deleting the last argument. From the LuaBridge 2.0 Reference Manual. I have myself not yet used LuaBridge, however what you are teaching leads to “undefined behavior”. Please Update. 2.7 – lua_State Sometimes it is convenient from within a bound function or member function to gain access to the `lua_State*` normally available to a `lua_CFunction`. With LuaBridge, all you need to do is add a `lua_State*` as the last parameter of your bound function: void useState (lua_State* L); getGlobalNamespace (L).addFunction (“useState”, &useState); You can still include regular arguments while receiving the state: void useStateAndArgs (int i, std::string s, lua_State* L); getGlobalNamespace (L).addFunction (“useStateAndArgs”, &useStateAndArgs); When the script calls useStateAndArgs, it passes only the integer and string parameters. LuaBridge takes care of inserting the lua_State* into the argument list for the corresponding C++ function. This will work correctly even for the state created by coroutines. Undefined behavior results if the lua_State* is not the last parameter. AFAIK, this is what you need to do if you intend to use or reference lua_State in C++ function called from Lua. It’s fine to not do this when you don’t intend to change lua_State. hi there, great blog really liking it. but i’v got a bit of a problem, after including lua and luaBridge, linking the lua library and writing the main() function; i’m getting #LNK “13 unresolved externals” errors, has this happened to you, any ideas? Hello. Thank you! Can you provide your source code and some error messages you’re getting? Are linking errors from Lua? Do you get them if you just simply create lua_State in main()? Hi, what are the changes required to migrate to Lua 5.3.3? I need to support 64bit integers. Thank you To be fair, I didn’t work with Lua 5.3, so I can’t answer to that. :) Very Helpful Tutorial Series, well explained and taking care of all the sensitive part thanks for the tutorials, keep it up You’re welcome! Check out sol2, though, it’s much superior binding! :D What function is that “lua_pcall” calling in the first example? I’m guessing it’s one of the Lua-side return values from luaL_dofile? lua_pcall executes stuff on stack. It’s unnecessary when doing dofile, because dofile = loadfile + pcall. I don’t remember why I added it. :D Hello, when I try to addFunction I get error assert failed, namespace.h Hi. Can you show me your code and which assert fails? I’ve downloaded the lua binaries, but there is no lua52.lib, only a lua53.dll and three executables. Any ideas? Download Lua from here Thanks very much :)
https://eliasdaler.wordpress.com/2014/07/18/using-lua-with-cpp-luabridge/
CC-MAIN-2019-26
refinedweb
2,919
67.96
In EPiServer 7.5 we have done some additions that makes it possible to alter quite a few things regarding how your content types should look and behave in the EPiServer UI. This is done by adding something called a UI Descriptor which is responsible for instructing the EPiServer UI how you want instances of the given content type to behave. Lets start with a simple example taken from the Alloy sample project: using EPiServer.Shell; using EPiServer.Templates.Alloy.Models.Pages; namespace EPiServer.Templates.Alloy.Business.UIDescriptors { [UIDescriptorRegistration] public class ContainerPageUIDescriptor : UIDescriptor<ContainerPage> { public ContainerPageUIDescriptor() : base(ContentTypeCssClassNames.Container) { DefaultView = CmsViewNames.AllPropertiesView; } } } What the code above does is configuring the following settings for the type ContainerPage: In the example above we are using one of the built in css classes in EPiServer but there is nothing preventing you from adding your own classes/icons (see Stefan Torstenssons blog post about how to add custom styles to the EPiServer UI). Image showing how container pages have a different icon compared to other pages. Hint: You can use the technique above if you want to have the “All properties” view as the default view for some of your content types, for instance a content type where it makes no sense using on page editing. Another thing you can configure is the desired behavior when you drag-and-drop an item to a html editor. The default behavior for pages is that a link to the page is inserted to the editor. For blocks however, a “content block” is created using the same technology as for content areas. The following screen shot shows how a block is inserted to a html editor: When the property is rendered to the page it will render using a partial renderer, following the same rules as for a content area: We can change the desired behavior for what happens when dropping an item to an editor by setting the EditorDropBehavior property in the UIDescriptor. Lets try adding a ui descriptor to the SitePageData base class that all pages in the Alloy template inherits from: using EPiServer.Shell; using EPiServer.Templates.Alloy.Models.Pages; namespace EPiServer.Templates.Alloy.UIExtensions { [UIDescriptorRegistration] public class SitePageUIDescriptor : UIDescriptor<SitePageData>, IEditorDropBehavior { public SitePageUIDescriptor() { EditorDropBehaviour = EditorDropBehavior.CreateContentBlock; } public EditorDropBehavior EditorDropBehaviour { get; set; } } } Now when a page is drag-and-dropped to the editor, a content block containing the page is created instead: And this is rendered using a partial template, just as for the block: The settings for content types are inherited so settings you define will affect all inhirited types unless there is a more specific setting defined for a sub type. We currently have no good way to alter the setting for built in EPiServer types (PageData, BlockData etc.) so if you want to change settings for all types for a given main type (all pages, all blocks etc.) I recomend using a base class in your template package as in the Alloy example. Nice! Here is how you change the default view for a product: [UIDescriptorRegistration] public class CatalogContentUiDescriptor : UIDescriptor { public CatalogContentUiDescriptor() : base() { DefaultView = CmsViewNames.OnPageEditView; } } I'm trying to enable partial view for pages in TinyMCE. Is it possible to make use of Tags here to change rendering class (Used RenderingsTags on )? I can only get it to work without tags. @Sven: Do I understand you correctly that you want to add a tag on the html-property that will be used when determining which template to use for any content items inside of the html? @Linus: Yes, that's correct. Simular/same function that is used on ContentAreas (tag to select correct template renderer). I tried adding a tag to the property declaration and it works the same way as for content areas, that is: I can trigger another template for the partial rendering by setting a tag, for instance: Ok. That's what I think I did in my test. I tried this during the episerver training course today (No more training days in this course, so test environment is gone now). I must have dona something wrong on my configuration of my template renderer. Good to know that it shoppa be possible. I'm satisfied with that so see my question as answered/solved :-) When it comes to dropping Pages and Blocks, wouldn't it be nice to be able to have DisplayOptions on Content dragged to the TinyMCE-editor? Also, having an option "None" would be nice. As in "I never want to drop this content into a tinymce field" Thanks for the feedback Alf. I'm forwarding the request for DisplayOptions to the PM:s since it's basically a new feature. For the none option, I checked the code and thought that it would be possible be defining EditorDropBehavior.Undefined. Unfortunately, 0 is currently being treated as undefined and we will fetch settings from a parent type. I have reported a bug for this: Bug #112099: TypeDescriptorManager does not support a value being 0 I can add that the bug mentioned above has been fixed and released so that it's now possible to have no effect when a specific item is dropped to an editor. Ah, great stuff. Was just looking for this. Combined with this: it makes for very powerful customization features "inline" in regular text areas. (Using it as a mix between a ContentArea and XhtmlArea, sortof). Hello Guys, We are developing a solution based on EPiServer 7.5 update 37, and were wondering.. Is there a way to limit the block types that can be dragged into a RichText area? Is there a way to use displayOptions in blocks that are added into a RichText area? Cheers! - Wac Hi! There are two ways to prevents types being added to the editor. The first is the AllowedTypes attribute. This has some limitations but you can add a list of specific types or some built in base types like PageData, ContentFolder etc. There are also some work arounds to get support to add prevention logic based on your own base classes and interfaces: The second way to prevent actions when dropping a specific type, mentioned previously in the comments, by setting EditorDropBehavior.Undefined for a UIDescriptor. This will not prevent the editor from dropping instances of the type to the editor, but nothing will happen when the item is dropped so this way you can prevent actions for an entire type regardless of property. Regarding the display options, we do not currently support this but it's something that we have heard requests for a few times and it's something that we would like to add to get the functionality matching the content area. Hey guys! I've noticed that UIDescriptorRegistration only runs when a site is restarted and I wonder if you can trigger this by code somehow? Our editors wants to have the ability to chose to have either All Properties View by defailt or On-Page edit view by default. My thought was to have a group (for example AllProperteesEditView) and add those editors that want All properties view by default to that group so each time a user logs in you check wether that user is part of the AllProperties.EditView-group and show the appropiate edit view. Hi Alexander. As you mention, the UI Descriptors are treated as singleton objects that are created when the application starts. The means that there is currently no way of modifying them runtime without affecting all users. I tried finding a work around, like using the new keyword for the DefaultView property but that does not work. We have taken the feedback though so if this is something that we hear that there is a big need for, we might implement some way to do this going forward. ps. If you really want to find a solution, you might get away with a real hacky solution like implementing a property with a getter that actually sets the value for the DefaultView property. The idea here is that your property is called when the object is serialized and sent to the client. This is to be considered as a hack and to be able to make this work you need to figure out and make sure that your property is serialized before the DefaultView which I'm not sure is even possible. Then you of course have potential, but probably unlikely, threading issues but that might not be a big issue in this case. ds. Hi Linus! Thanks for answering. It would be a really nice-to-have function if the editors themselves could choose what kind of edit-mode that should be default so if you could implement it in a future release that would be great! In the meantime we've informed our editors that they have the ability to switch every deploy (when we restart the site) if they want to toggle default mode. Hi guys, I've noticed that editing of a custom block breaks when a display template for XhtmlString is present. The issue is mentioned in the comments for. Has anyone found a way around it withouth dropping the template? I tried using FullRefreshPropertiesMetaData though it was a long shot since the editing breaks in All properties view as well. The template doesn't do anything fancy: It renders the property using the EPiServer.Web.Mvc.Html.XhtmlStringExtensions.XhtmlString extension and potentially adds a wrapper div. How can I code custom drop behavior if I could so? See also my question. @Jiri: I have answered your question in the other forum thread. I have learned many language of CS to make the content better and also it’s UI. In this site of essay uk we know about the customizing the look and behavior of the UI and content types.
https://world.episerver.com/blogs/Linus-Ekstrom/Dates/2013/12/Customizing-the-look-and-behavior-in-the-UI-for-your-content-types/
CC-MAIN-2020-05
refinedweb
1,635
60.75
- Ember Components: A Deep Dive Tuesday, January 07, 2014 by martijn broeders Ember.js is a JavaScript MVC framework that allows developers to create ambitious web applications. Although pure MVC allows a developer to separate concerns, it does not provide you with all the tools and your application will need other constructs. Today, I’m going to talk about one of those constructs. Ember components are essentially sandboxed re-usable chunks of UI. If you are not familiar with Ember, please check out Getting Started With Ember.js or the Let’s Learn Ember Course. In this tutorial we will cover the Web Components specification, how to write a component in Ember, talk about composition, explain the difference between an Ember view and an Ember component, and integrating plugins with Ember components. A Word About Web Components Ember components are based off of the W3C Web Components specification. The specification is comprised of four smaller specifications; templates, decorators, shadow DOM, and custom elements. Of these four concepts only three of them have harden specifications, decorators being the exception. By having the specifications in place, framework developers have been able to polyfill these new APIs prior to them being implemented by browser vendors. There are several important concepts to grasp when talking about components: - Components know nothing about the outside world unless explicitly passed in - Components should have a well defined interface to the outside world - Components cannot manipulate any JavaScript outside of the component - Components can broadcast events - Custom elements must be namespaced with a hyphen - Outside JavaScript cannot manipulate components Web Components provide true encapsulation for UI widgets. Below is a diagram of how a component works at the most basic level. While Ember has successfully polyfilled a lot of a specification, frameworks like AngularJS, Dart, Polymer, and Xtags have similar solutions. The only caveat here is that Ember and Angular currently don’t scope styles to the component. Overtime these polyfill solutions will fade away, and frameworks will adopt the browser vendor’s implementation. This is a fundamentally different approach to development, as we can take advantage of future specifications without tying ourselves to experimental features in browsers. The Most Basic Ember Component Now with our knowledge of Web Components, lets implement the very basic my-name component from above, but in Ember. Let’s begin by downloading the Ember Starter Kit from the Ember website. At the time of this tutorial the version of Ember is 1.3.0. Once you have it downloaded open up the files in your favorite editor, delete all of the templates in index.html( denoted with data-template-name ) and everything in app.js. The first thing we are going to want to do is create our component template. For the sake of this tutorial we are going to use inline templates. You do this by writing the following in your index.htmlfile. We also need to create a new Ember application in our JavaScript. <script type="text/x-handlebars"> {{my-name}} </script> <script type="text/x-handlebars" data- // My component template will go here </script> var App = Ember.Application.create(); You’ll notice that the data-template-name has a path name instead of just a plain string. The reason why we prefix our component name with "components/"is to tell Ember we are dealing with a component template and not a regular application template. You’ll also notice that the component name has the hyphen in it. This is the namespacing that I had mentioned in the Web Components specification. Namespacing is done so that we do not have name collisions with existing tags. If we open the browser we shouldn’t see anything different. The reason for this that we have yet to place anything in our my-name template. Let’s take care of that. ... <script type="text/x-handlebars" data- Hi, my name is {{name}}. </script> Now in the browser you should see something like the image above. We still aren’t finished as you can see we actually aren’t printing out a name. As I mentioned in the first section, components should expose a well defined interface to the outside world. In this case we are concerned with the name. So let’s pass in the name by placing a name attribute on the my-name component. ... <script type="text/x-handlebars"> {{my-name name="Chad"}} </script> When you refresh the page you should see “Hi, my name is Chad”. All of this with writing one line of JavaScript. Now that we have a feel for writing a basic component, let’s talk about the difference between Ember components and Ember views. Ember Components vs. Ember Views Ember is an MVC, so some may be thinking, “Why not just use a view for this?” This is a legitimate question. Components actually are a subclass of Ember.View, the biggest difference here is that views are generally found in the context of a controller. Take the example below. App.IndexController = Ember.Controller.extend({ myState: 'on' }); App.IndexView = Ember.View.extend({ click: function () { var controller = this.get( 'controller' ), myState = controller.get( 'mySate' ); console.log( controller ) // The controller instance console.log( myState ) // The string "on" } }); <script type="text/x-handlebars" data- {{myState}} </script> Views normally sit behind a template and turn raw input ( click, mouseEnter, mouseMove, etc ) into a semantic action ( openMenu, editName, hideModal, etc ) in a controller or route. Another thing to point out is that templates need a context as well. So what ends up happening is that Ember infers the context through naming conventions and the URL. See the diagram below. As you can see, there is a level of hierarchy based on the URL and each level of that hierarchy has its own context which is derived through naming conventions. Ember components do not have a context, they only know about the interface that they define. This allows a component to be rendered into any context, making it decoupled and reusable. If the component exposes an interface, it’s the job of the context to fulfill that interface. In other words, if you want the component to render properly you must supply it with data that it’s expecting. It’s important to note that these passed in values can be both strings or bound properties. When bound properties are manipulated inside of a component those changes are still propagated wherever they are referenced in your application. This makes components extremely powerful. Now that we have a good understanding of how components are different from views, let’s look at a more complex example that illustrates how a developer can compose multiple components. Composition of Components One really nice thing about Ember is that it’s built on concepts of UI hierarchy and this is very apparent with composition of components. Below is an example of what we are going to make. It’s a simple group chat UI. Obviously I’m not going to write a whole chat service to power the UI but we can look how we can break the UI down into re-usable and composeable components. Let’s first look how we are going to break up the UI into smaller and more digestible parts. Basically anything that we can draw a box around is a component, with the exception of a the text and button inputs at the bottom of the UI. Our goal is to be able to just configure the component at the outer layer and everything should just work. Let’s start by creating a new html file called chat.html and setting up all of the dependencies for Ember. Next create all of templates. <script type="text/x-handlebars" data- {{outlet}} </script> <script type="text/x-handlebars" data- {{ group-chat messages=model <div class="chat-component"> <ul class="conversation"> {{#each message in messages}} <li class="txt">{{chat-message username=message.twitterUserName message=message.text time=message.timeStamp }}</li> {{/each}} </ul> <form class="new-message" {{action submit <div class="message media"> <div class="img"> {{user-avatar username=username {{user-message message=message}} {{time-stamp time=time}} </div> </div> </script> <script type="text/x-handlebars" data- <img {{bind-attr src=avatarUrl alt=username}} </script> <script type="text/x-handlebars" data- <div class="user-message">{{message}}</div> </script> <script type="text/x-handlebars" data- <div class="time-stamp"> <span class="clock" role="presentation"></span> <span class="time">{{format-date time}}</span> </div> </script> You will see that components can be nested inside of other components. This makes components just like legos that we can assemble any way we want. We just need to write to the component’s interface. If we now go look in the browser we shouldn’t see much because we don’t have any data flowing into the component. You will also notice that even though there is no data, the components do not throw an error. The only thing that actually gets rendered here is the input area and the send button. This is because they aren’t dependent on what is passed in. Taking a little bit closer look at the templates you’ll notice that we assigned a couple things on the group-chat component. <script type="text/x-handlebars" data- {{ group-chat messages=model action="sendMessage" }} </script> In this case, we are passing the model from the context of the IndexRoute as “messages” and we have set the string of “sendMessage” as the action on the component. The action will be used to broadcast out when the user wants to send a new message. We will cover this later in the tutorial. The other thing that you will notice is that we are setting up strict interfaces to the nested components all of which are using the data passed in from the group-chat interface. ... <ul class="conversation"> {{#each message in messages}} <li class="txt">{{chat-message username=message.twitterUserName message=message.text time=message.timeStamp }}</li> {{/each}} </ul> ... As mentioned before you can pass strings or bound properties into components. Rule of thumb being, use quotes when passing a string, don’t use quotes when passing a bound property. Now that we have our templates in place, lets throw some mock data at it. App = Ember.Application.create(); App.IndexRoute = Ember.Route.extend({ model: function() { return [ { id: 1, firstName: 'Tom', lastName: 'Dale', twitterUserName: 'tomdale', text: 'I think we should back old Tomster. He was awesome.', timeStamp: Date.now() - 400000, }, { id: 2, firstName: 'Yehuda', lastName: 'Katz', twitterUserName: 'wycats', text: 'That\'s a good idea.', timeStamp: Date.now() - 300000, } ]; } }); If we go look at this in the browser now, we should see a bit of progress. But there are still some work to be done, mainly getting the images to show up, formatting the date, and being able to send a new message. Let’s take care of that. So with our user-avatar component, we want to use a service called Avatars.io to fetch a user’s twitter avatar based on their twitter user name. Let’s look at how the user-image component is used in the template. <script type="text/x-handlebars" data- ... {{ user-avatar username=username <img {{bind-attr src=avatarUrl alt=username}} </script> It’s a pretty simple component but you will notice that we have a bound property called avatarUrl. We are going to need to create this property within our JavaScript for this component. Another thing you will note is that we are specifying the service we want to fetch the avatar from. Avatars.io allows you fetch social avatars from Twitter, Facebook, and Instagram. So we can make this component extremely flexible. Let’s write the component. App.UserAvatarComponent = Ember.Component.extend({ avatarUrl: function () { var username = this.get( 'username' ), service = this.get( 'service' ), availableServices = [ 'twitter', 'facebook', 'instagram' ]; if ( availableServices.indexOf( service ) > -1 ) { return '' + service + '/' + username; } return 'images/cat.png'; }.property( 'username' , 'service' ) }); As you can see, to create a new component we just follow the naming convention of NAMEOFCOMPONENTComponent and extend Ember.Component. Now if we go back to the browser we should now see our avatars. To take care of the date formatting let’s use moment.js and write a Handlebars helper to format the date for us. Ember.Handlebars.helper('format-date', function( date ) { return moment( date ).fromNow(); }); Now all we need to do is apply the helper to our time stamp component. <script type="text/x-handlebars" data- <div class="time-stamp"> <span class="clock" role="presentation"></span> <span class="time">{{format-date time}}</span> </div> </script> We should now have a component that formats dates instead of the Unix epoch timestamps. We can do one better though. These timestamps should automatically update over the coarse of time. So lets make our time-stamp component do just that. App.TimeStampComponent = Ember.Component.extend({ startTimer: function () { var self = this, currentTime; this._timer = setInterval( function () { currentTime = self.get( 'time' ); self.set( 'time', ( currentTime - 60000 ) ); }, 60000 ); }.on( 'didInsertElement' ), killTimer: function () { clearInterval( this._timer ); }.on( 'willDestroyElement' ) }); A couple points to note here are the on() declarative event handler syntax. This was introduced in Ember prior to the 1.0 release. It does exactly what you think it does, when the time-stamp component is inserted into the DOM, startTimer is called. When the element is about to be destroyed and cleaned up the killTimer method will be called. The rest of component just tells the time to update every minute. The next thing we need to do is setup the action so that when the user hits submit, a new message will be created. Our component shouldn’t care how the data is created it should just broadcast out that the user has tried to send a message. Our IndexRoute will be responsible for taking this action and turning into something meaningful. App.GroupChatComponent = Ember.Component.extend({ message: '', actions: { submit: function () { var message = this.get( 'message' ).trim(), conversation = this.$( 'ul' )[ 0 ]; // Fetches the value of 'action' // and sends the action with the message this.sendAction( 'action', message ); // When the Ember run loop is done // scroll to the bottom Ember.run.next( function () { conversation.scrollTop = conversation.scrollHeight; }); // Reset the text message field this.set( 'message', '' ); } } }); <form class="new-message" {{action submit on="submit"}}> {{input type="text" placeholder="Send new message" value=message class="txt-field"}} {{input type="submit" class="send-btn" value="Send"}} </form> Since the group-chat component owns the input and send button we need to react to the user clicking send at this level of abstraction. When the user clicks the submit button it is going to execute the submit action in our component implementation. Within the submit action handler we are going to get the value of message, which is set by by the text input. We will then send the action along with the message. Finally we will reset the message to a black string. The other odd thing you see here is the Ember.run.next method being called. In Ember there is a queue, normally referred to as the run loop, that get’s flushed when data is changed. This is done to basically coalesce changes and make the change once. So in our case we are saying when the sending of the message is done making any manipulations, call our callback. We need to scroll our ul to the bottom so the user can see the new message after any manipulations. For more on the run loop I suggest reading Alex Matchneer’s article “Everything You Never Wanted to Know About the Ember Run Loop”. If we go over to the browser and we click the send button, we get a really nice error from Ember saying “Uncaught Error: Nothing handled the event ‘sendMessage’. This is what we expect because we haven’t told our application on how to reaction to these types of events. Let’s fix that. App.IndexRoute = Ember.Route.extend({ /* … */ actions: { sendMessage: function ( message ) { if ( message !== '') { console.log( message ); } } } }); Now if we go back to the browser type something into the message input and hit send, we should see the message in the console. So at this point our component is loosely coupled and talking to the rest our application. Let’s do something more interesting with this. First let’s create a new Ember.Object to work as a model for a new message. App.Message = Ember.Object.extend({ id: 3, firstName: 'Chad', lastName: 'Hietala', twitterUserName: 'chadhietala', text: null, timeStamp: null }); So when the sendMessage action occurs we are going to want to populate the text and timeStamp field of our Message model, create a new instance of it, and then push that instance into the existing collection of messages. App.IndexRoute = Ember.Route.extend({ /* … */ actions: { sendMessage: function ( message ) { var user, messages, newMessage; if ( message !== '' ) { messages = this.modelFor( 'index' ), newMessage = App.Message.create({ text: message, timeStamp: Date.now() }) messages.pushObject( newMessage ); } } } }); When we go back to the browser and we should now be able to create new messages. We now have several different re-usable chucks of UI that we can just place anywhere. For instance if you needed to use an avatar somewhere else in your Ember application we can just reuse the user-avatar component. <script type="text/x-handlebars" data- ... {{user-avatar username="horse_js" service="twitter" }} {{user-avatar username="detroitlionsnfl" service="instagram" }} {{user-avatar username="KarlTheFog" service="twitter" }} </script> Wrapping jQuery Plugins So at this point you’re probably wondering “What if I want to use some jQuery plugin in my component?” No problem. For brevity, lets modify our user-avatar component to show a tool tip when we hover over the avatar. I’ve chosen to use the jQuery plugin tooltipster to handle the tooltip. Let’s modify the existing code to utilize tooltipster. First lets add correct files to our chat.htmland modifiy the existing user avatar component. ... <link href="css/tooltipster.css" rel="stylesheet" /> ... <script type="text/JavaScript" src="js/libs/jquery.tooltipster.min.js"></script> <script type="text/JavaScript" src="js/app.js"></script> ... And then our JavaScript: App.UserAvatarComponent = Ember.Component.extend({ /*…*/ setupTooltip: function () { this.$( '.avatar' ).tooltipster({ animation: 'fade' }); }.on( 'didInsertElement' ), destroyTooltip: function () { this.$( '.avatar' ).tooltipster( 'destroy' ); }.on( 'willDestroyElement' ) )}; So once again we see the declarative event listener syntax, but for the first time we see this.$. If you are familiar with jQuery you would expect that we would be querying all the elements with class of ‘avatar’. This isn’t the case in Ember because context is applied. So in our case we are only looking for elements with the class of ‘avatar’ in the user-avatar component. It’s comparable to jQuery’s find method e.g. $( ‘.user-avatar’ ).find( ‘.avatar’ ). On destruction of the element we should unbind the hover event on the avatar and clean up any functionality, this is done by passing ‘destroy’ to tooltipster. If we go to the browser, refresh and hover an image we should see the users username. Conclusion In this tutorial we took a deep dive into Ember components and showed how you can take re-usable chunks of UI to generate larger composites and integrate jQuery plugins. We looked at how components are different from views in Ember. We also covered the idea of interface-based programming when it comes to components. Hopefully I was able to shine some light on not only Ember Components but Web Components and where the Web is headed. Leave a comment › Posted in: Daily
http://www.4elements.com/blog/comments/ember_components_a_deep_dive
CC-MAIN-2017-47
refinedweb
3,241
56.55
In Part 1 of this series, I briefly outlined the goals for this project, which at a high level is to use Windows Azure table storage as a data store for a SharePoint custom claims provider. The claims provider is going to use the CASI Kit to retrieve the data it needs from Windows Azure in order to provide people picker (i.e. address book) and type in control name resolution functionality. this, the final part in this series, we’ll walk through the different components used on the SharePoint side. It includes a custom component built using the CASI Kit to add items to the queue as well as to make our calls to Azure table storage. It also includes our custom claims provider, which will use the CASI Kit component to connect SharePoint with those Azure functions. To begin with let’s take a quick look at the custom CASI Kit component. I’m not going to spend a whole lot of time here because the CASI Kit is covered extensively on this blog. This particular component is described in Part 3 of the CASI Kit series. Briefly though, what I’ve done is created a new Windows class library project. I’ve added references to the CASI Kit base class assembly and the other required .NET assemblies (that I describe in part 3). I’ve added a Service Reference in my project to the WCF endpoint I created in Part 2 of this project. Finally, I added a new class to the project and have it inherit the CASI Kit base class, and I’ve added the code to override the ExecuteRequest method. As you have hopefully seen in the CASI Kit series, here’s what my code looks like to override ExecuteRequest: public class DataSource : AzureConnect.WcfConfig { public override bool ExecuteRequest() { try { //create the proxy instance with bindings and endpoint the base class //configuration control has created for this AzureClaims.AzureClaimsClient cust = new AzureClaims.AzureClaimsClient(this.FedBinding, this.WcfEndpointAddress); //configure the channel so we can call it with //FederatedClientCredentials. SPChannelFactoryOperations.ConfigureCredentials<AzureClaims.IAzureClaims> (cust.ChannelFactory, Microsoft.SharePoint.SPServiceAuthenticationMode.Claims); //create a channel to the WCF endpoint using the //token and claims of the current user AzureClaims.IAzureClaims claimsWCF = SPChannelFactoryOperations.CreateChannelActingAsLoggedOnUser <AzureClaims.IAzureClaims>(); } } “AzureClaims” is the name of the Service Reference I created, and it uses the IAzureClaims interface that I defined in my WCF project in Azure. As explained previously in the CASI Kit series, this is basically boilerplate code, I’ve just plugged in the name of my interface and class that is exposed in the WCF application. The other thing I’ve done, as is also explained in the CASI Kit series, is to create an ASPX page called AzureClaimProvider.aspx. I just copied and pasted in the code I describe in Part 3 of the CASI Kit series and substituted the name of my class and the endpoint it can be reached at. The control tag in the ASPX page for my custom CASI Kit component looks like this: <AzWcf:DataSource The main things to note here are that I created a CNAME record for “spsazure.vbtoys.com” that points to my Azure application at cloudapp.net (this is also described in Part 3 of the CASI Kit). I’ve set the default MethodName that the page is going to invoke to be GetClaimTypes, which is a method that takes no parameters and returns a list of claim types that my Azure claims provider supports. This makes it a good test to validate the connectivity between my Azure application and SharePoint. I can simply go to and if everything is configured correctly I will see some data in the page. Once I’ve deployed my project by adding the assembly to the Global Assembly Cache and deploying the page to SharePoint’s _layouts directory that’s exactly what I did – I hit the page in one of my sites and verified that it returned data, so I knew my connection between SharePoint and Azure was working. Now that I have the plumbing in place, I finally get to the “fun” part of the project, which is to do two things: This is actually a good point to stop and step back a little. In this particular case I just wanted to roll something out as quickly as possible. So, what I did is I created a new web application and I enabled anonymous access. As I’m sure you all know, just enabling it at the web app level does NOT enable it at the site collection level. So for this scenario, I also enabled at the root site collection only; I granted access to everything in the site. All other site collections, which would contain any information for members only, does NOT have anonymous enabled so users have to be granted rights to join. The next thing to think about is how to manage the identities that are going to use the site. Obviously, that’s not something I want to do. I could have come up with a number of different methods to sync accounts into Azure or something goofy like that, but as I explained in Part 1 of this series, there’s a whole bunch of providers that do that already so I’m going to let them keep doing what they do. What I mean by that is that I took advantage of another Microsoft cloud service called ACS, or Access Control Service. In short ACS acts like an identity provider to SharePoint. So I just created a trust between my SharePoint farm and the instance of ACS that I created for this POC. In ACS I added SharePoint as a relying party, so ACS knows where to send users once they’ve authenticated. Inside of ACS, I also configured it to let users sign in using their Gmail, Yahoo, or Facebook accounts. Once they’ve signed in ACS gets a single claim back that I’ll use – email address – and sends it back to SharePoint. Okay, so that’s all of the background on the plumbing – Azure is providing table storage and queues to work with the data, ACS is providing authentication services, and CASI Kit is providing the plumbing to the data. So with all that plumbing described, how are we going to use it? Well I still wanted the process to become a member pretty painless, so what I did is I wrote a web part to add users to my Azure queue. What it does is it checks to see if the request is authenticated (i.e. the user has clicked the Sign In link that you get in an anonymous site, signed into one of the providers I mentioned above, and ACS has sent me back their claim information). If the request is not authenticated the web part doesn’t do anything. However if the request is authenticated, it renders a button that when clicked, will take the user’s email claim and add it to the Azure queue. This is the part about which I said we should step back a moment and think about it. For a POC that’s all fine and good, it works. However you can think about other ways in which you could process this request. For example, maybe you write the information to a SharePoint list. You could write a custom timer job (that the CASI Kit works with very nicely) and periodically process new requests out of that list. You could use the SPWorkItem to queue the requests up to process later. You could store it in a list and add a custom workflow that maybe goes through some approval process, and once the request has been approved uses a custom workflow action to invoke the CASI Kit to push the details up to the Azure queue. In short – there’s a LOT of power, flexibility and customization possible here – it’s all up to your imagination. At some point in fact I may write another version of this that writes it to a custom list, processes it asynchronously at some point, adds the data to the Azure queue and then automatically adds the account to the Visitors group in one of the sub sites, so the user would be signed up and ready to go right away. But that’s for another post if I do that. So, all that being said – as I described above I’m just letting the user click a button if they’ve signed in and then I’ll use my custom CASI Kit component to call out the WCF endpoint and add the information to the Azure queue. Here’s the code for the web part – pretty simple, courtesy of the CASI Kit: public class AddToAzureWP : WebPart { //button whose click event we need to track so that we can //add the user to Azure Button addBtn = null; Label statusLbl = null; protected override void CreateChildControls() if (this.Page.Request.IsAuthenticated) addBtn = new Button(); addBtn.Text = "Request Membership"; addBtn.Click += new EventHandler(addBtn_Click); this.Controls.Add(addBtn); statusLbl = new Label(); this.Controls.Add(statusLbl); void addBtn_Click(object sender, EventArgs e) try //look for the claims identity IClaimsPrincipal cp = Page.User as IClaimsPrincipal; if (cp != null) //get the claims identity so we can enum claims IClaimsIdentity ci = (IClaimsIdentity)cp.Identity; //look for the email claim //see if there are claims present before running through this if (ci.Claims.Count > 0) { //look for the email address claim var eClaim = from Claim c in ci.Claims where c.ClaimType == "" select c; Claim ret = eClaim.FirstOrDefault<Claim>(); if (ret != null) { //create the string we're going to send to the Azure queue: claim, value, and display name //note that I'm using "#" as delimiters because there is only one parameter, and CASI Kit //uses ; as a delimiter so a different value is needed. If ; were used CASI would try and //make it three parameters, when in reality it's only one string qValue = ret.ClaimType + "#" + ret.Value + "#" + "Email"; //create the connection to Azure and upload / = AzureCCP.SVC_URI; cfgCtrl.OutputType = AzureConnect.WcfConfig.DataOutputType.None; cfgCtrl.MethodName = "AddClaimsToQueue"; cfgCtrl.MethodParams = qValue; cfgCtrl.ServerCacheTime = 10; cfgCtrl.ServerCacheName = ret.Value; cfgCtrl.SharePointClaimsSiteUrl = this.Page.Request.Url.ToString(); //execute the method bool success = cfgCtrl.ExecuteRequest(); if (success) { //if it worked tell the user statusLbl.Text = "<p>Your information was successfully added. You can now contact any of " + "the other Partner Members or our Support staff to get access rights to Partner " + "content. Please note that it takes up to 15 minutes for your request to be " + "processed.</p>"; } else statusLbl.Text = "<p>There was a problem adding your info to Azure; please try again later or " + "contact Support if the problem persists.</p>"; } } catch (Exception ex) statusLbl.Text = "There was a problem adding your info to Azure; please try again later or " + "contact Support if the problem persists."; Debug.WriteLine(ex.Message); } So a brief rundown of the code looks like this: I first make sure the request is authenticated; if it is I added the button to the page and I add an event handler for the click event of the button. In the button’s click event handler I get an IClaimsPrincipal reference to the current user, and then look at the user’s claims collection. I run a LINQ query against the claims collection to look for the email claim, which is the identity claim for my SPTrustedIdentityTokenIssuer. If I find the email claim, I create a concatenated string with the claim type, claim value and friendly name for the claim. Again, this isn’t strictly required in this scenario, but since I wanted this to be usable in a more generic scenario I coded it up this way. That concatenated string is the value for the method I have on the WCF that adds data to the Azure queue. I then create an instance of my custom CASI Kit component and configure it to call the WCF method that adds data to the queue, then I call the ExecuteRequest method to actually fire off the data. If I get a response indicating I was successful adding data to the queue then I let the user know; otherwise I let him know there was a problem and hey may need to check again later. In a real scenario of course I would have even more error logging so I could track down exactly what happened and why. Even with this as is though, the CASI Kit will write any error information to the ULS logs in a SPMonitoredScope, so everything it does for the request will have a unique correlation ID with which we can view all activity associated with the request. So I’m actually in a pretty good state right now. Okay – we’ve walked through all the plumbing pieces, and I’ve shown how data gets added to the Azure queue and from there pulled out by a worker process and added into table storage. That’s really the ultimate goal because now we can walk through the custom claims provider. It’s going to use the CASI Kit to call out and query the Azure table storage I’m using. Let’s look at the most interesting aspects of the custom claims provider. First let’s look at a couple of class level attributes: //the WCF endpoint that we'll use to connect for address book functions //test url: //production url: public static string SVC_URI = ""; //the identity claimtype value private const string IDENTITY_CLAIM = ""; //the collection of claim type we support; it won't change over the course of //the STS (w3wp.exe) life time so we'll cache it once we get it AzureClaimProvider.AzureClaims.ClaimTypeCollection AzureClaimTypes = new AzureClaimProvider.AzureClaims.ClaimTypeCollection(); First, I use a constant to refer to the WCF endpoint to which the CASI Kit should connect. You’ll note that I have both my test endpoint and my production endpoint. When you’re using the CASI Kit programmatically, like we will in our custom claims provider, you always have to tell it where that WCF endpoint is that it should talk to. Next, as I’ve described previously I’m using the email claim as my identity claim. Since I will refer to it a number of times throughout my provider, I’ve just plugged into a constant at the class level. Finally, I have a collection of AzureClaimTypes. I explained in Part 2 of this series why I’m using a collection, and I’m just storing it here at the class level so that I don’t have to go and re-fetch that information each time my FillHierarchy method is invoked. Calls out to Azure aren’t cheap, so I minimize them where I can. Here’s the next chunk of code: internal static string ProviderDisplayName get return "AzureCustomClaimsProvider"; internal static string ProviderInternalName //******************************************************************* //USE THIS PROPERTY NOW WHEN CREATING THE CLAIM FOR THE PICKERENTITY internal static string SPTrustedIdentityTokenIssuerName return "SPS ACS"; public override string Name return ProviderInternalName; The reason I wanted to point this code out is because since my provider is issuing identity claims, it MUST be the default provider for the SPTrustedIdentityTokenIssuer. Explaining how to do that is outside the scope of this post, but I’ve covered it elsewhere in my blog. The main thing to remember about doing that is that you must have a strong relationship between the name you use for your provider and the name used for the SPTrustedIdentityTokenIssuer. The value I used for the ProviderInternalName is the name that I must plug into the ClaimProviderName property for the SPTrustedIdentityTokenIssuer. Also, I need to use the name of the SPTrustedIdentityTokenIssuer when I’m creating identity claims for users. So I’ve created an SPTrustedIdentityTokenIssuer called “SPS ACS” and I’ve added that to my SPTrustedIdentityTokenIssuerName property. That’s why I have these values coded in here. Since I’m not doing any claims augmentation in this provider, I have not written any code to override FillClaimTypes, FillClaimValueTypes or FillEntityTypes. The next chunk of code I have is FillHierarchy, which is where I tell SharePoint what claim types I support. Here’s the code for that: try if ( (AzureClaimTypes.ClaimTypes == null) || (AzureClaimTypes.ClaimTypes.Count() == 0) ) / = SVC_URI; cfgCtrl.OutputType = AzureConnect.WcfConfig.DataOutputType.None; cfgCtrl.MethodName = "GetClaimTypes"; cfgCtrl.ServerCacheTime = 10; cfgCtrl.ServerCacheName = "GetClaimTypes"; cfgCtrl.SharePointClaimsSiteUrl = context.AbsoluteUri; //execute the method bool success = cfgCtrl.ExecuteRequest(); if (success) //if it worked, get the list of claim types out AzureClaimTypes = (AzureClaimProvider.AzureClaims.ClaimTypeCollection)cfgCtrl.QueryResultsObject; //make sure picker is asking for the type of entity we return; site collection admin won't for example if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.User)) return; //at this point we have whatever claim types we're going to have, so add them to the hierarchy //check to see if the hierarchyNodeID is null; it will be when the control //is first loaded but if a user clicks on one of the nodes it will return //the key of the node that was clicked on. This lets you build out a //hierarchy as a user clicks on something, rather than all at once (string.IsNullOrEmpty(hierarchyNodeID)) && (AzureClaimTypes.ClaimTypes.Count() > 0) ) //enumerate through each claim type foreach (AzureClaimProvider.AzureClaims.ClaimType clm in AzureClaimTypes.ClaimTypes) //when it first loads add all our nodes hierarchy.AddChild(new Microsoft.SharePoint.WebControls.SPProviderHierarchyNode( ProviderInternalName, clm.FriendlyName, clm.ClaimTypeName, true)); catch (Exception ex) Debug.WriteLine("Error filling hierarchy: " + ex.Message); So here I’m looking to see if I’ve grabbed the list of claim types I support already. If I haven’t then I create an instance of my CASI Kit custom control and make a call out to my WCF to retrieve the claim types; I do this by calling the GetClaimTypes method on my WCF class. If I get data back then I plug it into the class-level variable I described earlier called AzureClaimTypes, and then I add it to the hierarchy of claim types I support. The next methods we’ll look at is the FillResolve methods. The FillResolve methods have two different signatures because they do two different things. In one scenario we have a specific claim with value and type and SharePoint just wants to verify that is valid. In the second case a user has just typed some value into the SharePoint type in control and so it’s effectively the same thing as doing a search for claims. Because of that, I’ll look at them separately. In the case where I have a specific claim and SharePoint wants to verify the values, I call a custom method I wrote called GetResolveResults. In that method I pass in the Uri where the request is being made as well as the claim type and claim value SharePoint is seeking to validate. The GetResolveResults then looks like this: //Note that claimType is being passed in here for future extensibility; in the //current case though, we're only using identity claims private AzureClaimProvider.AzureClaims.UniqueClaimValue GetResolveResults(string siteUrl, string searchPattern, string claimType) AzureClaimProvider.AzureClaims.UniqueClaimValue result = null; try cfgCtrl.MethodName = "ResolveClaim"; cfgCtrl.ServerCacheName = claimType + ";" + searchPattern; cfgCtrl.MethodParams = IDENTITY_CLAIM + ";" + searchPattern; cfgCtrl.SharePointClaimsSiteUrl = siteUrl; //if the query encountered no errors then capture the result result = (AzureClaimProvider.AzureClaims.UniqueClaimValue)cfgCtrl.QueryResultsObject; catch (Exception ex) Debug.WriteLine(ex.Message); return result; So here I’m creating an instance of the custom CASI Kit control then calling the ResolveClaim method on my WCF. That method takes two parameters, so I pass that in as semi-colon delimited values (because that’s how CASI Kit distinguishes between different param values). I then just execute the request and if it finds a match it will return a single UniqueClaimValue; otherwise the return value will be null. Back in my FillResolve method this is what my code looks like: protected override void FillResolve(Uri context, string[] entityTypes, SPClaim resolveInput, List<PickerEntity> resolved) //look for matching claims AzureClaimProvider.AzureClaims.UniqueClaimValue result = GetResolveResults(context.AbsoluteUri, resolveInput.Value, resolveInput.ClaimType); //if we found a match then add it to the resolved list if (result != null) PickerEntity pe = GetPickerEntity(result.ClaimValue, result.ClaimType, SPClaimEntityTypes.User, result.DisplayName); resolved.Add(pe); So I’m checking first to make sure that the request is for a User claim, since that the only type of claim my provider is returning. If the request is not for a User claim then I drop out. Next I call my method to resolve the claim and if I get back a non-null result, I process it. To process it I call another custom method I wrote called GetPickerEntity. Here I pass in the claim type and value to create an identity claim, and then I can add that PickerEntity that it returns to the List of PickerEntity instances passed into my method. I’m not going to go into the GetPickerEntity method because this post is already incredibly long and I’ve covered how to do so in other posts on my blog. Now let’s talk about the other FillResolve method. As I explained earlier, it basically acts just like a search so I’m going to combine the FillResolve and FillSearch methods mostly together here. Both of these methods are going to call a custom method I wrote called SearchClaims, that looks like this: private AzureClaimProvider.AzureClaims.UniqueClaimValueCollection SearchClaims(string claimType, string searchPattern, string siteUrl) AzureClaimProvider.AzureClaims.UniqueClaimValueCollection results = new AzureClaimProvider.AzureClaims.UniqueClaimValueCollection(); cfgCtrl.MethodName = "SearchClaims"; cfgCtrl.MethodParams = claimType + ";" + searchPattern + ";200"; //if it worked, get the array of results results = (AzureClaimProvider.AzureClaims.UniqueClaimValueCollection)cfgCtrl.QueryResultsObject; Debug.WriteLine("Error searching claims: " + ex.Message); return results; In this method, as you’ve seen elsewhere in this post, I’m just creating an instance of my custom CASI Kit control. I’m calling the SearchClaims method on my WCF and I’m passing in the claim type I want to search in, the claim value I want to find in that claim type, and the maximum number of records to return. You may recall from Part 2 of this series that SearchClaims just does a BeginsWith on the search pattern that’s passed in, so with lots of users there could easily be over 200 results. However 200 is the maximum number of matches that the people picker will show, so that’s all I ask for. If you really think that users are going to scroll through more than 200 results looking for a result I’m here to tell you that ain’t likely. So now we have our colletion of UniqueClaimValues back, let’s look at how we use it our two override methods in the custom claims provider. First, here’s what the FillResolve method looks like: protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List<PickerEntity> resolved) //this version of resolve is just like a search, so we'll treat it like that //do the search for matches AzureClaimProvider.AzureClaims.UniqueClaimValueCollection results = SearchClaims(IDENTITY_CLAIM, resolveInput, context.AbsoluteUri); //go through each match and add a picker entity for it foreach (AzureClaimProvider.AzureClaims.UniqueClaimValue cv in results.UniqueClaimValues) PickerEntity pe = GetPickerEntity(cv.ClaimValue, cv.ClaimType, SPClaimEntityTypes.User, cv.DisplayName); resolved.Add(pe); It just calls the SearchClaims method, and for each result it gets back (if any), it creates a new PickerEntity and adds it to the List of them passed into the override. All of them will show up in then in the type in control in SharePoint. The FillSearch method uses it like this: protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree) SearchClaims(IDENTITY_CLAIM, searchPattern, context.AbsoluteUri); //if there was more than zero results, add them to the picker if (results.UniqueClaimValues.Count() > 0) foreach (AzureClaimProvider.AzureClaims.UniqueClaimValue cv in results.UniqueClaimValues) //node where we'll stick our matches Microsoft.SharePoint.WebControls.SPProviderHierarchyNode matchNode = null; //get a picker entity to add to the dialog PickerEntity pe = GetPickerEntity(cv.ClaimValue, cv.ClaimType, SPClaimEntityTypes.User, cv.DisplayName); //add the node where it should be displayed too if (!searchTree.HasChild(cv.ClaimType)) //create the node so we can show our match in there too matchNode = new SPProviderHierarchyNode(ProviderInternalName, cv.DisplayName, cv.ClaimType, true); //add it to the tree searchTree.AddChild(matchNode); else //get the node for this team matchNode = searchTree.Children.Where(theNode => theNode.HierarchyNodeID == cv.ClaimType).First(); //add the match to our node matchNode.AddEntity(pe); In FillSearch I’m calling my SearchClaims method again. For each UniqueClaimValue I get back (if any), I look to see if I’ve added the claim type to the results hierarchy node. Again, in this case I’ll always only return one claim type (email), but I wrote this to be extensible so you could use more claim types later. So I add the hierarchy node if it doesn’t exist, or find it if it does. I take the PickerEntity that I create created from the UniqueClaimValue and I add it to the hierarchy node. And that’s pretty much all there is too it. I’m not going to cover the FillSchema method or any of the four Boolean property overrides that every custom claim provider must have, because there’s nothing special in them for this scenario and I’ve covered the basics in other posts on this blog. I’m also not going to cover the feature receiver that’s used to register this custom claims provider because – again – there’s nothing special for this project and I’ve covered it elsewhere. After you compile it you just need to make sure that your assembly for the custom claim provider as well as custom CASI Kit component is registered in the Global Assembly Cache in each server on the farm, and you need to configure the SPTrustedIdentityTokenIssuer to use your custom claims provider as the default provider (also explained elsewhere in this blog). That’s the basic scenario end to end. When you are in the SharePoint site and you try and add a new user (email claim really), the custom claim provider is invoked first to get a list of supported claim types, and then again as you type in a value in the type in control, or search for a value using the people picker. In each case the custom claims provider uses the custom CASI Kit control to make an authenticated call out to Windows Azure to talk to our WCF, which uses our custom data classes to retrieve data from Azure table storage. It returns the results and we unwrap that and present it to the user. With that you have your complete turnkey SharePoint and Azure “extranet in a box” solution that you can use as is, or modify to suit your purposes. The source code for the custom CASI Kit component, web part that registers the user in an Azure queue, and custom claims provider is all attached to this posting. Hope you enjoy it, find it useful, and can start to visualize how you can tie these separate services together to create solutions to your problems. Here’s some screenshots of the final solution: Root site as anonymous user: Here’s what it looks like after you’ve authenticated; notice that the web part now displays the Request Membership button: Here’s an example of the people picker in action, after searching for claim values that starts with “sp”: thanks
http://blogs.technet.com/b/speschka/archive/2012/02/20/the-azure-custom-claim-provider-for-sharepoint-project-part-3.aspx
CC-MAIN-2014-42
refinedweb
4,571
60.65
File and Type Layout ReSharper can reorder types and type members in C# files according to the configured patterns. Patterns can describe a lot of conditions and constraints that are evaluated when reordering items in a file and/or wrapping them with specified regions. In this topic: - Introduction to layout patterns - File and type layout preferences - Configuring file and type layout rules visually - Configuring file and type layout by editing the source XAML - Reordering file and type members Introduction to layout patterns You can configure and use two types of patterns: - File pattern. Applies to all C# files. Can arrange namespaces, types, and delegates; wrap them in regions or organize in groups, remove regions. The contents of the types can be further arranged with type patterns. Note that only one file pattern can be applied at a time. - Type pattern. Only applies to types, that match pattern's constraints, if any. Can arrange file members, wrap them in regions or organize in groups, remove regions. Within the patterns, you can specify matcher entries in the desired order as well as regions/groups, in which the matching items are wrapped/grouped. The algorithm of applying the current pattern set works as follows: - If a file pattern exists, ReSharper ReSharper. ReSharper checks whether each of the type patterns matches amy type in the file. If there are several matching patterns for a type, the conflicts are resolved similarly to steps 3 and 4. - When the type match is established, ReSharper checks whether regions in the type should be removed, then it checks whether each of the matcher entries in the pattern matches amy member in the file. - If there are matching members, their position in the type is changed according to the position of the corresponding matcher item in the type pattern. - Regions, groups and unmatched members are dealt with similarly to steps 5 and 6. File and type layout preferences Out of the box, ReSharper provides type patterns for COM interfaces and structs, for NUnit test fixtures, and the default pattern for the rest of C# types. There are two sets of patterns: one uses regions to wrap specific kinds of type members, while the other does not use regions. The default member layout rules are based on numerous best practices and can be recommended in most cases. However, if your personal preferences or company standards differ from ReSharper defaults, you can configure code reordering patterns basing one the default ones as well as create new patters for specific cases. All modifications to the layout patterns are done on the Code Editing | C# | File Layout page of ReSharper options. After the editing is done, click Save to apply the modifications and let ReSharper choose the settings layer, or choose a particular settings layer in the Save To drop-down list. To learn more about saving ReSharper settings, see Managing and Sharing ReSharper Settings. Configuring file and type layout rules visually ReSharper allows you to configure all parameters of layout rules using a dedicated visual editor. Items in the editor page can be displayed in one of the following views: - Patterns. This is a root view that displays all available patterns in the current patterns set. You can open this view by clicking Patterns in the top left corner of the page. From this view, you can navigate to any pattern by double-clicking it. To add a new pattern to the set, drag-n-drop a file or type pattern item from the toolbox on the right. You can also use drag-n-drop to reorder patterns. The order of type patterns defines which pattern is applied if several patterns match the same type with equal priority and constraints. - Composition. This view visualizes the order and grouping of the matcher entries, regions, and groups inside a pattern, a region or a group. In the illustration below, you can see a composition view of a type pattern: - Constrains. This view visualises constraints of a pattern or a matcher entry, e.g. what kind of code items with which modifiers or attributes should or should not be matched by it, etc. Patterns and matchers will only apply to items matching all their constraints. All constraints are grouped by logical containers that identify relations between these constraints. In the illustration below, you can see a constraints view of a matcher entry: To edit an existing layout pattern - Go to the Code Editing | C# | File Layout page of ReSharper options. - Click Patterns on the upper left corner of the page to see all patterns in the current set. In the properties of this element, you can use the Static Field Reordering Policy selector to define whether and how to reorder static fields with initializers. The options are: - Strict - static fields are not reordered if there is a chance it might affect program behavior. For example, if there is a static field with initializer that has a reference to a static member of the same class, all static fields of the class are not reordered. - Relaxed - reordering of static fields that have explicit usage of other static fields in their initializers as well as the static fields they are referencing is prohibited. - Unrestricted - reordering is always allowed (not recommended). For non-reordered static fields with initializers, ReSharper preserves their relative order while still reordering them together with other declarations. - Optionally, to load one of the default pattern sets, click Load in the upper right corner of the page, and then choose the pattern set. - Double-click on the desired pattern, and switch it to the composition view if it is in the constraints view (click the icon to the right of the pattern header to switch views). Note that file patterns are always displayed in the composition view, i.e. you cannot specify any constraints for them. - In the composition view, you can modify the pattern in the following ways: - To change the order of the items, drag and drop them inside the pattern. - To remove a specific item, select it, and press Delete. Note that if you are deleting a region or group, all items inside it will be also deleted. Therefore, you may want to drag the items from the region/group before deleting it. - To add a new item, drag it into the desired place in the pattern from the Toolbox area. Drag a Region or Group to use it as a grouping item, or drag an Entry to match something in the target code. You can also use the Dependency property matcher to match and arrange all parts of WPF dependency properties. - To configure the properties of the pattern or an item inside it, select it and modify its properties in the right bottom part: - Display Name - this property available for a pattern and for a matcher entry is only used for your convenience and should describe what is matched by it. - Name - this property of a region specifies how to name the region when it is created. You can use the ${0}parameter in the name to insert the sequence number of the region if the region is spawned according to the Group By option. You can also use named parameters to insert the grouping option in the region name. For example, you can use the ${Access}parameter, which will be replaced with 'private', 'public' etc. in the names of the corresponding regions. Obviously, this parameter makes sense if you use the same value for the 'Group By' property of the region. Valid values for this parameter are the same as the values of the 'Group By' property without spaces. I.e, to insert the name of the implementing interface in the region name, use the ${ImplementsInterface}parameter. - Remove Regions - this property of file and type patterns specifies what to do with existing regions in the matched code. The Except generated value can be used to only remove regions created previously by applying this feature with default patterns. - Priority - this property sets the relative priority of the matcher entry. That is, if some piece of code is matched by several matcher entries, it is moved according to the position of the entry with the highest priority. - Sort By - this property of an entry specifies sorting preferences in case of multiple matching code items. As soon as you select a sorting preference other than None, a Then By clause appears that allows further refinement of the sort order. - Group By - this property of a region or a group specifies whether to spawn regions/groups according to the specified grouping. For example, if Kind is selected as a value, several regions/groups would be created for fields, properties, and other kind of members, if any. As soon as you select a grouping preference other than None, a Then By clause appears that allows further separation of matched code items. - To configure constraints that define how a specific type pattern or a matcher entry matches code items, we switch to the constrains view. To open this view for a type pattern, click the corresponding icon on its header; to open this view for a matcher entry, double-click it. - In the constraints view, the selected item is represented as a container of conditions. To configure these conditions, drag and drop items from the Toolbox area into the edited pattern or entry: - The items in the Logical Containers should be added first as they define how to apply multiple conditions. Names of these containers explain rather clearly how the conditions are related inside these containers. If you add constraints without logical containers, they will be grouped by the And container. - The items in the Constraints group allows you to define what the matching item should or should not be (if wrapped in the Not container). Not that you can use regex expressions in the value of the Name constraint. Drag items from this group into logical containers and configure their properties in the bottom right part. - Drag the items from the Modifiers group to specify which modifiers the target item should or should not have. Configuring file and type layout by editing the source XAML If necessary, you can edit the source XAML that describes the set of file and type patterns. To do so, click XAML in the top of the File Layout page. This view can be also helpful if you want to copy and paste the pattern set. We recommend you, etc. Consider the example below: This XML code matches constructors and sorts them in such way that first go static constructors. Reordering file and type members To apply your file and type layout settings in the desired scope, use code cleanup. You can either run code cleanup with the default profile Default: Full Cleanup or run the cleanup with a custom profile solely targeted at your specific task as described below. To apply file and type layout - Open the Code Cleanup options: ReSharper | Options | Code Editing | Code Cleanup. - Create a new profile as described in the Configuring Code Clenup section. In the Selected profile settings section for the new profile tick the Apply file layout apply file layout: - Set the caret anywhere in the file to apply file layout to the file. - Select one or more items in the Solution Explorer to apply file layout in the files under these nodes and their child items. - Do one of the following: - apply file layout in the selected scope according to your preferences. If you want to apply file layout without opening the Code Cleanup dialog box, you can bind the created profile to the silent cleanup and run it simply by pressing Ctrl+Shift+Alt+F. You can also create a custom cleanup profile that would combine applying file layout
https://www.jetbrains.com/help/resharper/10.0/File_and_Type_Layout.html
CC-MAIN-2018-05
refinedweb
1,958
59.94
When we graduated Loki into a GA release last year, there were more than 137 contributors who already made more than 1,000 contributions to the project. We also added hosted Loki to the lineup of Grafana Cloud offerings after it proved to be stable internally for our ops cluster, storing 40TB and half a trillion log lines each month. There was, however, one persistent problem that kept surfacing, especially for developers who were writing applications in Go: The regex package was slow. Our goal has always been to make Loki not only cost-effective. We want it to be efficient, too, so we decided to tackle this problem. In this blog post, we’re going to dissect what the root cause was behind the speed issue and how the Grafana Labs team found a workaround to improve overall performance in Loki. The problem It’s universally known that the regex package in Go is quite slow. This package is used by Prometheus, Thanos, and basically everyone using Go and regex. And for those who are working with Loki, it’s especially problematic because if you have to search for your logs and apply a regex for each line, one line at a time, then Loki’s performance will be less than ideal. That’s because the Go team created the regex algorithm using linear time, which means there’s a direct correlation between the amount of data inputted and the time required to carry out a function. So the more data that’s ingested, the longer the application takes to process the workload. But that’s not without good reason. The regex in Go was designed with safety as a priority. The algorithm specifically blocks a security attack called the regular expression denial of service (ReDoS) attack, during which an attacker provides a regex that takes an inordinate amount of time to process. That, in turn, causes the program to overload and slow down or shut down altogether. The Go team initially had expected more engineers to use this package for production services, a use case in which the regexp performance is sufficient and the security feature was necessary. But for those who aren’t implementing it in a similar instance, the package can be sluggish. The Go authors have always been aware of the issue (and the complaints), but the trade-off has always made sense: It’s better to have security over speed. The solution Our workaround was inspired by the package itself. There is a syntax sub-package that allows users to parse a regex expression and access the abstract syntax tree. The package leverages simplification, which breaks down the regular expression by replacing it with another combination of expressions. All the while, the original expression remains intact. With that concept in mind, we applied our own regexp simplification in Loki by using byte comparisons. This is possible because we are simply filtering and we don’t need to capture matches. So let’s take a basic example of a filtered expression in Loki such as {foo="bar"} |~ "(DEBUG|WARNING)". If you use the regex package in Go, this will run slowly because you’re matching in your log, for each log line, if there is either a debug or warning label. And for a single query, Loki can traverse millions of log lines. In Loki, a byte comparison would scan logs to see if it contains “debug” or if it contains “warning.” So we actually don’t run a regex expression. We, in fact, bypass that. How? First we use the syntax package to parse the user regex and see if there are ways to run the regex differently. (Regular expressions can be very complex so we didn’t want to do our own parsing. Luckily, the Go engineers made this very easy for us!) If no improvement can be made, then Loki will use the normal regex. But if we can improve upon it and avoid the regex, Loki will run a bytes.Contains, which is less complex to run than a regex. So in the above example, because the filtered expression can be simplified, we don’t need to run a costly regex. Instead we only run two bytes.Contains on the string. Not only does the byte comparison improve the performance of the original package and keep costs down. We do not compromise the original security measure that the Go team implemented because we don’t have to replace the regex package in Loki. The results When running a 24h query range for {namespace="loki-dev"} |~ "foo|bar", the results went from being 11.5s to 1.5s after the regexp simplification was introduced in Loki v1.4.0. Some regexp were slow for line filtering, specially the alternate op such as `{app="foo"} |~ "err|panic"`. I dove into the golang regexp/syntax package and find way to simplify them for line filtering. Result speak for itself: pic.twitter.com/19R0r5QLVR— Cyril Tovena (@Kuqd) February 25, 2020 Overall, for various use cases we saw benchmark improvements ranging from 5x to more than 300x! What’s next One thing we want to do in the future is extract all that work in the PR and create a package that can be used by the whole ecosystem. We want to give anyone who is running a project that leverages filtering and does not require capturing values access to this work as well. We also presented our vision for the future of Loki at GrafanaCONline 2020, highlighting some of the team’s long-term goals and non-goals, what features we would like to add, and the active discussion and plans for the LogQL query language. You can watch the recording of the talk here.
https://grafana.com/blog/2020/06/08/how-a-regex-simplification-in-loki-increased-performance-by-up-to-300x/
CC-MAIN-2021-31
refinedweb
960
61.97
Have you ever wondered how a computer manages the most complex tasks with such efficiency and accuracy? The answer is, with the help of the operating system. It is the operating system that uses hardware resources efficiently to perform various tasks and ultimately makes life easier. At a high level, the OS can be divided into two partsthe first being the kernel and other is the utility programs. Various user space processes ask for system resources such as the CPU, storage, memory, network connectivity, etc, and the kernel services these requests. This column will explore loadable kernel modules in GNU/Linux. The Linux kernel is monolithic, which means that the entire OS runs solely in supervisor mode. Though the kernel is a single process, it consists of various subsystems and each subsystem is responsible for performing certain tasks. Broadly, any kernel performs the following main tasks. Process management: This subsystem handles the process life-cycle. It creates and destroys processes, allowing communication and data sharing between processes through inter-process communication (IPC). Additionally, with the help of the process scheduler, it schedules processes and enables resource sharing. Memory management: This subsystem handles all memory related requests. Available memory is divided into chunks of a fixed size called pages, which are allocated or de-allocated to/from the process, on demand. With the help of the memory management unit (MMU), it maps the process virtual address space to a physical address space and creates the illusion of a contiguous large address space. File system: The GNU/Linux system is heavily dependent on the file system. In GNU/Linux, almost everything is a file. This subsystem handles all storage related requirements like the creation and deletion of files, compression and journaling of data, the organisation of data in a hierarchical manner, and so on. The Linux kernel supports all major file systems including MS Windows NTFS. Device control: Any computer system requires various devices. But to make the devices usable, there should be a device driver and this layer provides that functionality. There are various types of drivers present, like graphics drivers, a Bluetooth driver, audio/video drivers and so on. Networking: Networking is one of the important aspects of any OS. It allows communication and data transfer between hosts. It collects, identifies and transmits network packets. Additionally, it also enables routing functionality. Dynamically loadable kernel modules We often install kernel updates and security patches to make sure our system is up-to-date. In case of MS Windows, a reboot is often required, but this is not always acceptable; for instance, the machine cannot be rebooted if is a production server. Wouldnt it be great if we could add or remove functionality to/from the kernel on-the-fly without a system reboot? The Linux kernel allows dynamic loading and unloading of kernel modules. Any piece of code that can be added to the kernel at runtime is called a kernel module. Modules can be loaded or unloaded while the system is up and running without any interruption. A kernel module is an object code that can be dynamically linked to the running kernel using the insmod command and can be unlinked using the rmmod command. A few useful utilities GNU/Linux provides various user-space utilities that provide useful information about the kernel modules. Let us explore them. lsmod: This command lists the currently loaded kernel modules. This is a very simple program which reads the /proc/modules file and displays its contents in a formatted manner. insmod: This is also a trivial program which inserts a module in the kernel. This command doesnt handle module dependencies. rmmod: As the name suggests, this command is used to unload modules from the kernel. Unloading is done only if the current module is not in use. rmmod also supports the -f or –-force option, which can unload modules forcibly. But this option is extremely dangerous. There is a safer way to remove modules. With the -w or –-wait option, rmmod will isolate the module and wait until the module is no longer used. modinfo: This command displays information about the module that was passed as a command-line argument. If the argument is not a filename, then it searches the /lib/modules/<version> directory for modules. modinfo shows each attribute of the module in the field:value format. Note: <version> is the kernel version. We can obtain it by executing the uname -r command. dmesg: Any user-space program displays its output on the standard output stream, i.e., /dev/stdout but the kernel uses a different methodology. The kernel appends its output to the ring buffer, and by using the dmesg command, we can manage the contents of the ring buffer. Preparing the system Now its time for action. Lets create a development environment. In this section, lets install all the required packages on an RPM-based GNU/Linux distro like CentOS and a Debian-based GNU/Linux distro like Ubuntu. Installing CentOS First install the gcc compiler by executing the following command as a root user: [root]# yum -y install gcc Then install the kernel development packages: [root]# yum -y install kernel-devel Finally, install the make utility: [root]# yum -y install make Installing Ubuntu First install the gcc compiler: [mickey] sudo apt-get install gcc After that, install kernel development packages: [mickey] sudo apt-get install kernel-package And, finally, install the make utility: [mickey] sudo apt-get install make Our first kernel module Our system is ready now. Let us write the first kernel module. Open your favourite text editor and save the file as hello.c with the following contents: #include <linux/kernel.h> #include <linux/module.h> int init_module(void) { printk(KERN_INFO Hello, World !!!\n); return 0; } void cleanup_module(void) { printk(KERN_INFO Exiting ...\n); } MODULE_LICENSE(GPL); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Hello world module.); MODULE_VERSION(1.0); Any module must have at least two functions. The first is initialisation and the second is the clean-up function. In our case, init_module() is the initialisation function and cleanup_module() is the clean-up function. The initialisation function is called as soon as the module is loaded and the clean-up function is called just before unloading the module. MODULE_LICENSE and other macros are self-explanatory. There is a printk() function, the syntax of which is similar to the user-space printf() function. But unlike printf() , it doesnt print messages on a standard output stream; instead, it appends messages into the kernels ring buffer. Each printk() statement comes with a priority. In our example, we used the KERN_INFO priority. Please note that there is no comma (,) between KERN_INFO and the format string. In the absence of explicit priority, DEFAULT_MESSAGE_LOGLEVEL priority will be used. The last statement in init_module() is return 0 which indicates success. The names of the initialisation and clean-up functions are init_module() and cleanup_module() respectively. But with the new kernel (>= 2.3.13) we can use any name for the initialisation and clean-up functions. These old names are still supported for backward compatibility. The kernel provides module_init and module_exit macros, which register initialisation and clean-up functions. Let us rewrite the same module with names of our own choice for initialisation and cleanup functions: #include <linux/kernel.h> #include <linux/module.h> static int __init hello_init(void) { printk(KERN_INFO Hello, World !!!\n); return 0; } static void __exit hello_exit(void) { printk(KERN_INFO Exiting ...\n); } module_init(hello_init); module_exit(hello_exit); MODULE_LICENSE(GPL); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Hello world module.); MODULE_VERSION(1.0); Here, the __init and __exit keywords imply initialisation and clean-up functions, respectively. Compiling and loading the module Now, let us understand the module compilation procedure. To compile a kernel module, we are going to use the kernels build system. Open your favourite text editor and write down the following compilation steps in it, before saving it as Makefile. Please note that the kernel modules hello.c and Makefile must exist in the same directory. obj-m += hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean To build modules, kernel headers are required. The above makefile invokes the kernels build system from the kernels source and finally the kernels makefile invokes our Makefile to compile the module. Now that we have everything to build our module, just execute the make command, and this will compile and create the kernel module named hello.ko: [mickey] $ ls hello.c Makefile [mickey]$ make make -C /lib/modules/2.6.32-358.el6.x86_64/build M=/home/mickey modules make[1]: Entering directory `/usr/src/kernels/2.6.32-358.el6.x86_64 CC [M] /home/mickey/hello.o Building modules, stage 2. MODPOST 1 modules CC /home/mickey/hello.mod.o LD [M] /home/mickey/hello.ko.unsigned NO SIGN [M] /home/mickey/hello.ko make[1]: Leaving directory `/usr/src/kernels/2.6.32-358.el6.x86_64 [mickey]$ ls hello.c hello.ko hello.ko.unsigned hello.mod.c hello.mod.o hello.o Makefile modules.order Module.symvers We have now successfully compiled our first kernel module. Now, let us look at how to load and unload this module in the kernel. Please note that you must have super-user privileges to load/unload kernel modules. To load a module, switch to the super-user mode and execute the insmod command, as shown below: [root]# insmod hello.ko insmod has done its job successfully. But where is the output? It is appended to the kernels ring buffer. So lets verify it by executing the dmesg command: [root]# dmesg Hello, World !!! We can also check whether our module is loaded or not. For this purpose, lets use the lsmod command: [root]# lsmod | grep hello hello 859 0 To unload the module from the kernel, just execute the rmmod command as shown below and check the output of the dmesg command. Now, dmesg shows the message from the clean-up function: [root]# rmmod hello [root]# dmesg Hello, World !!! Exiting ... In this module, we have used a couple of macros, which provide information about the module. The modinfo command displays this information in a nicely formatted fashion: [mickey]$ modinfo hello.ko filename: hello.ko version: 1.0 description: Hello world module. author: Narendra Kangralkar. license: GPL srcversion: 144DCA60AA8E0CFCC9899E3 depends: vermagic: 2.6.32-358.el6.x86_64 SMP mod_unload modversions Finding the PID of a process Let us write one more kernel module to find out the Process ID (PID) of the current process. The kernel stores all process related information in the task_struct structure, which is defined in the <linux/sched.h> header file. It provides a current variable, which is a pointer to the current process. To find out the PID of a current process, just print the value of the current->pid variable. Given below is the complete working code (pid.c): #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> static int __init pid_init(void) { printk(KERN_INFO pid = %d\n, current->pid); return 0; } static void __exit pid_exit(void) { /* Dont do anything */ } module_init(pid_init); module_exit(pid_exit); MODULE_LICENSE(GPL); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Kernel module to find PID.); MODULE_VERSION(1.0); The Makefile is almost the same as the first makefile, with a minor change in the object files name: obj-m += pid.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean Now compile and insert the module and check the output using the dmesg command: [mickey]$ make [root]# insmod pid.ko [root]# dmesg pid = 6730 A module that spans multiple files So far we have explored how to compile a module from a single file. But in a large project, there are several source files for a single module and, sometimes, it is convenient to divide the module into multiple files. Let us understand the procedure of building a module that spans two files. Lets divide the initialization and cleanup functions from the hello.c file into two separate files, namely startup.c and cleanup.c. Given below is the source code for startup.c: #include <linux/kernel.h> #include <linux/module.h> static int __init hello_init(void) { printk(KERN_INFO Function: %s from %s file\n, __func__, __FILE__); return 0; } module_init(hello_init); MODULE_LICENSE(GPL); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Startup module.); MODULE_VERSION(1.0); And cleanup.c will look like this. #include <linux/kernel.h> #include <linux/module.h> static void __exit hello_exit(void) { printk(KERN_INFO Function %s from %s file\n, __func__, __FILE__); } module_exit(hello_exit); MODULE_LICENSE(BSD); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Cleanup module.); MODULE_VERSION(1.1); Now, here is the interesting part — Makefile for these modules: obj-m += final.o final-objs := startup.o cleanup.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean The Makefile is self-explanatory. Here, we are saying: Build the final kernel object by using startup.o and cleanup.o. Let us compile and test the module: [mickey]$ ls cleanup.c Makefile startup.c [mickey]$ make Then, lets display module information using the modinfo command: [mickey]$ modinfo final.ko filename: final.ko version: 1.0 description: Startup module. author: Narendra Kangralkar. license: GPL version: 1.1 description: Cleanup module. author: Narendra Kangralkar. license: BSD srcversion: D808DB9E16AC40D04780E2F depends: vermagic: 2.6.32-358.el6.x86_64 SMP mod_unload modversions Here, the modinfo command shows the version, description, licence and author-related information from each module. Let us load and unload the final.ko module and verify the output: [mickey]$ su - Password: [root]# insmod final.ko [root]# dmesg Function: hello_init from /home/mickey/startup.c file [root]# rmmod final [root]# dmesg Function: hello_init from /home/mickey/startup.c file Function hello_exit from /home/mickey/cleanup.c file Passing command-line arguments to the module In user-space programs, we can easily manage command line arguments with argc/ argv. But to achieve the same functionality through modules, we have to put in more of an effort. To achieve command-line handling in modules, we first need to declare global variables and use the module_param() macro, which is defined in the <linux/moduleparam.h> header file. There is also the MODULE_PARM_DESC() macro which provides descriptions about arguments. Without going into lengthy theoretical discussions, let us write the code: #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> static char *name = Narendra Kangralkar; static long roll_no = 1234; static int total_subjects = 5; static int marks[5] = {80, 75, 83, 95, 87}; module_param(name, charp, 0); MODULE_PARM_DESC(name, Name of the a student); module_param(roll_no, long, 0); MODULE_PARM_DESC(rool_no, Roll number of a student); module_param(total_subjects, int, 0); MODULE_PARM_DESC(total_subjects, Total number of subjects); module_param_array(marks, int, &total_subjects, 0); MODULE_PARM_DESC(marks, Subjectwise marks of a student); static int __init param_init(void) { static int i; printk(KERN_INFO Name : %s\n, name); printk(KERN_INFO Roll no : %ld\n, roll_no); printk(KERN_INFO Subjectwise marks ); for (i = 0; i < total_subjects; ++i) { printk(KERN_INFO Subject-%d = %d\n, i + 1, marks[i]); } return 0; } static void __exit param_exit(void) { /* Dont do anything */ } module_init(param_init); module_exit(param_exit); MODULE_LICENSE(GPL); MODULE_AUTHOR(Narendra Kangralkar.); MODULE_DESCRIPTION(Module with command line arguments.); MODULE_VERSION(1.0); After compilation, first insert the module without any arguments, which display the default values of the variable. But after providing command-line arguments, default values will be overridden. The output below illustrates this: [root]# insmod parameters.ko [root]# dmesg Name : Narendra Kangralkar Roll no : 1234 Subjectwise marks Subject-1 = 80 Subject-2 = 75 Subject-3 = 83 Subject-4 = 95 Subject-5 = 87 [root]# rmmod parameters Now, let us reload module with command-line arguments and verify the output. [root]# insmod ./parameters.ko name=Mickey roll_no=1001 marks=10,20,30,40,50 [root]# dmesg Name : Mickey Roll no : 1001 Subjectwise marks Subject-1 = 10 Subject-2 = 20 Subject-3 = 30 Subject-4 = 40 Subject-5 = 50 If you want to learn more about modules, the Linux kernels source code is the best place to do so. You can download the latest source code from. Additionally, there are a few good books available in the market like Linux Kernel Development (3rd Edition) by Robert Love and Linux Device Drivers (3rd Edition). You can also download the free book from.
http://opensourceforu.com/2015/06/an-introduction-to-the-linux-kernel/
CC-MAIN-2017-13
refinedweb
2,726
50.33
CTags for PHP A Sublime Text 2 plugin that use CTag for cool PHP programming Details Installs - Total 19K - Win 11K - OS X 4K - Linux 4K Readme - Source - raw.githubusercontent.com Sublime CTags PHP This Sublime Text 2 Package provides cool stuff for PHP 5.3+ coding session. Sublime Text 3 support This plugin will NOT work in Sublime Text 3 ! I've made a new plugin which use the built-in index instead of ctags. Take a look at SublimePHPCompanion. This new plugin is even better as it sort the use in your classes. Dependency Obviously, you NEED the CTags plugin for Sublime Text 2. - - Via package control (search for ctag) Installation Search ctagphp in package control and you have done ! Or clone this repo in your Sublime Text 2 Package dir. $ git clone Features Two AWESOME features for the moment ! import_use The first one is 'import use statement'. Just bring your cursor hover a class name, hit the F5 key (default but customizable) and that's it. Based on the current file content, the use statement could be added in : - Below the last use statement - Below the namespace statement (with an empty line between both) - Below the php opening tag (with an empty line between both) import_namespace Just hit the F4 key, it will add the namespace definition based on the absolute filename of the current file. I use a simple trick to determine where the namespace begun, actually the namespace will start at the first CamelCased folder. If a namespace is already declared, the command will shout how crazy you are in the status bar. Warning: This feature require a filename so the command won't work in an unsaved buffer.
https://packagecontrol.io/packages/CTags%20for%20PHP
CC-MAIN-2019-51
refinedweb
284
71.85
Ramblings from the Creator of WilsonDotNet.com Thanks Paul. Your presenation was great and helped me clear up a few issues I was having. Thanks for letting us know baout the source code being released too! Hi, This is my first foray into ASP 2.0 and after following your guide (in Readme.txt) I get the following error: The type or namespace name 'Wilson' could not be found (are you missing a using directive or an assembly reference?) That highlights this line: <add namespace="Wilson.Providers.Framework"/> Do you have any tips on what I'm obviously doing wrong? (I'm using the Visual Web Developer 2005 Express Edition.) Thanks in advance, Jose Hi Jose: My first thought is to ask you if you have compiled / built the solution? If not, then that would certainly be an error that I would expect. Otherwise, I'm not real sure what limitations the Express Edition may have, so that may or may not be part of the problem. One last thought, I removed most of the binaries (dlls) to make the download smaller, but I could send you a version with the compiled binaries to see if that helps if you send me an email. That might help if there are limitations of the Express Edition, but if that's the case you probably aren't really going to be able to do anything this advanced in the first place. This also isn't exactly something basic to be starting with period. Thanks, Paul Wilson One of the most popular features in ASP.NET 2.0 was the introduction of the "provider model" for the Paul Wilson, creator of the popular Wilson OR-Mapper, presented on the Provider Model and custom providers....
http://weblogs.asp.net/pwilson/archive/2006/05/14/446372.aspx
crawl-002
refinedweb
291
72.87
I've looked all over the www, and called a refurb sonic wall vendor, for a power supply for my SW Pro1260e. (The capacitors in my PS are swollen and leaking.) I figured that refurb vendors would surely know where to obtain one. However, the vendor I called said, "When you find out where to get one of these, let me know." The supply is a "custom" unit, in the parlance of the IT world, not a universal PS like I thought it would be. Where did you get the PS you mentioned? Surely there's a source for these things somewhere. My email address is dsetchfield@ruizassoc.com thanks! Dan 19 Replies Feb 14, 2012 at 7:47 UTC Dan. I have an unused spare ‘boxed’ 1260, which takes power from a normal UK supply. All you need is a US mains lead. I can let it go if you are interested. Serial Number 006b13917cc Feb 14, 2012 at 9:38 UTC Thanks for your gracious offer. Actually, I have a working Pro 1260 on the rack, and another just like it (hot spare) on the rack just above it, config'd and ready to go. (We have a small data center). But the last 1260 that failed is in my office (with PS obviously bad), and I figured I'd try to get a PS for it--cheap way to get another spare unit to either keep as a hot spare or to sell. So I don't really need yet another unit. I'm just trying to find the PS somewhere. Thanks for your kind response. --Dan Feb 15, 2012 at 5:10 UTC Is the custom part of it just the connector that connects to the sonicwall? I know my old TZ190 has an odd plug. I would think the power part of it is pretty conventional so if you could find one with the correct voltage and amperage then you could just swap the tips. Not optimal, but if you do it correctly it shouldn't be a big deal. Feb 16, 2012 at 8:43 UTC Right--except that you're envisioning a PS like that of a laptop, etc. This PS is an internal module--inside the Pro 1260 case. It's a 3"x5" "card" that looks like an electronics kit someone put together at home. Apparently, Sonic Wall, like many equipment vendors, goes to "custom" PS vendors, tells them what VA outputs and physical size they need, and the vendor designs and fabricates the several thousand they might need. This PS looks virtually identical to the ones in the small retail scanner/scales I worked on many years ago when I was at NCR (the old National Cash Register Co)--basically non-reworkable power supply modules you discard when they go bad. Except, at NCR, our parts department supplied us with replacement modules. That's all I'm needing here--a replacement module. Feb 16, 2012 at 3:22 UTC OK, so it's totally different than the sonicwalls I've used. They have all had standard power supplies just with odd plugs that plug into the box. Good luck! May 8, 2012 at 10:58 UTC Dan, Did you get anywhere with the replacement PSU. I am in the same position. Our 1260 popped its clogs a couple of days ago and I think the PSU is the culprit. Thanks, Keith May 8, 2012 at 1:43 UTC No luck. But I've had so many other fires to put out in the meantime, I've given up looking. No doubt there's some factory, vendor, or parts department that has any number of these, but it seems to be a fool's errand spending much time looking. Since time really is money, it's better to just buy another refurb, or upgrade to a newer appliance. May 9, 2012 at 3:00 UTC Dan, Yes, we have ordered a new TZ200 anyway but I would have liked to be able to repair the 1260 as it has been a great piece of kit for the 6 years or so since install. Like you said, time is money. I think I will walk away from this one. Cheers, Keith Oct 31, 2012 at 3:07 UTC 1st Post I'm in the same predicament: my 1260 won't boot up. It's either the PS, or the board, and I'm hoping that it's the PS (this modular, custom card Dan described -- I'm looking at the thing right now). I'm going to start with a silly question: has anyone tried replacing the fuse in this PS? Mine looks okay, but it would be the absolute cheapest replacement cost I also see two drops of some yellowish-brown goop on top of two capacitors (2200 microF, 16V). If that means they're leaking, then I could always try replacing just those two components with a soldering iron. Heck, I could replace all four of them and the fuse for less than $10. Please let me know! Oct 31, 2012 at 3:27 UTC UPDATE: The part in question is a Fairway VA4005, Rev 1.1. I'm awaiting a quote from Industrial Partner: http:/ Dec 24, 2012 at 2:44 UTC 1st Post Hi All, I have the same problem like Beowulf on my Sonicwall pro 1260. Do you receive the quote from seller? Have you try to replace those capacitor? Can you please kindly let me know any update? Thank you. Jan 5, 2013 at 1:29 UTC Hello, I also had the same probelm I too am waiting on a quote from industrial partner.. I noticed the capacitors on C13 , C14, C15, and C16 were buldging. C15 leaked onto a resistor marked R22 on the board. Because the stuff was all over the resistor i could not make out the color stripes, could any of you tell me what it is? I suppose i can try to solder in new components and see what happens. Mar 18, 2013 at 2:49 UTC 1st Post Hey, Did anyone ever find a supplier for the Pro 1260 power supplies? I have a couple that were removed from service at customer sites that I would like to fix up for home / lab use, but finding a replacement PSU has proven to be exceedingly difficult. I'd even have a go at replacing the components myself if someone could point me to a convenient source for the pieces. Thanks in advance for any help you may be able to provide. Jan 31, 2014 at 12:11 UTC 1st Post So noone has found where to buy the power supply for 1260 yet? I have two 1260 in need of power supply as well... Jun 4, 2014 at 4:41 UTC 1st Post I had a Sonicwall 1260 blow its VA4005 power supply board today. Big client, can't have the downtime, nothing suitable around for immediate replacement. Needed to buy some time. Downloaded the VA4005 data sheet. It's basically just a 5 volt 8 amp DC power supply. The 6 wire cable that goes from the PS to the Mainboard is very simple. 3 of the wires are +5 and the other 3 are voltage return (ground). I broke out the soldering iron and whipped up a cable that taps 5 volts from a molex connector in a computer and feeds to that connector. I interfaced to the sonicwall original 6 wire cable without modifying it by tinning the ends of my wires and plugging them into the connector then securing them. Hot glue works good and is removable. Some heat shrink to pretty it up then just plugged it into the sonicwall mainboard. There's nothing pretty about it but it worked great. Bought me some time to solve the problem correctly. Client understands and is just glad to be functional again. Jul 29, 2014 at 11:17 UTC Just reporting back. The power supply I purchased was indeed a direct swap unit other than one simple modification and the Sonicwall is back up an running for a quite awhile now. The new unit is a Mean Well PS-45-5 and seems to be a direct bolt in replacement for the old Fairway VA4005 power supply. It is available online through various sites that didn't list availability or ship time so I picked mine up through ebay to the tune of under $30. The new power supply has the same connectors as the old one except the AC input is reversed. I don't know if that actually matters or not but it was easily resolved by pulling the plastic piece off the connector and reversing it. If interested I have put together a showing all the details. I also put together a second video going over some past sonicwall power problems that I have encountered in case the issue is not your power supply. Best Wishes. Jul 31, 2014 at 10:18 UTC Nice one, well done rbc2. Jul 31, 2014 at 2:38 UTC Excellent find! Thank you for your tenacity in tracking down an answer to this problem. I ordered one of these power supplies from Jameco Electronics. I'm hoping that it does the trick for my dead PRO1260! Aug 2, 2014 at 11:27 UTC UPDATE: My Mean Well PS-45-5 showed up today. As rbc2 said, the only thing that needed doing was to reverse the plastic "key" on the connector for the power switch. Some gentle insistence with a pair of pliers pulled it off of the two square pins onto which it had been seated (without glue). Spin it around, and then press it back on. The connector from the power switch fits perfectly, as does the 6-pin connector running to the motherboard. The firewall started right up and is running like a champ for all of $17.43, shipped. Thanks, rbc2! This discussion has been inactive for over a year. You may get a better answer to your question by starting a new discussion.
https://community.spiceworks.com/topic/198405-need-power-supply-for-sonic-wall-pro-1260e
CC-MAIN-2017-26
refinedweb
1,689
80.41
You will make a menu-driven program in this tutorial. Using a while loop, you will learn how to add a menu to a C# console application. This technique helps your users navigate your app, and it enables you to create more robust C# programs. If you have been following our beginners tutorial series, you have written simple applications that highlight some of the basic functionality of C# and .NET Core. In this tutorial, we will merge some of these examples into a non-trivial application using some of the techniques you have already learned. Pseudo-code for Console Menu In short, our menu-driven console application will use a While Loop that will call a Main Menu method. The Main Menu method will print all menu options to the console and wait for the user to choose an option. Once the user selects an option, the program will execute the code block pertaining to the selected option. Here's how it might look as a pseudo-code: Main() { Loop { MainMenu(); } } MainMenu() { print "option 1"; print "option 2"; ... wait user input; if option1 do something1; if option2 do something2; } The Main() Method In the previous two tutorials, we learned some useful C# string manipulation techniques - reverse string, and remove whitespace. In this tutorial, our menu-driven console application will use some of the methods we wrote in the previous tutorials and combine them into a useful, fully functional string manipulation program. We will begin with the static void Main() method. We want the application's menu to appear until the user chooses to exit the program. Add the following code: static void Main(string[] args) { bool showMenu = true; while (showMenu) { showMenu = MainMenu(); } } On Line 12, the MainMenu() is invoked inside the while loop. This method will return a bool value, and the loop will iterate as long as that value is true. If the user chooses to exit the program, the MainMenu() method should return a false value. When this happens, the loop will stop and the application will close. Building the Console Menu The MainMenu() method should first print the menu options to the console so the user is able to make a selection. Next, it will read the user's response and determine which option was selected. Based on the option that was selected, the program will call the appropriate method.; } } On Line 17, I am using Console.Clear() to ensure the menu will be printed onto a blank console screen. This will be important for tidiness, because other methods in my console application will also write to the console window. The menu options themselves are printed on Lines 18-22. On Lines 24-37, I am using a switch statement. The switch-case construct is a good alternative to using multiple if-else statements. It checks an expression against a number of possible values. In this case, we are reading what the user entered to determine whether they selected option "1," "2," or "3." Based on the value the user enters, we will invoke either the ReverseString() method or the RemoveWhitespace() method. If the user selects Option 3, the MainMenu() method will return false (Line 33) and the program will terminate. The default case will catch situations where the user enters values other than 1, 2, or 3. In this case, the method will return true and the menu will reset allowing the user to try again. A Complete Example Now, we will simply add the [ReverseString()]( and [RemoveWhitespace()]( methods from our previous tutorials and display the results to the user. Here is our complete String Manipulation program: using System; namespace StringManipulation { class Program { static void Main(string[] args) { bool showMenu = true; while (showMenu) { showMenu = MainMenu(); } }; } } private static string CaptureInput() { Console.Write("Enter the string you want to modify: "); return Console.ReadLine(); } private static void ReverseString() { Console.Clear(); Console.WriteLine("Reverse String"); char[] charArray = CaptureInput().ToCharArray(); Array.Reverse(charArray); DisplayResult(String.Concat(charArray)); } private static void RemoveWhitespace() { Console.Clear(); Console.WriteLine("Remove Whitespace"); DisplayResult(CaptureInput().Replace(" ", "")); } private static void DisplayResult(string message) { Console.WriteLine($"\r\nYour modified string is: {message}"); Console.Write("\r\nPress Enter to return to Main Menu"); Console.ReadLine(); } } } The Bottom Line In this tutorial, you learned how to add a menu to your C# console application. You created a method to display a menu and called that method from inside a while loop. You processed the user's selection and triggered the relevant methods. Finally, you returned a boolean value to determine whether to continue to show the menu. This technique allows you to create more complicated console programs while still maintaining a user-friendly interface. Your end users will be able to easily navigate your application and find the features they need. What kind of programs will you create with
https://wellsb.com/csharp/beginners/create-menu-csharp-console-application/
CC-MAIN-2022-21
refinedweb
798
55.84
I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work either. from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string In Python, lists are indexed with integers ranging from 0 to 1 less than the length of the list. E.g., a list with 10 items in it would have indexes from 0 to 9. Your call to randint() attempts to get indexes from zero to the full length of the list, which will cause this exception. Change it to: for i in range(28): random_string = random_string + take_from[randint (0,len(take_from)-1)]
https://codedump.io/share/zFI0OAEDoF61/1/lndexerror-list-index-out-of-range
CC-MAIN-2017-17
refinedweb
182
75.44
This page is likely outdated (last edited on 16 Apr 2009). Visit the new documentation for updated content. Continuations Starting with Mono 2.6 the Mono runtime supports a continuation framework that allows for a number of high-level abstractions like co-routines and cooperative multi-threading to be implemented on top of it. The API is contained in the Mono.Tasklets assemblies, and it is the Mono-team supported mechanism for doing continuations, microthreading and coroutines in the ISO CLI. It is based on Tomi Valkeinen’s excellent work on co-routines for Mono. Unlike the work that we typically do in Mono which is pure C# and will work out of the box in .NET (even our Mono.SIMD code will work on .NET, it will just run a lot slower) Mono.Tasklets requires changes to the VM that are not portable to other ISO CLI implementations. An introduction that describes various frameworks and the evolution of the Mono.Tasklet.Continuation framework is available in the announcement post in Miguel’s blog. That post also discusses some scenarios where continuations and co-routines are useful. The API The Mono.Tasklet.Continuation is based on Tomi’s Microthreading library, but it only provides the core primitive: the continuation. None of the high-level features from Tomi’s library are included. This is the API: public class Continuation { public Continuation (); public void Mark (); public int Store (int state); public void Restore (int state); } When you call Store the current state of execution is recorded and it is possible to go back to this state by invoking Restore. The caller to Store tells whether it is the initial store or a restore point based on the result from Store: var c = new Continuation (); ... switch (c.Store (0)){ case 0: // First invocation case 1: // Restored from the point ahead. } ... // Jump back to the switch statement. c.Restore (1); Tomi implemented a Microthreading library on top of this abstraction, this library has been ported to Mono.Tasklets.Continuation.
http://www.mono-project.com/archived/continuations/
CC-MAIN-2014-41
refinedweb
335
57.67
Name: [002] Ian Ozsvald Member: 127 months Authored: 181 videos Description: I am the co-founder of ShowMeDo (see), author of `The Screencasting Handbook <>`_ and the founder of the professional screencast production company `ProCasts <>`_: .. image:: ... Refactoring with functions and doc strings [ID:249] (8/17) in series: Python 101 - easygui and csv video tutorial by Ian Ozsvald, added 05/07 Name: [002] Ian Ozsvald Member: 127. import csv import easygui def getFileAndPath(): "Get fully-qualified path to the csv file" # get the file-name fileAndPath = getFileAndPath() print fileAndPath # read the CSV file linesInCSV = getLinesInCSVFile(fileAndPath) print linesInCSV print print "Headings:",linesInCSV[0] for n in range(1,4): print linesInCSV[n] - python - beginners - tutorials - beginner_programming - programs - code - time - running - graphics - application - files - make - screencasts - development - user - work - builds - IDE - useful - learning - functions - modules - programmers - good - read - interfaces - values - problem - debugging - wing - docs - nosetests - messages - wingware - complete - easygui - keep - fully-worked - documentation - csv - reviews - understanding - jobs - exceptions - strings - refactoring - test-driven - comma-separated-values Got any questions? Get answers in the ShowMeDo Learners Google Group. Video statistics: - Video's rank shown in the most popular listing - Video plays: 0 (since July 30th) - Plays in last week: 0 - Published:<< You have Nicely transitioned to good coding style. Thanks Might change last line from for n in range(1,4): to for n in range(1,len(linesInCSV)): for a bit more robustness. (My two line CSV caused an error.) Refactoring with functions and doc strings (8/17) 2:30 linesInCSV.append(row) 3:40 print linesInCSV 4:20 n in range(1,4) gives n = 1, 2, 3 5:30 print (alone on line) prints blank line 6:40 print "I am here" or "here1" "here2" Great episode!! Hi Ian great stuff easy enough to follow so far. now that I have to work with real big files with more than 100.000 rows problems arise. do you have an idea how to handle csv files that big not only reading them instead do some mathematical processing with single variables in the rows any videos here around? greetings ali Been in and out of learning Python for sometime now...this is certainly reminding me of why I enjoyed it in the first place...can't wait to keep increasing my python-fu through these lessons... Also helps to see that even the top programmers still use print "iam here" so the y know wherer they are in the procedures...thought that was just a cheap way i had left over from previous expinexperience, but I guess it works!! Good Stuff! Another simple but important lesson. It's a trip how indenting the code is so important to the script running properly. Personally I think that's a good thing. Makes you write more readable code right from the start. I'm using DrPython for my ide by the way Thanks Great series, and only up to #8. Love the way each video builds on the previous. Review of Refactoring with functions and doc strings I am enjoying this series. Good stuff. Assuming you mean functions rather than linear blocks of code, the answer is that functions (and classes) make code more reusable, testable and readable. You can find some more benefits here: Ian. Great video. I am, just like you said, not really a programmer, but someone very interested in learning. I work with programmers all the time, and they want to convert all their code to functions, what is the advantage of doing that? Hi labuzz - great, glad you're enjoying the series. The 'hero01' task would be a great idea to test how much you've learned, it would need some techniques that are beyond what's covered in this series though so you'll have to play around. Good luck with that little challenge :-) Ian. hi there, I am just starting to learn python ( I have a little bit of knowkledge in C...) and your videos are welcome (btw I am a CG artist working with 3d softwares )! I like the idea -> print "I am here" for debugging. It would be cool based on this idea to be able to print maybe something like this: ////////////////////HERE01//////////////////////// BUT with the complete line filled with the character / and the HERE centered. Maybe also the 01 should be incremented each time you have a new reference ( refcount based on a book that I am reading -> core python programming ) to this object. Also all this "#define" should be in another module. I have not see the next videos yet. tky for your work. Very nice, being able to print the source code. Hi Horst. I have added the original CSV file to the second video in this series (the one where the CSV file is written): Ian. Nice jobs introducing those functions. Suggestion: link to a wiki or a place where i can download the original csv-file that you used. Thanks, good to know. 'rb' means read-binary. 'r' by itself means read as text. You can use 'b' as a modifier for reading and writing. More information in Section 7.2 here: In this context we open the file for reading as binary because the end-of-line characters are handled differently on Windows, Mac and *nix. The csv reader needs Binary-mode to handle them correctly. Ian. What does the "rb" do on the line: reader = csv.reader(open(fileAndPath, "rb")) ?
http://showmedo.com/videotutorials/video?name=910070
CC-MAIN-2016-26
refinedweb
903
71.85
Up to [cvs.NetBSD.org] / src / lib / libc / gen Request diff between arbitrary revisions Default branch: MAIN Revision 1.15.8.1 / (download) - annotate - [select for diffs], Wed Aug 20 00:02:14 2014 UTC (15 months ago) by tls Branch: tls-maxphys Changes since 1.15: +19 -36 lines Diff to previous 1.15 (colored) next main 1.16 (colored) Rebase to HEAD as of a few days ago. Revision 1.15.2.1 / (download) - annotate - [select for diffs], Thu May 22 11:36:52 2014 UTC (18 months ago) by yamt Branch: yamt-pagecache Changes since 1.15: +19 -36 lines Diff to previous 1.15 (colored) next main 1.16 (colored) sync with head. for a reference, the tree before this commit was tagged as yamt-pagecache-tag8. this commit was splitted into small chunks to avoid a limitation of cvs. ("Protocol error: too many arguments") Revision 1.16 / (download) - annotate - [select for diffs], Thu Jan 16 17:21:38 2014 UTC (22.15: +19 -36 lines Diff to previous 1.15 (colored) Add the {v,}{err,warn}c flavors, from FreeBSD. Revision 1.15 / (download) - annotate - [select for diffs], Sun Jul 17 20:54:34 2011 UTC (4 years, 4.14: +3 -3 lines Diff to previous 1.14 .14 / (download) - annotate - [select for diffs], Mon Jun 18 14:13:54 2007 UTC (8 years, 5 01:44:09 2005 UTC (10 -8 lines Diff to previous 1.12 (colored) compat core reorg. Revision 1.12 / (download) - annotate - [select for diffs], Mon Oct 27 02:17:18 2003 UTC (12 years, 1 month: +6 -5 lines Diff to previous 1.11 .11 / (download) - annotate - [select for diffs], Thu Aug 7 16:43:00 2003 UTC (12 years, 3 months ago) by agc Branch: MAIN Changes since 1.10: +3 -7 lines Diff to previous 1.10 (colored) Move UCB-licensed code from 4-clause to 3-clause licence. Patches provided by Joel Baker in PR 22280, verified by myself. Revision 1.6.2.3 / (download) - annotate - [select for diffs], Fri Jun 21 18:18:12 2002 UTC (13 years, 5 months ago) by nathanw Branch: nathanw_sa CVS Tags: nathanw_sa_end Changes since 1.6.2.2: +3 -8 lines Diff to previous 1.6.2.2 (colored) next main 1.7 (colored) Catch up to -current. Revision 1.10 / (download) - annotate - [select for diffs], Sun May 26 14:03:20 2002 UTC (13 years, 6 months ago) by wiz Branch: MAIN CVS Tags: nathanw_sa_before_merge, nathanw_sa_base, fvdl_fs64_base Changes since 1.9: +3 -8 lines Diff to previous 1.9 (colored) __STDC__ is always defined on NetBSD. Revision 1.6.2.2 / (download) - annotate - [select for diffs], Fri Mar 22 20:42:14 2002 UTC (13 years, 8 months ago) by nathanw Branch: nathanw_sa Changes since 1.6.2.1: +2 -2 lines Diff to previous 1.6.2.1 (colored) Catch up to -current. Revision 1.6.2.1 / (download) - annotate - [select for diffs], Fri Mar 8 21:35:20 2002 UTC (13 years, 8 months ago) by nathanw Branch: nathanw_sa Changes since 1.6: +5 -2 lines Diff to previous 1.6 (colored) Catch up to -current. Revision 1.9 / (download) - annotate - [select for diffs], Thu Jan 31 22:43:38 2002 UTC (13 years, 9 months ago) by tv.8: +3 -4 lines Diff to previous 1.8 .8 / (download) - annotate - [select for diffs], Mon Jan 28 23:01:43 2002 UTC (13 years, 9 months ago) by tv Branch: MAIN Changes since 1.7: +5 -3 lines Diff to previous 1.7 (colored) Fix previous to actually include config.h. Revision 1.7 / (download) - annotate - [select for diffs], Mon Jan 28 22:45:28 2002 UTC (13 years, 9 months ago) by tv Branch: MAIN Changes since 1.6: +4 -2 lines Diff to previous 1.6 (colored) Make compilable from src/tools/compat. Revision 1.6 / (download) - annotate - [select for diffs], Mon Feb 19 22:22:16 2001 UTC (14 years, 9 months ago) by cgd Branch: MAIN Branch point for: nathanw_sa Changes since 1.5: +3 -5 lines Diff to previous 1.5 (colored) convert from __progname to getprogname() Revision 1.5 / (download) - annotate - [select for diffs], Sat Dec 30 16:27:33 2000 UTC (14 years, 10 months ago) by martin Branch: MAIN Changes since 1.4: +3 -3 lines Diff to previous 1.4 (colored) Be consistent with argument types vs. prototype; use _BSD_VA_LIST_ as the argument, instead of va_list. Might not make a difference on most ports, depending on toolchain/MD typedefs. Does make a difference on sparc64, where it wouldn't compile otherwise. Revision 1.4 / (download) - annotate - [select for diffs], Tue Aug 17 03:47:40 1999 UTC (16 years, 3.3: +6 -2 lines Diff to previous 1.3 (colored) Make some needed weak aliases. Revision 1.3 / (download) - annotate - [select for diffs], Thu Jul 17 21:33:23 1997 UTC (18 years, 4 19:42:13 1997 UTC (18 years, 4 months ago) by christos Branch: MAIN Changes since 1.1: +4 -2 lines Diff to previous 1.1 (colored) Fix RCSID's Use "namespace.h" Revision 1.1.2.1 / (download) - annotate - [select for diffs], Mon Sep 16 18:40:40 1996 UTC (19 years, 2 months ago) by jtc Branch: ivory_soap2 Changes since 1.1: +8 -3 lines Diff to previous 1.1 (colored) next main 1.2 (colored) snapshot namespace cleanup Revision 1.1 / (download) - annotate - [select for diffs], Mon Apr 15 23:45:35 1996 UTC (19 years, 7 months.
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gen/verr.c
CC-MAIN-2015-48
refinedweb
928
76.42
>> largest good number in the divisors of given number N in C++ In this problem, we are given a number N. Our task is to find the largest good number in the divisors of given number N. A good number is a number in which every digit is larger than the sum of digits of its right (all less significant bits than it). For example, 732 is a good number, 7> 3+2 and 3>2. Let's take an example to understand the problem, Input : N = 15 Output : 15 Explanation − Divisors of 15 : 1, 3, 5, 15. Solution Approach A simple solution to the problem is by finding all the divisors of N. And they find the largest good number which is extracted as a product of all prime divisors of the number. Example Program to illustrate the working of our solution #include <bits/stdc++.h> using namespace std; int findLargestGoodNumber(int n){ vector<int> primeFactors; int x = n; for (int i = 2; i * i <= n; i++) { if (x % i == 0) { primeFactors.push_back(i); while (x % i == 0) x /= i; } } if (x > 1) primeFactors.push_back(x); int goodNumber = 1; for (int i = 0; i < primeFactors.size(); i++) goodNumber = goodNumber * primeFactors[i]; return goodNumber; } int main(){ int n = 28; cout<<"The largest good Number in divisor of "<<n<<" is "<<findLargestGoodNumber(n); return 0; } Example The largest good Number in divisor of 28 is 14 - Related Questions & Answers - Find the number of divisors of all numbers in the range [1, n] in C++ - Count the number of common divisors of the given strings in C++ - Find the Largest number with given number of digits and sum of digits in C++ - Find sum of divisors of all the divisors of a natural number in C++ - First triangular number whose number of divisors exceeds N in C++ - Find largest sum of digits in all divisors of n in C++ - How to find the n number of largest values in an R vector? - Find the largest palindrome number made from the product of two n digit numbers in JavaScript - Find the largest number in a Java array. - Find the largest number with n set and m unset bits in C++ - Find the largest number that can be formed with the given digits in C++ - Largest N digit number divisible by given three numbers in C++ - Program to find out the sum of the number of divisor of the divisors in Python - Find number from its divisors in C++ - Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++ Advertisements
https://www.tutorialspoint.com/find-the-largest-good-number-in-the-divisors-of-given-number-n-in-cplusplus
CC-MAIN-2022-33
refinedweb
438
57.84
This is probably easy stuff for most of you guys but have tried to have this working for the past hour and it's not working. I basicly have made my own button which is a movieclip. Inside the movieclip on the normal/roll off state i've put a dynamic textfieldwith instance name "textbtn" my button is supposed to span 2 frames on my mainstage, thought is need to say something different in each frame. Sofar I have this inside the movieclip on Frame 1: textbtn.text = MovieClip(parent).buttonText; on my mainstage in frame1 I have:"); } function buttonRollOver(event:MouseEvent):void{ back_btn.gotoAndStop("over"); } function buttonClick(event:MouseEvent):void{ back_btn.gotoAndStop("click"); gotoAndStop("frontpage2"); } var buttonText = "this is frame1"; on my mainstage in frame2 I have: buttonText = "this is frame2"; sorry on my mainstage frame2 I have the following: back_btn.addEventListener(MouseEvent.MOUSE_OVER, buttonRollOver2); back_btn.addEventListener(MouseEvent.MOUSE_OUT, buttonRollOut2); back_btn.addEventListener(MouseEvent.CLICK, buttonClick2); function buttonRollOut2(event:MouseEvent):void{ back_btn.gotoAndStop("off"); } function buttonRollOver2(event:MouseEvent):void{ back_btn.gotoAndStop("over"); } function buttonClick2(event:MouseEvent):void{ back_btn.gotoAndStop("click"); gotoAndStop("frontpage2"); } buttonText = "this is frame2"; you'll need to execute: textbtn.text = MovieClip(parent).buttonText; each time you want to update your textfield's text property. I Did this instead"); var buttonText = "this is frame1"; } function buttonRollOver(event:MouseEvent):void{ back_btn.gotoAndStop("over"); } function buttonClick(event:MouseEvent):void{ back_btn.gotoAndStop("click"); gotoAndStop("frontpage2"); } But gives me an error: TypeError: Error #2007: Parameter text must be non-null. at flash.text::TextField/set text() at having2galleriestesttext_fla::namebutton_17/frame1()[having2galleries testtext_fla.namebutton_17::frame1:5] at flash.display::MovieClip/gotoAndStop() at having2galleriestesttext_fla::MainTimeline/buttonRollOut()[having2gal leriestesttext_fla.MainTimeline::frame3:24] frame 1 line 5 is inside my movie clip button. textbtn.text = MovieClip(parent).buttonText; And Frame 3:24 is my inside my "buttonRollOut" function: back_btn.gotoAndStop("off"); I think you're unnecessarily complexifying things. One good practice is not to litter the timeline inside movieclips with code. When you want to go find some code to adjust something you may have to traverse movieclips several levels deep to get at the code in some frame. It becomes unweildly very quickly. If you want to use the timeline, I would register the event listeners and also set the text of the button from the root timeline. I also would not use "frame labels" as they're very antiquated although usable. To make your buttons I would make a movieclip (setting the base class of the clip to flash.display.Sprite for optimization) and include 3 layers. layer 1 background, layer 2 roll, layer 3 text. I don't see any "on" state mentioned in your code so I left that out. The roll or 'selected' and 'textfield' layers should have instance names so you can access them. For instance I'd name the selected state graphic to selected_mc and the TextField to text_txt. If your button was named as you said back_btn then the code would look like this, remembering that the event passes a target property: back_btn.addEventListener(MouseEvent.MOUSE_OVER, buttonRollOver); back_btn.addEventListener(MouseEvent.MOUSE_OUT, buttonRollOut); back_btn.addEventListener(MouseEvent.CLICK, buttonClick); Sprite(back_btn.getChildByName('selected_mc')).visible = false; // make sure the initial selected state is invisible function buttonRollOut(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).visible = false; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).text = 'roll off'; // change to the roll off text } function buttonRollOver(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).visible = true; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).text = 'roll on'; // change to the roll on text } function buttonClick(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).visible = true; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).text = 'selected text'; // change to the selected text gotoAndStop("frontpage2"); } TextField(back_btn.getChildByName('text_txt')).text = 'start text'; // change to the starting text of the button The display list returns DisplayObject and DisplayObjectContainer so you always need to wrap things with the 'type' they are to access them properly. That's why I have Sprite() and TextField() wrapped around specific things. Doing that gives you access to their settings. I mean: this is just beautiful... no more error messages, just 2 questions: in my second gallery I've done the following: back_btn.addEventListener(MouseEvent.MOUSE_OVER, buttonRollOver2); back_btn.addEventListener(MouseEvent.MOUSE_OUT, buttonRollOut2); back_btn.addEventListener(MouseEvent.CLICK, buttonClick2); Sprite(back_btn.getChildByName('selected_mc')).visible = false; // make sure the initial selected state is invisible function buttonRollOut2(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).vis ible = false; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).tex t = 'gallery1'; // change to the roll off text } function buttonRollOver2(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).vis ible = true; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).tex t = 'back'; // change to the roll on text } function buttonClick2(event:MouseEvent):void{ Sprite(Sprite(event.currentTarget).getChildByName('selected_mc')).vis ible = true; TextField(Sprite(event.currentTarget).getChildByName('text_txt')).tex t = 'back'; // change to the selected text gotoAndStop("frontpage2"); } TextField(back_btn.getChildByName('text_txt')).text = 'gallery1'; // change to the starting text of the button but the button first shows when the mouse rolls over..? In my dynamic textfield aka. "text_txt" only "gallery" and the letter "A" appears - I've tried to make the text field bigger, but still the samme, is there somewhere I have forgot something..? forgot to embed font... thank you so much - it works perfect I'm not quite sure I follow but are you saying that you don't want the button to show up but it is? The roll is setting the visible property on the selected state so that will fire off every time you roll over it. If the buttons are not supposed to show you should just initially set the .visible property of the entire button to false to assure it won't show up. You should also set the mouseEnabled property to false (and perhaps useHandCursor to false) so the user can't click it until you desire them to. edit: Ah ok, you're welcome. Hi Sinious, similar challenge here... I have a dynamic text field which currently works fine on the stage. (see code below). When I covert this field to a symbol movie clip, I can't seem to find the correct AS3 code to pass the text into the movie clip. I tried this without success; dynamic test field name = a_field movie clip instance name = a_mc AS3 code: _root(a_mc.a_field); ~ ~ below is the current code which works fine prior to converting the dynamic text field to a movie clip; CS5.5 Flash AS3 import flash.netURLLoader; var xmlData:XML = new XML(); var the URL_ur:URLRequest = new URLRequest("fieldinput.xml"); var loader_ur:URLLoader = new URLLoader(theURL_ur); loader_ur.addEventListener("complete", fileLoaded); function fileLoaded(e,Event):void { xmlData = XML(loader_ur.data); a_field.text = xmlData.a_text; } side note.... within these forums, is there a way to insert one's code rather than retyping? Thanks in advance for your time and guidance. D- How you keep your references is completely up to you. If you never made a reference to the textfield or the movieclip (as a class variable or directly in a timeline script or such) then you'll have trouble accessing it. This is AS2, it no longer works in as3: _root I presume you're doing this in a frame script. I also presume you put a_mc and a_field in a frame manually by dragging it out of the library and onto the timeline. First thing to do is make sure you have an instance name specified. You mtnioned you set up a_mc and a_field. Those need to be instance names and not the name of them in the library. Whatever you name them in the library is meaningless. Once you drag them into your timeline, click it and look at your properties panel. The first textbox is the instance name. Those must be set properly for this to work. Here, I just keep re-using this screenshot I made to point out instance name which has nothing to do with your project but you get the idea: Make absolutely sure you gave them names. Then you need to always "type cast" which is a pain in the *** but is necessary. So for example you added correct instance names. You can literally: TextField(a_mc.getChildByName('a_field')).text = XML(loader_ur.data).toString(); Thanks for your help. I inserted your script within the "function" noted in Post #9... with a host of complier errors. While posting it out side the "function" with both complier & output errors..... Does the MovieClip " a_mc " have to be declared first? a_mc = new MovieClip(); var a_mc:MovieClip; ..... I tried this with only further errors...... ~ ~ ~ The script in Post #9 works fine until I change the textfield to Dynamic... If there is more AS3 required I would welcome your ideas..... (all the code thus far is what is in Post #9 ) At a loss.... Thanks again D- If you do not put something on the timeline with the "Instance Name" (refer to graphic) as a_mc, then yes it will need to be created before you can use it. Otherwise no, you can directly use it if you put it on the timline. e.g. you clicked in a frame, clicked on the text tool, set it to dynamic text and had drawn a text box. Afterwards you named the text box instance something. You can then use that instance name directly in actionscript code. However you did say a_mc and referred to it as a movieclip. So if that movieclip contained a dynamic text field, you'd need to go in a_mc and make sure the textfield had an instance name as well. So lets say you have a movieclip on your timeline with the INSTANCE NAME of a_mc. Lets say inside that clip you had a textfield with the INSTANCE NAME of a_field. You could do this to dump the XML into it: function fileLoaded(e:Event):void { TextField(a_mc.getChildByName('a_field')).text = e.target.data; }} And you can just paste code in here really, although sometimes it comes out as tables and other weird stuff. Most of us actualy use the "HTML" button in the upper right and add in something like <pre> or <blockquote> or other tags to help make the code easier to read. Do note the reason I put TextField() around the code above is because any time you request to get a child by its instance name (getChildByName()) it returns a generic "DisplayObject". It's really annoying that the method doesn't sense the original type of the object it returns and generically returns a "DisplayObject" but that is what it does. So by putting TextField() around it I "cast" it back into what I know it should be, a TextField class. Therefore the .text() method will be available. Just a side note... Sinious, First of all, I greatly appreciate all the details and theory behind how & why the code works. You coach the way I learn.. Thanks !! Yes, I do have a Movie clip on the timeline (instance; a_mc) and within it, a dynamic text field (instance: a_field). Before I test the script, I would welcome a bit of clarity; At the end of your script above, you reference e.target.data. With my current external text source the XML file (fieldinput.xml), will your script access this exteranal file or do I use loader_ur.data as noted in my original "function fileLoaded..." in post #9 ? Thanks again for your time and assistance. D- The function fileLoaded is called by your XML loader telling it that it successfully parsed the XML. Once that happens, all the data in the XML is included in the event, which has the variable name of 'e'. So e.target refers directly to the loader that loaded the XML in the first place. So it's exactly like saying loader_ur.data to say e.target.data. You don't really need to keep a reference to loader_ur because the data is sent in the event. This is typically why people use the e.target.data approach. You create a loader in the middle of a function. You know at the end of that functions life the variable is garbage collected. However until the listener fires off, it still exists. Once the listener fires off after successfully loading the document people don't typically have a global variable (like loader_ur) to reference at all. They just refer to e.target to access it. So they access the loaders XML using e.target.data. After that the loader is removed in the next garbage collection sweep. You never really needed to keep loader_ur around at all. It just takes up extra memory. Great..... again, this helps a lot with a thorough understanding. I look forward to testing the script this evening... Many thanks D- You're welcome and good luck I you have a moment, I have one other challenge I am working on. (see forum re: "FlashVars pass field text to SWF") In this forum, I have been working with some great folks teaching me how to interface a SWF (RMA) which has been loaded into a PDF. Here, I am using an Acrobat form field to interface with the "said" dynamic text field we've been working with above. The last piece of my challenge is to get my AS3 script written properly to receive the text data sent from the PDF. If you are aware of any examples of this (PDF to SWF:RMA) project both AcroJS and AS3 scripts I'd appreciate a link or two.... Thanks again D- I think I already posted in that link (I don't have the URL to atm). I mentioned to show the PDF in a StageWebView instance and then it was made clear there was some acrobat scripting syntax that I wasn't familiar with. There were links mentioned that deconstruct PDFs and let you access things inside them but displaying a PDF and accessing data from it at the same time is another level of difficulty. Most APIs either just let you display the PDF or let you read its guts and reconstruct it. Reconstructing is what you appear to want so I'd go that route. It's a lot of work but it lets you convert an input from a PDF into an actionscript input that looks identical (when styled to do so) so you can access the data that way. Otherwise this is not at all someone new to actionscript should be approaching. It's not "easy". Agreed, A novice to AS3... it's been a steep learning curve. Joel G. is planning on developing some examples soon... he has been a great resource... ~~~ Back to your Lesson.... the Script worked perfect.....Thank you.. Planning ahead .... when you have a moment, would you please explain how to code the same FLA with Multiple Dynamic text fields(which have respective MovieClips) ? Further, how would the/my xml file / code change? With the current coding above, say I add: MovieClip instance: b_mc , with a Dynamic text field instance: b_field Thanks in advance... again. D- Reading the PDF and reconstructing it is no simple task, that's for sure. When I say reconstruct I mean literally reading all the contents on a particular page and rebuilding that in flash using what flash has. Text in TextFields, images in Loaders, etc etc. Then all that content needs to be position. Inputs will need to be TextFields with the .type property set to be an input. It's a ton of work. Perhaps you could utilize a PDF to SWF converter? Have a look at this article below to see some useful information on PDFs and Flash: Thank you Sinious, I appreciate the PDF / Flash reference link. Insightful tools... ~ ~ Thanks again for the script re: accessing a dynamic text within a MoiveClip. D- You're welcome and good luck Hi Sinious, Some good news, I was able to contruct the Interfacing codes (AcroJS and AS3) to have a PDF form TextField interface with a SWF (RMA). The origianl script (above) works perfect with the assumption, the SWF's dynamic TextField was interfacing with a XML file. So with the SWF now interfacing with a PDF, will the AS3 code above still pass the dynamic TExtField into the MovieClip? My first few attampts have been unsuccessful..... D- North America Europe, Middle East and Africa Asia Pacific South America
http://forums.adobe.com/message/4338538
CC-MAIN-2013-20
refinedweb
2,736
66.94
[ ] Hoss Man updated SOLR-1592: --------------------------- Fix Version/s: 3.1 4.0 Correcting Fix Version based on CHANGES.txt, see this thread for more details... > Refactor XMLWriter startTag to allow arbitrary attributes to be written > ----------------------------------------------------------------------- > > Key: SOLR-1592 > URL: > Project: Solr > Issue Type: Improvement > Affects Versions: 1.4 > Environment: My MacBook laptop. > Reporter: Chris A. Mattmann > Assignee: Noble Paul > Fix For: 1.5, 3.1, 4.0 > > Attachments: SOLR-1592.Mattmann.112209.patch.txt, SOLR-1592.Mattmann.112209_02.patch.txt, SOLR-1592.patch, SOLR-1592.patch > > > There are certain cases in which a user would like to write arbitrary attributes as part of the XML output for a field tag. Case in point: I'd like to declare tags in the SOLR output that are e.g., georss namespace, like georss:point. Other users may want to declare myns:mytag tags, which should be perfectly legal as SOLR goes. This isn't currently possible with the XMLWriter implementation, which curiously only allows the attribute "name" to be included in the XML tags. > Coincidentally, users of XMLWriter aren't allowed to modify the <response outer XML tag to include those arbitrary namespaces (which was my original thought as a workaround for this). This wouldn't matter anyways, because by the time the user got to the FieldType#writeXML method, the header for the XML would have been written anyways. > I've developed a workaround, and in doing so, allowed something that should have probably been allowed in the first place: allow a user to write arbitrary attributes (including xmlns:myns="myuri") as part of the XMLWriter#startTag function. I've kept the existing #startTag, but replaced its innards with versions of startTag that include startTagWithNamespaces, and startTagNoAttrs. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online. --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@lucene.apache.org For additional commands, e-mail: dev-help@lucene.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-dev/201005.mbox/%3C12534662.37741275002617557.JavaMail.jira@thor%3E
CC-MAIN-2015-14
refinedweb
326
57.98
Watch variables with Watch windows and QuickWatch While you're debugging, you can use Watch windows and QuickWatch to watch variables and expressions. The windows are only available during a debugging session. Watch windows can display several variables at a time while debugging. The QuickWatch dialog displays a single variable at a time, and must be closed before debugging can continue. Note If this is the first time that you've tried to debug code, you may want to read Debugging for absolute beginners and Debugging techniques and tools before going through this article. Observe variables with a Watch window You can open more than one Watch window, and observe more than one variable in a Watch window. For example, to set a watch on the values of a, b, and c in the following code: int main() { int a, b, c; a = 1; b = 2; c = 0; for (int i = 0; i < 10; i++) { a++; b *= 2; c = a + b; } return 0; } Set a breakpoint on the c = a + b;line by clicking in the left margin, selecting Debug > Toggle Breakpoint, or pressing F9. Start debugging by selecting the green Start arrow or Debug > Start Debugging, or press F5. Execution pauses at the breakpoint. Open a Watch window by selecting Debug > Windows > Watch > Watch 1, or pressing Ctrl+Alt+W > 1. You can open additional Watch windows by selecting windows 2, 3, or 4. In the Watch window, select an empty row, and type variable a. Do the same for band c. Continue debugging by selecting Debug > Step Into or pressing F11 as needed to advance. The variable values in the Watch window change as you iterate through the forloop. Note For C++ only, You may need to qualify the context of a variable name, or an expression that uses a variable name. The context is the function, source file, or module where a variable is located. If you have to qualify the context, use the context operator (C++) syntax in the Name in the Watch window. You can add register names and variable names using $<register name> or @<register name> to the Name in the Watch window. For more information, see Pseudovariables. Use expressions in a Watch window You can observe any valid expression recognized by the debugger in a Watch window. For example, for the code in the preceding section, you can get the average of the three values by entering (a + b + c) / 3 in the Watch window: The rules for evaluating expressions in the Watch window are generally the same as the rules for evaluating expressions in the code language. If an expression has a syntax error, expect the same compiler error as in the code editor. For example, a typo in the preceding expression produces this error in the Watch window: A circle with two wavy lines icon may appear in the Watch window. This icon means the debugger doesn't evaluate the expression because of a potential cross-thread dependency. Evaluating the code requires other threads in your app to run temporarily, but since you are in break mode, all threads in your app are usually stopped. Allowing other threads to run temporarily can have unexpected effects on the state of your app, and the debugger may ignore events such as breakpoints and exceptions on those threads. Search in the Watch window You can search for keywords in the Name, Value, and Type columns of the Watch window using the search bar above each window. Hit ENTER or select one of the arrows to execute a search. To cancel an ongoing search, select the "x" icon in the search bar. Use the left and right arrows (Shift+F3 and F3, respectively) to navigate between found matches. To make your search more or less thorough, use the Search Deeper dropdown at the top of the Watch window to select how many levels deep you want to search into nested objects. Pin properties in the Watch window Note This feature is supported in .NET Core 3.0 or higher. You can quickly inspect objects by their properties in the Watch window Value column. To unpin a property, select the pin icon again or select the Unpin Member as Favorite option in the context menu. You can also toggle property names and filter out non-pinned properties when viewing the object’s property list in the Watch window. You can access both options by selecting the buttons in the toolbar above the watch window. Refresh watch values A refresh icon (circular arrow) might appear in the Watch window when an expression is evaluated. The refresh icon indicates an error or a value that is out of date. To refresh the value, select the refresh icon, or press the spacebar. The debugger tries to reevaluate the expression. However, you may not want or be able to reevaluate the expression, depending on why the value wasn't evaluated. Hover over the refresh icon or see the Value column for the reason the expression wasn't evaluated. Reasons include: An error occurred as the expression was being evaluated, as in the previous example. A timeout might occur, or a variable might be out of scope. The expression has a function call that could trigger a side effect in the app. See Expression side effects. Automatic evaluation of properties and implicit function calls is disabled. If the refresh icon appears because automatic evaluation of properties and implicit function calls is disabled, you can enable it by selecting Enable property evaluation and other implicit function calls in Tools > Options > Debugging > General. To demonstrate using the refresh icon: In Tools > Options > Debugging > General, clear the Enable property evaluation and other implicit function calls check box. Enter the following code, and in the Watch window, set a watch on the list.Countproperty. static void Main(string[] args) { List<string> list = new List<string>(); list.Add("hello"); list.Add("goodbye"); } Start debugging. The Watch window shows something like the following message: To refresh the value, select the refresh icon, or press the spacebar. The debugger reevaluates the expression. Expression side effects Evaluating some expressions can change the value of a variable, or otherwise affect the state of your app. For example, evaluating the following expression changes the value of var1: var1 = var2 This code can cause a side effect. Side effects can make debugging more difficult by changing the way your app operates. An expression with side effects is evaluated only once, when you first enter it. After that, the expression appears grayed out in the Watch window, and further evaluations are disabled. The tooltip or Value column explains that the expression causes a side effect. You can force reevaluation by selecting the refresh icon that appears next to the value. One way to prevent the side effects designation is to turn off automatic function evaluation. In Tools > Options > Debugging > General, deselect Enable property evaluation and other implicit function calls. For C# only, when evaluation of properties or implicit function calls is turned off, you can force evaluation by adding the ac format modifier to a variable Name in the Watch window. See Format specifiers in C#. Use Object IDs in the Watch window (C# and Visual Basic) Sometimes. Note Object IDs create weak references that don't prevent the object from being garbage collected. They are valid only for the current debugging session. In the following code, the MakePerson() method creates a Person using a local variable: class Person { public Person(string name) { Name = name; } public string Name { get; set; } } public class Program { static List<Person> _people = new List<Person>(); public static void Main(string[] args) { MakePerson(); DoSomething(); } private static void MakePerson() { var p = new Person("Bob"); _people.Add(p); } private static void DoSomething() { // more processing Console.WriteLine("done"); } } To find out the name of the Person in the DoSomething() method, you can add a reference to the Person Object ID in the Watch window. Set a breakpoint in the code after the Personobject has been created. Start debugging. When execution pauses at the breakpoint, open the Locals window by choosing Debug > Windows > Locals. In the Locals window, right-click the Personvariable and select Make Object ID. You should see a dollar sign ($) plus a number in the Locals window, which is the Object ID. Add the object ID to the Watch window by right-clicking the Object ID and selecting Add Watch. Set another breakpoint in the DoSomething()method. Continue debugging. When execution pauses in the DoSomething()method, the Watch window displays the Personobject. Note If you want to see the object's properties, such as Person.Name, you must enable property evaluation by selecting Tools > Options > Debugging > General > Enable property evaluation and other implicit function calls. Dynamic View and the Watch window Some scripting languages (for example, JavaScript or Python) use dynamic or duck typing, and .NET version 4.0 and later supports objects that are difficult to observe in the normal debugging windows. The Watch window displays these objects as dynamic objects, which are created from types that implement the IDynamicMetaObjectProvider interface. Dynamic object nodes show the dynamic members of the dynamic objects, but don't allow editing of the member values. To refresh Dynamic View values, select the refresh icon next to the dynamic object node. To display only the Dynamic View for an object, add a dynamic format specifier after the dynamic object name in the Watch window: - For C#: ObjectName, dynamic - For Visual Basic: $dynamic, ObjectName Note - The C# debugger doesn't automatically reevaluate the values in the Dynamic View when you step to the next line of code. - The Visual Basic debugger automatically refreshes expressions added through the Dynamic View. - Evaluating the members of a Dynamic View can have side effects. To insert a new watch variable that casts an object to a dynamic object: - Right-click any child of a Dynamic View. - Choose Add Watch. The object.namebecomes ((dynamic) object).nameand appears in a new Watch window. The debugger also adds a Dynamic View child node of the object to the Autos window. To open the Autos window, during debugging, select Debug > Windows > Autos. Dynamic View also enhances debugging for COM objects. When the debugger gets to a COM object wrapped in System.__ComObject, it adds a Dynamic View node for the object. Observe a single variable or expression with QuickWatch You can use QuickWatch to observe a single variable. For example, for the following code: static void Main(string[] args) { int a, b; a = 1; b = 2; for (int i = 0; i < 10; i++) { a = a + b; } } To observe the a variable, Set a breakpoint on the a = a + b;line. Start debugging. Execution pauses at the breakpoint. Select the variable ain the code. Select Debug > QuickWatch, press Shift+F9, or right-click and select QuickWatch. The QuickWatch dialog appears. The avariable is in the Expression box with a Value of 1. To evaluate an expression using the variable, type an expression such as a + bin the Expression box, and select Reevaluate. To add the variable or expression from QuickWatch to the Watch window, select Add Watch. Select Close to close the QuickWatch window. (QuickWatch is a modal dialog, so you can't continue debugging as long as it is open.) Continue debugging. You can observe the variable in the Watch window.
https://docs.microsoft.com/en-us/visualstudio/debugger/watch-and-quickwatch-windows?view=vs-2019
CC-MAIN-2021-25
refinedweb
1,888
54.93
BGE: Loading values with configparser Someone recently asked on the BA forums about loading variables from a file into the game engine. There are a number of ways to do this. The usual suggestions are Python’s built in IO – a simple, but messy solution to the problem. In this particular thread there was also the suggestion of saving/loading from your own custom module. And for completeness, there’s the pickle module. But there’s also the configparser module – which we’ll look at today. It’s always struck me as odd that you never really see this module used in the BGE as I think it’s perfectly suited for dealing with user settings. The main downside is that it requires an external Python module, another thing you need to include as part of the final product. But I think it’s strengths more than make up for this. You can save and recall any variable you want by name, so unlike using built in IO you don’t need to know the order of things. You don’t even need to know how many variables are saved as variables are meaningfully grouped. For example, if you’re loading high scores and you don’t need know how many games have been played by the player as it wont effect any other variables or the order. Finally, the file produced is human friendly. This has the advantage of simplifying play testing. Say you have something that’s triggered by beating a certain score, it’s easy to open the file set a high score and test things out. Or you can test loaded control setups without having to produce the GUI for saving them. It’s magical stuff. For the record, this tutorial uses Python 3.2. It should work with Python 2.x, I think the only change is the capitalisation in the module name. INI style files The configparser uses a file type based on the Windows .ini file style. This doesn’t mean that it makes registry edits like windows .ini files, nor does it mean that it’s restricted to the Windows system. It simply uses that style. Values are stored under a section header by option-value pairs (similar to a dictionary). So let’s have a look at one. Open up a text editor, notepad will do nicely, and enter the following: [player] # I am a comment, this section contains the player's details name: Jay Age: 24 location: UK [highscores] ; I am also a comment score1 = 1034 score2 = 5943 score3 = 2312 [settings] lod: 3 mouse: 0.2 filters: yes Lets save this file as settings.cfg (the file extension really doesn’t matter, make one up if you like). The first thing you see is a section header. This is the name of the section encased in square brackets: [section]. This is followed by a comment, which is started with either a hash symbol (#) or a semicolon (;). Comments exist on their own line and are optional. Under each section we have option-value pairs. First there’s the option (the variable’s name) followed by either a colon (:) or an equals sign (=) then the value. Values can even be multi-line. Pretty simple, right? Reading the file with Python You can either do this in pure Python, or open up Blender and create a new script and attach it to an object with an always sensor set to trigger once. All that matters is that the directory you save your .py or .blend is the same as settings.cfg (unless you specify the path to the settings file in the python script). What you do with these values once you’ve loaded them is up to you, for this tutorial we’re just going to print them. We shall start simple and loop through the file and print out the section headers and options: import configparser config = configparser.ConfigParser() config.read('settings.cfg') for section in config.sections(): print('###',section,'###') for option in config.options(section): print(option) After importing the configparser module we create an instance of the ConfigParser class and read settings.cfg into using the .read() function. We can return the names of the sections contained in settings.cgf with .sections() and returns a list that we can loop through. Looping through the list we then pass each section to .options() which returns a list of options under a section. We then loop through that list, printing out each option. Still with me? Now, .read() can take a list of file names, and is used when loading multiple files. So, if the file does not exist then it will skip over it an wont return an error. This means that later down the line when we try and access something in the file we will get an error. This is where .read_file() comes in. This function only takes one file and returns an error if it doesn’t exist. Error Handling As I mentioned earlier, the INI style file format is very readable and so is easily edited, which means that when using it it’s good practice to protect your self against unexpected changes. In the next example we’ll look at using .read_file(), checking sections/options exist and some simple error handling. import configparser config = configparser.ConfigParser() try: config.read_file(open('settings.cfg')) except IOError: print('file could not be found') #Load some default settings here age = 30 #check a section exists if config.has_section('player'): #check an option exists if config.has_option('player', 'age'): #get a specific option from a section age = config.get('player', 'age') print(age) .read_file() takes a file object, which we create by calling the built in method open(). In the above example if the specified file cannot be opened we can then move onto loading in some default variables so that our game does not crash. When we expect that something could go wrong we can use try/except to catch and handle exceptions. An exception is a syntactically correct statement, but one that might not always execute correctly. Notice how the code captured by the try/except block is as minimal as possible. This means that only the exceptions we expect could possibly happen and have prepared for are being caught. Other errors will be generated as per usual. If we had not specified what error we’re looking for, or included all the code within try/expect, other errors/exceptions unrelated to a missing file could slip by and we’d have no idea they had occurred, creating harder to find problems. Try changing the file name in the above example to something that doesn’t exist and see what value age takes then. We can use .has_section() and .has_option() to check for a section/option’s existence. These functions return true or false. Once we’re sure that the data we’re looking for exists we can grab it using .get(), which takes the section name followed by the option name and returns the value of the option in the form of a string. If a section or option doesn’t exist then we could use an else statement to assign a default value to age. Of course, you could avoid the need for extra else statements and multiple assignments by assigning age a value at the beginning of the script. Then if the file can be read and all the details that exist would get reassigned, otherwise it would remain unchanged. Another way to deal with missing sections/options, and perhaps the most straightforward, is with the fallback keyword argument: gender = config.get('player', 'gender', fallback='male') print(gender) We never added the option gender, so if it doesn’t exist then a default value will be returned instead – in this case the string ‘male’. There’s lots more to the configparser, such as saving, adding default values to your config file and dealing with data types. Not to mention a couple of different modes of operation. In my next tutorial on the subject we’ll do something a little more Blender specific and look at saving, doing things with the loaded data as well as defaults. But for now, this post is long enough and there’s plenty there to get started with. Any questions? Ask below. Should be nice to show how to load it with default values […] my last tutorial, many moons ago, we took a look at using the configparser to load data into the BGE and printing […] BGE: using values from configparser and default values | whatjaysaid said this on April 21, 2014 at 15:10 | […] can find the previous tutorials here: Introduction to the configparser Using data retrieved with the […] configparser and default sections | whatjaysaid said this on April 27, 2014 at 10:05 |
https://whatjaysaid.wordpress.com/2012/04/04/bge-loading-values-with-configparser/
CC-MAIN-2019-04
refinedweb
1,473
73.27
Other Aliasmandoc, man_deroff, man_meta, man_mparse, man_node, mdoc_deroff, mdoc_meta, mdoc_node, mparse_alloc, mparse_free, mparse_getkeep, mparse_keep, mparse_open, mparse_readfd, mparse_reset, mparse_result, mparse_strlevel, mparse_wait SYNOPSIS#include <sys/types.h> #include <mandoc.h> #define ASCII_NBRSP #define ASCII_HYPH #define ASCII_BREAK struct mparse * - mparse_alloc(int options, enum mandoclevel wlevel, mandocmsg mmsg, const struct mchars *mchars, char *defos); void - (*mandocmsg)(enum mandocerr errtype, enum mandoclevel level, const char *file, int line, int col, const char *msg); void - mparse_free(struct mparse *parse); const char * - mparse_getkeep(const struct mparse *parse); void - mparse_keep(struct mparse *parse); enum mandoclevel - mparse_open(struct mparse *parse, int *fd, const char *fname); enum mandoclevel - mparse_readfd(struct mparse *parse, int fd, const char *fname); void - mparse_reset(struct mparse *parse); void - mparse_result(struct mparse *parse, struct mdoc **mdoc, struct man **man, char **sodest); const char * - mparse_strerror(enum mandocerr); const char * - mparse_strlevel(enum mandoclevel); enum mandoclevel - mparse_wait(struct mparse *parse); #include <sys/types.h> void - mdoc_deroff(char **dest, const struct mdoc_node *node); const struct mdoc_meta * - mdoc_meta(const struct mdoc *mdoc); const struct mdoc_node * - mdoc_node(const struct mdoc *mdoc); extern const char * const * mdoc_argnames; #include <sys/types.h> void - man_deroff(char **dest, const struct man_node *node); const struct man_meta * - man_meta(const struct man *man); const struct mparse * - man_mparse(const struct man *man); const struct man_node * - man_node(const struct man *man); extern const char * const * man_macronames; DESCRIPTION The following describes a general parse sequence: - 1. - initiate a parsing sequence with mchars_alloc(3) and mparse_alloc(); - 2. - open a file with open(2) or mparse_open(); - 3. - parse it with mparse_readfd(); - 4. - retrieve the syntax tree with mparse_result(); - 5. - iterate over parse nodes with mdoc_node() or man_node(); - 6. - free all allocated memory with mparse_free() and mchars_free(3), or invoke mparse_reset() and parse new files. REFERENCEThis section documents the functions, types, and variables available via <mandoc.h>, with the exception of those documented in mandoc_escape(3) and mchars_alloc(3). Types An error or warning message during parsing. A classification of an enum mandocerr as regards system operation. An opaque pointer to a a character table. Created with mchars_alloc(3) and freed with mchars_free(3). An opaque pointer to a running parse sequence. Created with mparse_alloc() and freed with mparse_free(). This may be used across parsed input if mparse_reset() is called between parses. A prototype for a function to handle error and warning messages emitted by the parser. Functions Obtain a text-only representation of a struct man_node, including text contained in its child nodes. To be used on children of the pointer returned from man_node(). When it is no longer needed, the pointer returned from man_deroff() can be passed to free(3). Obtain the meta-data of a successful man(7) parse. This may only be used on a pointer returned by mparse_result(). Declared in <man.h>, implemented in man.c. Get the parser used for the current output. Declared in <man.h>, implemented in man.c. Obtain the root node of a successful man(7) parse. This may only be used on a pointer returned by mparse_result(). Declared in <man.h>, implemented in man.c. Obtain a text-only representation of a struct mdoc_node, including text contained in its child nodes. To be used on children of the pointer returned from mdoc_node(). When it is no longer needed, the pointer returned from mdoc_deroff() can be passed to free(3). Obtain the meta-data of a successful mdoc parse. This may only be used on a pointer returned by mparse_result(). Declared in <mdoc.h>, implemented in mdoc.c. Obtain the root node of a successful mdoc parse. This may only be used on a pointer returned by mparse_result(). Declared in <mdoc.h>, implemented in mdoc.c. Allocate a parser. The arguments have the following effect: - options - When the MPARSE_MDOC or MPARSE_MAN bit is set, only that parser is used. Otherwise, the document type is automatically detected. When the MPARSE_SO bit is set, roff(7) so file inclusion requests are always honoured. Otherwise, if the request is the only content in an input file, only the file name is remembered, to be returned in the sodest argument of mparse_result(). When the MPARSE_QUICK bit is set, parsing is aborted after the NAME section. This is for example useful in makewhatis(8) -Q to quickly build minimal databases. - wlevel - Can be set to MANDOCLEVEL_BADARG, MANDOCLEVEL_ERROR, or MANDOCLEVEL_WARNING. Messages below the selected level will be suppressed. - mmsg - A callback function to handle errors and warnings. See main.c for an example. - mchars - An opaque pointer to a a character table obtained from mchars_alloc(3). - defos - A default string for the mdoc(7) 'Os' macro, overriding the OSNAME preprocessor definition and the results of uname(3). The same parser may be used for multiple files so long as mparse_reset() is called between parses. mparse_free() must be called to free the memory allocated by this function. Declared in <mandoc.h>, implemented in read.c. Free all memory allocated by mparse_alloc(). Declared in <mandoc.h>, implemented in read.c. Acquire the keep buffer. Must follow a call of mparse_keep(). Declared in <mandoc.h>, implemented in read.c. Instruct the parser to retain a copy of its parsed input. This can be acquired with subsequent mparse_getkeep() calls. Declared in <mandoc.h>, implemented in read.c. If the fname ends in .gz, open with gunzip(1); otherwise, with open(2). If open(2) fails, append .gz and try with gunzip(1). Return a file descriptor open for reading in fd, or -1 on failure. It can be passed to mparse_readfd() or used directly. Declared in <mandoc.h>, implemented in read.c. Parse a file descriptor opened with open(2) or mparse_open(). Pass the associated filename in fname. Calls mparse_wait() before returning. This function may be called multiple times with different parameters; however, mparse_reset() should be invoked between parses. Declared in <mandoc.h>, implemented in read.c. Reset a parser so that mparse_readfd() may be used again. Declared in <mandoc.h>, implemented in read.c. Obtain the result of a parse. One of the three pointers will be filled in. Declared in <mandoc.h>, implemented in read.c. Return a statically-allocated string representation of an error code. Declared in <mandoc.h>, implemented in read.c. Return a statically-allocated string representation of a level code. Declared in <mandoc.h>, implemented in read.c. Bury a gunzip(1) child process that was spawned with mparse_open(). To be called after the parse sequence is complete. Not needed after mparse_readfd(), but does no harm in that case, either. Returns MANDOCLEVEL_OK on success and MANDOCLEVEL_SYSERR on failure, that is, when wait(2) fails, or when gunzip(1) died from a signal or exited with non-zero status. Declared in <mandoc.h>, implemented in read.c. Variables The string representation of a man macro as indexed by enum mant. The string representation of a mdoc macro argument as indexed by enum mdocargt. The string representation of a mdoc macro as indexed by enum mdoct. IMPLEMENTATION NOTESThis section consists of structural documentation for mdoc(7) and man(7) syntax trees and strings. Man and Mdoc StringsStrings. - ASCII_BREAK - A breakable zero-width space. Escape characters are also passed verbatim into text strings. An escape character is a sequence of characters beginning with the backslash ('\'). To construct human-readable text, these should be intercepted with mandoc_escape(3) and converted with one the functions described in mchars_alloc(3). Man Abstract Syntax TreeTh - ← mnode+ - mnode - ← ELEMENT | TEXT | BLOCK - BLOCK - ← HEAD BODY - HEAD - ← mnode* - BODY - ← mnode* - ELEMENT - ← ELEMENT | TEXT* - TEXT - ← [[:ascii:]]* The only elements capable of nesting other elements are those with next-line scope as documented in man(7). Mdoc Abstract Syntax TreeTh position - ← mnode+ - mnode - ← BLOCK | ELEMENT | TEXT - BLOCK - ← HEAD [TEXT] (BODY [TEXT])+ [TAIL [TEXT]] - ELEMENT - ← TEXT* - HEAD - ← mnode* - BODY - ← mnode* [ENDBODY mnode*] - TAIL - ← mnode* - TEXT - ← [[ compatibility with some older mdoc(7) implementations. Using badly-nested blocks is strongly discouraged; for example, the -Thtml and -Txhtml front-ends to mandoc(1) are unable to render them in any meaningful way. Furthermore, behaviour when encountering badly-nested blocks is not consistent across troff implementations, especially when using multiple levels of badly-nested blocks. AUTHORSThe mandoc library was written by Kristaps Dzonsons <[email protected]>.
http://manpages.org/mparse_strerror/3
CC-MAIN-2021-39
refinedweb
1,348
61.02
Action<'T> Delegate Encapsulates a method that has a single parameter and does not return a value. To browse the .NET Framework source code for this type, see the Reference Source. Assembly: mscorlib (in mscorlib.dll) You can use the Action<'T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (In C#, the method must return void. In Visual Basic, it must be defined by the Sub…End Sub construct. It can also be a method that returns a value that is ignored.) Typically, such a method is used to perform an operation.. The following example simplifies this code by instantiating the Action<'T> delegate instead of explicitly defining a new delegate and assigning a named method to it. You can also use the Action<'T> delegate with anonymous methods in C#, as the following example illustrates. (For an introduction to anonymous methods, see Anonymous Methods (C# Programming Guide).) using System; using System.Windows.Forms; public class TestAnonMethod { public static void Main() { Action<string> messageTarget; if (Environment.GetCommandLineArgs().Length > 1) messageTarget = delegate(string s) { ShowWindowsMessage(s); }; else messageTarget = delegate(string s) { Console.WriteLine(s); }; messageTarget("Hello, World!"); } private static void ShowWindowsMessage(string message) { MessageBox.Show(message); } } You can also assign a lambda expression to an Action<'T> delegate instance, as the following example illustrates. (For an introduction to lambda expressions, see Lambda Expressions (C# Programming Guide).) The ForEach and ForEach<'T> methods each take an Action<'T> delegate as a parameter. The method encapsulated by the delegate allows you to perform an action on each element in the array or list. The example uses the ForEach method to provide an illustration. The following example demonstrates the use of the Action<'T> delegate to print the contents of a List<'T> object. In this example, the Print method is used to display the contents of the list to the console. In addition, the C# example also demonstrates the use of anonymous methods to display the contents to the console. Note that the example does not explicitly declare an Action<'T> variable. Instead, it passes a reference to a method that takes a single parameter and that does not return a value to the List<'T>.ForEach method, whose single parameter is an Action<'T> delegate. Similarly, in the C# example, an Action<'T> delegate is not explicitly instantiated because the signature of the anonymous method matches the signature of the Action<'T> delegate that is expected by the List<'T>.ForEach method. Available since 8 .NET Framework Available since 2.0 Portable Class Library Supported in: portable .NET platforms Silverlight Available since 2.0 Windows Phone Silverlight Available since 7.0 Windows Phone Available since 8.1
https://msdn.microsoft.com/library/018hxwa8.aspx?cs-save-lang=1&cs-lang=fsharp
CC-MAIN-2016-36
refinedweb
491
50.53
Move/Merge articles to external wikis - 3.3 New dependencies for pacman - 3.4 vmlinuz26 - 3.5 Switch initscripts to systemd on all pages - 3.6 ConsoleKit and D-Bus - 3.7 virtualbox-iso-additions & Co. package name changes - 3.8 Inconsistent block size value for dd command - 3.9 Move openjdk6 to jdk7-openjdk - 3.10 compiz and emerald got dropped to AUR - 3.11 libgl and libgl-dri are no more - 3.12 Automatic loading of kernel modules - 3.13 Help me rewrite the eCryptfs article - 3.14 Links to Gentoo wiki - 3.15 Cleanup: installation category - 3.16 Cleanup: links to non-existent packages - 3.17 Add missing interlanguage links in protected pages - 3.18 xorg-server 1.16 - 3.19 Should we remove or archive obsolete articles? -. - Pages with misspelled or deprecated templates - Need to fix template or change to new) Xen: Creation of a network bridge I cleaned up the Xen article as much as I could. I can't get past the "Creation of a network bridge" section as it only describes how to do that with netctl. Maybe someone more experienced with Xen can expand on how to do that with other network managers? UPDATE: See Network bridge, this request should be implemented there. axper (talk) 07:32, 20 July) - Just a note: some of these pages are in Category:DeveloperWiki, some in Category:Arch development and some in both :\ -- Lahwaacz (talk) 08:42, 10 July 2014 (UTC)) - is of course preferable, however if there's really no alternative and the article in the Archives is still relevant, the fact that it's no longer editable shouldn't prevent from linking there. -- Kynikos (talk) 01:43, 8? Seriously outdated: - AIF_Configuration_File - outdated, but see Talk:AIF_Configuration_File#Preserve_AIF_pages_for_Development (it says "pages" in title, were there more?) - Installing_Arch_Linux_with_EVMS - last stable version of EVMS is from 2006 - Hard_Disk_Installation - written in 2008, no major update ever since Duplicated: - Install_from_SSH and Remote_Arch_Linux_Install describe basically the same thing - Installing_Arch_Linux_in_Virtual_Server - merge into Virtual_Private_Server? merge Remastering_the_Install_ISO and Building_a_Live_CD? -- Lahwaacz (talk) 22:08, 6 March 2014 (UTC) -- edited on 17:18, 11 July) Add missing interlanguage links in protected pages Some protected pages lack respective interlanguage links even though translated pages exist (for example, Installation guide). --Kusakata (talk) 16:49, 1 July 2014 (UTC) - I've fixed Installation guide, I can't check all the other pages now, if you find some other missing links somewhere else, please report it in that article's talk page. A little tip to find all the localized versions of the same title is to preview one article adding Template:i18n (no need to save of course). -- Kynikos (talk) 07:31, 2 July 2014 (UTC) - Thank you. I found: Category:Help (lacks ja, uk, zh-TW links), The Arch Way (su), Arch Linux (su), Installation guide (bg (its name is Official Installation Guide)), lt (Quick Arch Linux Install), nl (Official Installation Guide), th (Quick Arch Linux Install)), Arch packaging standards (ja, pt), Archboot (ar), and Help:i18n (ja). xorg-server 1.16 The release brings in rootless X, but also breaks redirecting output, it's not obvious how to run more than one X server at a time, I don't like it and I'm going on strike, so I won't be fixing any articles like Start X at Boot. -- Karol (talk) 15:01, 29 July 2014 (UTC) - Well, someone should step up as we're seeing content duplication, e.g. [6]. -- Alad (talk) 07:20, 11 August 2014 ) List of suggested solutions Delete, don't look back(current method, not a solution) Separate namespace(discarded) - Redirect to a page like "ArchWiki:Deleted" - Publicize Special:Undelete Bot requests Here, list requests for repetitive, systemic modifications to a series of existing articles to be performed by a wiki bot.
https://wiki.archlinux.org/index.php?title=ArchWiki:Requests&oldid=330061
CC-MAIN-2017-34
refinedweb
633
55.44
KDEUI KCModule Class ReferenceThe base class for configuration modules. More... #include <kcmodule.h> Detailed DescriptionThe base class for configuration modules. Configuration modules are realized as plugins that are loaded only when needed. a factory function like the following: #include <KPluginFactory> K_PLUGIN_FACTORY(MyKCModuleFactory, registerPlugin<MyKCModule>() ) K_EXPORT_PLUGIN(MyKCModuleFactory("yourLibName","name_of_the_po_file") ) The optional parameter "name_of_the_po_file" has to correspond with the messages target that containst the strings to be translated. Instead of using the library name for yourLibName you can also use another name which you specify in the desktop file with X-KDE-FactoryName. This is useful to have more than one factory in one lib. The constructor of the KCModule then looks like this: YourKCModule::YourKCModule( QWidget* parent ) : KCModule( YourKCModuleFactory::componentData(), parent ) { KAboutData *about = new KAboutData( <kcm name>, 0, ki18n( "..." ), KDE_VERSION_STRING, KLocalizedString(), KAboutData::License_GPL, ki18n( "Copyright 2006 ..." ) ); about->addAuthor( ki18n(...) ); setAboutData( about ); . . . } If you want to make the KCModule available only conditionally (i.e. show in the list of available modules only if some test succeeds) then you can use Hidden in the .desktop file. An example: See for more detailed documentation. Definition at line 98 of file kcmodule.h. Member Enumeration Documentation An enumeration type for the buttons used by this module. You should only use Help, Default and Apply. The rest is obsolete. NoAdditionalButton can be used when we do not want have other button that Ok Cancel - See also: - KCModule::buttons - Enumerator: - Definition at line 111 of file kcmodule.h. Constructor & Destructor Documentation Base class for all KControlModules. - Note: - do not emit changed signals here, since they are not yet connected to any slot. Definition at line 86 of file kcmodule.cpp. Destroys the module. Definition at line 126 of file kcmodule.cpp. Member Function Documentation This is generally only called for the KBugReport. If you override you should have it return a pointer to a constant. - Returns: - the KAboutData for this module Definition at line 180 of file kcmodule.cpp. Adds a KConfigskeleton config to watch the widget widget. This function is useful if you need to handle multiple configuration files. - Returns: - a pointer to the KConfigDialogManager in use - Parameters: - Definition at line 117 of file kcmodule.cpp. Indicate which buttons will be used. The return value is a value or'ed together from the Button enumeration type. - See also: - KCModule::setButtons Definition at line 107 of file kcmodule.cpp. Calling this slot is equivalent to emitting changed(true). Definition at line 211 of file kcmodule.cpp. Indicate that the state of the modules contents has changed. This signal is emitted whenever the state of the configuration shown in the module changes. It allows the module container to keep track of unsaved changes. Definition at line 216 of file kcmodule.cpp. - Returns: - a list of KConfigDialogManager's in use, if any. Definition at line 232 150. It is also called right after construction. Definition at line 134 of file kcmodule.cpp. Returns the changed state of automatically managed widgets in this dialog. Definition at line 162 227Message Definition at line 196 142 of file kcmodule.cpp. This sets the KAboutData returned by aboutData(). Definition at line 185 112 of file kcmodule.cpp. Sets the quick help. Definition at line 221 of file kcmodule.cpp. Sets the RootOnly message. This message will be shown at the top of the module if useRootOnlyMessage is set. If no message is set, a default one will be used. - See also: - KCModule::rootOnlyMessage Definition at line 191 of file kcmodule.cpp. Change whether or not the RootOnly message should be shown. Following the value of on, the RootOnly message will be shown or not. - See also: - KCModule::useRootOnlyMessage Definition at line 201 of file kcmodule.cpp. Reimplemented from QWidget. Definition at line 96 of file kcmodule.cpp. Call this method when your manually managed widgets change state between changed and not changed. Definition at line 174Message Definition at line 206 of file kcmodule.cpp. A managed widget was changed, the widget settings and the current settings are compared and a corresponding changed() signal is emitted. Definition at line 157 of file kcmodule.cpp. The documentation for this class was generated from the following files:
http://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/classKCModule.html
crawl-002
refinedweb
691
51.95
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. On Thu, May 16, 2002 at 01:30:00PM -0400, Daniel Jacobowitz wrote: > On Thu, May 16, 2002 at 11:04:20AM -0400, Nathanael Nerode wrote: > > I was looking for things to clean up, and I found that > > _ALL_SOURCE is defined in several places (host or target specific), but > > not tested anywhere. > > > > I'm guessing it's obselete and can be removed. (But it might be a > > 'secret flag' for some system compilers, in which case I'd be wrong.) > > > > I'd like verification from someone who understands its original purpose > > before I start sumbitting patches. > > It is a "secret flag". For HP/UX, I think. Generally true of most > things starting with an underscore, which belong to the implementation > namespace. This is really, really stretching my memory, but as I remember it is used in the internal AIX headers to guard definitions of functions that exist on almost all unixes, but strictly shouldn't be defined according to the appropriate standards.
http://gcc.gnu.org/ml/gcc/2002-05/msg01541.html
CC-MAIN-2018-13
refinedweb
179
63.09
Many of you SQL folks out there have extended stored procedures installed and being used in your SQL Server. Most often this is installed by some 3rd party applications like backup applications or linked server providers. There are times when some custom business logic is implemented in XPROC’s and hence these are loaded inside the SQL Server process address space. I am going to talk about something that not many people know about, but which does play a role in SQL Server, hence a DBA/DB-Developer must be aware of this. This scenario was brought to me by one of our customers and it goes something like this… Scenario I have an extended stored procedure called xp_customproc which is written in C/C++. During the course of migrating from SQL 2005 to SQL 2008, we noticed that we were getting Access Violation’s (AV) when running this xp_customproc. Here is the environment with the results of our testing. SQL Server Version Windows Version Success (Yes/No) SQL Server 2005 Windows Server 2003 Yes Windows Server 2008 SQL Server 2008 No! Whenever it failed with an AV, a mini-dump was captured by SQL Server and the following error was reported back to the client. Msg 109, Level 20, State 0, Line 0 A transport-level error has occurred when receiving results from the server. (Provider: Shared Memory Provider, error: 0 - The pipe has been ended.) Not only this, once this happened our SQL Server used to crash with the following entry in the event log. Faulting application sqlservr.exe, version 2007.100.1600.22, time stamp 0x4875735e, faulting module ntdll.dll, version 6.0.6001.18000, time stamp 0x4791a7a6, exception code 0xc0000374, fault offset 0x000b015d, process id 0xa10, application start time 0x01cb7556b688c75b. When I looked into the mini-dump, I noticed the following call stack which had generated the exception. 77a30d68 ntdll!RtlReportCriticalFailure+0x2e 77a30e56 ntdll!RtlpReportHeapFailure+0x21 779f0531 ntdll!RtlpLogHeapFailure+0xa1 779f0531: ntdll!RtlFreeHeap+0x00000060 7623c56f: kernel32!HeapFree+0x00000014 544f3228: xp_popup!xp_func1+0x00000e58 544f2279: xp_popup!xp_customproc+0x00000959 If you notice the highlighted entry in the stack above, it is talking about freeing a memory segment called “Heap”. Here are my conclusions after looking into the exception in detail. Q: Why is SQL Server crashing? Ans: Heap Corruption (NT_HEAP_CORRUPTION) is a specific type of memory corruption which will cause a process termination. Since xp_customproc.dll is loaded inside SQL Server process, any goof-up which happens here will affect the parent process, which in this case is SQLServr.exe. This is the reason for the AV and subsequent SQL Server crash. Q: Corruption, what type of corruption? Ans: Double Free which means, trying to free an already free heap. i.e. trying to free an already free block of memory. You can read more about this here à Q: Who is corrupting the heap? Ans: Obvious, xp_customproc.dll itself. Q: Who is creating these heaps? Ans: xp_customproc.dll itself is creating these heaps. To confirm this you need to talk to the developer/vendor who wrote the custom xproc code. Now that we have ascertained what happened and why, the obvious question in your mind is this, Q: Why does this happen only with SQL 2008 on Windows 2008? Ans: Windows 2008 (actually Windows Vista onwards) introduced a lot of changes to the NT Heap Manager. The Heap Manager is smarter and is more capable of detecting heap corruption and better at heap memory management. By default, now it has the capability to detect certain types of heap corruption and whenever ANY PROCESS runs into this, it is detected and terminated. This is what happened to SQL Server as well. Whenever Windows does this, it will automatically capture a dump of the parent process and it is stored in the following location along with the process name. C:\ProgramData\Microsoft\Windows\WER\ReportQueue\*.mdmp or *.dmp For E.g., C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_sqlservr.exe_7561dcdfc5bdc1befcdfd7575b83ae72c949f1d3_cab_92e2688f SQL Server 2008 is one of the applications which makes use of the new heap manager since it offers a lot more types of heaps and better performance (like LFH heaps). This is the reason why you only see it with this combination. Is this a good thing? YES! I would want any kind of memory corruption detected and captured rather than let the process continue. It can lead to data corruption, data loss, incorrect results and all other sorts of problems, if the process continues to run. Okay smart guy, but why don’t I see this on Windows 2003? Like I said earlier, this default behavior was introduced starting with Vista and for you to see this behavior on Windows 2003, you need to enable an option called PageHeap which turns on this extensive heap detection mechanism. This can be done following this KB article, How to use Pageheap.exe in Windows XP, Windows 2000, and Windows Server 2003 You can use GFlags.exe that is available with WinDbg to enable this option using the GUI. Here is an example for sqlservr.exe. Note: This is not something to have turned ON always for sqlservr.exe since enabling PageHeap means extensive tracking of memory allocations and will affect performance. So never do this unless guided by MS Support. I have mentioned this here purely to help you understand what was happening behind the scenes. Apart from the mini-dump, Windows also logs a specific exception code in the event log to help you identify what has occurred. Windows Error Reporting 1001 None "Fault bucket, type 0 Event Name: APPCRASH Error 10/5/2010 2:30:38 PM Application Error 1000 (100) "Faulting application name: sqlservr.exe, version: 2009.100.1600.1, time stamp: 0x4bb6b40b Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b Exception code: 0xc0000374 0xc0000374 is a new error code added in Windows Vista+ and above for reporting heap corruption. Exception Code: 0xc0000374 (STATUS_HEAP_CORRUPTION) Description: A heap has been corrupted. For those of you lost with all this technical mumbo-jumbo, let me explain this in very simplistic terms using the following diagram. This time the Xproc is called “xp_popup.dll”. Simplistic Overview of the Problem Conclusion Q: All Right, I get it. Now what? Ans: Since the true problem is happening in your custom code in xp_customproc.dll, you will have to debug this to see where the problem lies. This means talking to the vendor or developer who wrote the code in the extended stored procedure. If they have a support team, call away. Sample Test Code for Heap Corruption For those who are wondering what heap corruption is, here is a sample C++ code I wrote to show you what is wrong, #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <iostream> #include <conio.h> int _tmain (int argc, _TCHAR* argv[]) { printf("Press any key to start\n"); _getch(); BYTE* pByte=(BYTE*) HeapAlloc(GetProcessHeap(), 0, 10); (*pByte)=10; HeapFree(GetProcessHeap(), 0, pByte); HeapFree(GetProcessHeap(), 0, pByte); /* Doing Free twice */ printf("Done...exiting application\n"); return 0; } If you run this with PageHeap enabled using GFlags, you will notice that windows caught the heap corruption and terminates the process. Something similar is happening to the SQL Xproc’s. Hope this was informative. As always, stay tuned for more. Cheers! Regards, Sudarshan Narasimhan Technical Lead, Microsoft SQL Server CSS Satisfactory...but too large
http://blogs.msdn.com/b/sqlserverfaq/archive/2011/05/24/inf-sql-server-extended-stored-procedures-amp-behaviour-change-starting-with-windows-2008.aspx
CC-MAIN-2014-41
refinedweb
1,232
66.33
Automating .NET Core Services with PostSharp and Aspect-Oriented Code Alexander Johnston Originally published at Medium on ・15 min read If you’re writing software targeting .NET then there’s a good chance you’re using Object-Oriented principles to do your work. In the process you may run into design patterns which you find yourself often repeating. Some of these patterns start as an abstract need such as “I want to log what my code is doing”. In practice this is easy to solve but as your solutions grow in scope you may find yourself spending a significant amount of time just deciding where and how to log your program’s state. Eventually you may want to change the logging pattern but that will require a significant amount of changes to the source. While many people have solved this in an Object-Oriented way, these cross-cutting concerns will eventually add up to significant time sinks for any development team. They also present an architectural challenge later down the line when you need to make a significant change. You will have to walk back through all of that boilerplate code at some point when you want to add new log sinks, monitors, or internal log exception handlers. This problem comes up again on many common concerns such as security, caching, threading, rate limiting, and even alerting a GUI that some viewable object has been updated. Aspect-Oriented designs are focused on targeting those concerns by dealing with the problem in one place and then applying that solution everywhere in your code where it is needed. What I am trying to show here is a way to purposefully hide away those concerns after investing the time to fully model them out. By spending some extra time considering our approach to logging or threading then we can write Aspects which are more like qualities that can be assigned to areas of code. Once you write a [Log] attribute, then you can decide a class or a method will be logged simply by tagging it with the attribute. Later on the compiler does the rest of the work by going back over and adding the missing code where those Aspects are declared. As a quick note before I get into the main example, Microsoft released .NET Core 3 Preview 1 last month and with it comes support for native Windows desktop namespaces. While this article deals with .NET Core 2.1, you can recompile it at any time under netcoreapp3.0 as a project target and it will support a wider surface of types, including UWP libraries, without any extra configuration. Remarks This article is an attempt to cover certain difficult topics which vary in design from one business to the next. The code I will reference is written to be as short as possible, not fast or efficient. This is in the interest of showcasing each of the features and creating a usable demonstration. The goal here is to explore the cross-platform capabilities of the .NET Generic Host when combined with the power of a pattern-aware compiler. By wrapping the platform and runtime concerns around the generic host it becomes possible to seamlessly link almost any part of the .NET library for any platform. This doesn’t mean you can run a UWP library on Linux, but you won’t have to rewrite any code if you want to run that library when it detects Windows 10 as the OS. PostSharp is a pattern-aware compiler extension for Visual Studio and will be featured heavily throughout the article. If you don’t have a license and want to follow along with the code then there is still a solution. The free Essentials version of this framework covers up to ten classes which is enough to implement the full program in this article. You will also need to download the extension for Visual Studio 2017. Hosting Services I spent the past couple months getting a handle on the new .NET Core Generic Host which is familiar to anyone who has worked in ASP.NET Core web applications. The host can also be used in console applications as well to handle built-in app configuration, dependency injection, and logging. Let’s take a moment to see how the service hosting fits into this design. The goal is to create a small application which can: - Host common services and load native classes based on OSVersion. - Automatically wrap logging around the entire solution. - Automatically thread the services for a multi-core computer. - Validate architecture so that bugs throw exceptions in a deterministic way. Now because I have spent a lot of time working on ETL solutions I tend to map out the flow of my program and look at what my goals are from a high level. Below I’ve drawn out just some basic shapes to illustrate what the structure is and try to see where the boundaries are going to be. These boundaries are important because they represent areas where concerns cross over and cut into the concerns of individual objects. When using AOP in a project I always find it helps to clearly define where those boundaries are because the goal is to hide how they work. You’ll have to excuse my MS Paint aesthetic here: Program: A console app with Main() in this example. Runtime: This will be the top level for all of the PostSharp wrappers and the constructor for the rest of the program. This should launch the service host. Platform: This contains any methods needed to load native classes and provide a thread-safe reference to the Host in case any inter-service communication needs to be implemented. Frozen: Both of the previous layers will be frozen which provides some of the same guarantees as an immutable object. This will be covered later on. Hosting: The .NET Generic Host builder. Services: The services will be wrapped with an Actor model ensuring that they can run on a multi-core computer. Log Output Throughout this exercise you will see several examples of log output which describes the state of the program in a specific template. I’ve marked some of them here as an example of what the values represent. Program First, let’s start with a new .NET Core 2.1 console app. Next we need to add PostSharp to the project. If you have the extension for Visual Studio then you can right click on the project and add PostSharp to it through the menu. You can also use the Package Manager Console to run Install-Package PostSharp You will also need to add the following NuGet packages: - PostSharp.Patterns.Common The bulk of the code contracts and aspects. - PostSharp.Patterns.Diagnostics Tracing, logging, and diagnostics. - PostSharp.Patterns.Diagnostics.Serilog Automatically inject Serilog. - PostSharp.Patterns.Threading Threading models, dispatching, and deadlock detection. - Serilog Logging framework. - Serilog.Sinks.Console and Serilog.Enrichers.Thread for the sink. Now that we have our packages, let’s drop down one layer away from Program for now. I suggest a sealed runtime layer with static properties and an isolated, non-static entry-point. This allows the runtime to be instantiated as an object with its own threading model which can then launch onto a platform compatible with the caller’s context. The static properties are isolated away from the entry point and can then be used to attach async monitors or metrics later on. Now that we have a basic structure, we can talk about threading models. PostSharp provides three major features in PostSharp.Patterns.Threading. - Threading Models : A threading model is a design pattern that gives guarantees that your code executes safely on a multi-core computer. - Thread Dispatching : Custom attributes DispatchedAttribute and BackgroundAttribute cause the execution of a method to be dispatched to the UI thread or to a background thread, respectively. - Deadlock Detection : Detects deadlocks at run time and throws an exception instead of allowing your application to freeze. Threading models are named solutions to recurring problems and can be considered a design pattern which we will inject at compile time. Defects are discovered by validating the code both during build and while running. If the application is improperly threaded then it will fail in a deterministic way inside of these models. Without this assurance, race conditions or deadlocks tend to show up randomly and can corrupt data without any warning. The primary threading model we will be looking at is the Actor model. Actors are services which run with their own state and a mailbox to receive messages in synchronous order. Their execution is more complex than this image describes, but they can be thought of as independent objects which run asynchronously against a queue of messages. The second threading model being used is the Freezable threading model. An immutable object can be safely accessed from multiple threads but the restrictions of immutability often makes configuration difficult. By using Freezable objects we can define at what point in time the object becomes immutable while still benefiting from mutability during creation. Now let’s wrap the Runtime class with a frozen model. To freeze an object we need to decorate it with an aspect called [Freezable]. To enforce most threading models, PostSharp relies on the [Aggregatable] attribute; this specifies that a class has its Parent/Child relationship explicitly defined. Any properties which are not children should be marked as a [Reference]. Any methods which return the same value for each input and make no observable state changes can be marked as [Pure] to inform PostSharp that they are safe in a threaded context. I opted to include [NotNull] to indicate which properties are available from the entry point. Now that the Runtime class has been updated we can move on to the Platform. While developing for a cross-platform application on .NET Core, it’s helpful to have a layer where concerns of the platform can be safely handled. Let’s take a look at some functions you might see here: - GenericHost Creating the .NET generic host. - GetNativeClass Services may need to load platform-specific implementations and this will provide the correct type. - Crash If we are going to inject threading models safely then services also need a way to crash if state becomes fatal. You will see the following patterns on the Platform code: - [Required] Throws if null is passed in so that the responsibility belongs to the caller. - INativeClass Serves as an interface to load and terminate native classes after importing them. .Crash()Allows native platform classes to call for immediate debugging or termination if a fatal state is reached. It is marked with [ContractAnnotation (“=> halt”)] which specifies that for any given input the output will be a halted state. This allows the IDE to emit warnings appropriately. - GenericHost Will be decorated with [Reference] instead of [Child] which doesn’t guarantee thread safety anymore at the boundary but also doesn’t force the host to implement a compatible model. Now we have a Runtime with a thread safe entry point and a Platform which can load native classes. At this point we can go ahead and use the .NET Generic Host, specifically HostBuiler to configure services and host them. Several packages are helpful for using the HostBuilder: - Microsoft.Extensions.Configuration - Microsoft.Extensions.Configuration.CommandLine - Microsoft.Extensions.Configuration.EnvironmentVariables - Microsoft.Extensions.Configuration.Json - Microsoft.Extensions.DependencyInjection - Microsoft.Extensions.Hosting - Microsoft.Extensions.Options.ConfigurationExtensions The .Start() method is decorated with a [SingleEntryMethod] attribute which automatically intercepts the method and returns null if it has been called more than once. This permits us to leave a reference to the Generic Host inside of the Platform without worrying about this method being called later on. Because this class is being intercepted, we can decorate it with the [ExplicitlySynchronized] aspect which informs PostSharp not to verify the safety of this class. [SingleEntryMethod] is a custom aspect written with PostSharp. To create one of these we only need to decorate a class with [PSerializable] and then inherit from any of the PostSharp aspects. In this case we want to intercept calls at the boundary of the decorated method which is a feature provided by MethodInterceptionAspect. As you can see in the Generic Host, one service was registered called TimingService. Let’s set that class up now. This will use the [Actor] threading model with a few new attributes: - [Actor] Generates code which prevents fields of an actor from being accessed from an invalid context. Requires [Aggregatable] parent/child decoration as well as the following two aspects. - [Reentrant] This attribute declares that an async method can be safely re-entered on each await statement. For the actor model, this means other methods can be invoked while waiting. This must be applied to all async actor methods. - [ExplicitlySynchronized] Opts out of the threading model by declaring that the object is handling its own safety. - [EntryPoint] This specifies that the method can be invoked from threads which do not currently have access to the object. This means an event handler, background task, or callback can safely enter the threading model. Only needs to be applied to private methods. The TimingService class also inherits from IHostedService which integrates with the .NET Generic Host which is covered by this MSDN article. Each of these services will have StartAsync() called in the order they were registered during configuration earlier in the GenericHost class. The queue reverses this order when StopAsync() is called, starting with the last service registered and working its way back through the queue. In the interest of keeping this example small we’re going to cheat here and just use a few Timer objects to run on threads and report back. This should illustrate that our class is appropriately using the threading model. These aren’t technically native namespaces either, but calling out to platform-specific code will work exactly the same way without any configuration. With that in mind we need to implement the NativeTimers class which is imported from the Platform into TimingService after StartAsync() is called. NativeTimers will need to be placed under a namespace compatible with the platform this code is running on. In my case I am running on Windows 10 17134 which will return “Win32NT” as the Platform. A list of potential platforms is provided by Microsoft. - MacOSX - Unix - Win32NT At this point we have created the following areas of code: - Runtime Entered from Program, configures logging and then sets up the platform. - Platform Contains methods for loading native types and starts the generic host. - Generic Host .NET Core Generic Host which configures and creates services. - TimingService An example service being threaded with the Actor model. - NativeTimers An example being loaded natively by the Timing Service. Now we just need to inject the logging wrapper and freeze our layers, starting with the .Entry() function in Runtime. You will see the following patterns here: - LoggingServices.DefaultBackend This is the PostSharp logging back end. By setting our logger here we can then inject it later on. Post.Cast<T, IFreezable>( object ).Freeze()This is the call to freeze an object and mark it as immutable. The VerboseLogger() implementation and BlueConsole theme: Last we just need to call the Runtime from the program and inject logging into the assembly. Create a new GlobalAspects.cs class without any using or namespace declarations. Include these lines: This will wrap all Public, Private, Internal, and Protected members with the [Log] attribute from the assembly level. Now just call the runtime from Program and watch it run. If everything is set up correctly then we should be able to watch the entire flow of execution print out to the console. We expect to see something like this: - Generic Host starts up and creates the services. - Services access AppConfig which creates the Platform. - Services start asynchronously and ask for native types from the Platform. - Native Timers class is constructed and three timers are set. - Application starts. - Timers callback to the private 1[EntryPoint]1 on 1WriteTime()1. If you’ve been following along up to this point then you now can launch native classes onto services hosted cross-platform with the logging and threading handled. Where can we go from here? - Calling any libraries or namespaces from the services will automatically pipe the log statements if those libraries also implement Serilog, whether or not they have a custom log handler. This can be made compatible with other loggers as well. - State machines will automatically be maintained by PostSharp so that asynchronous code is threaded safely. You can see these decorated in the logs above. The services are able to call into asynchronous code from other frameworks as well; this means a UWP .NET Framework 4.7.1 class library can be called from .NET Standard 2.0 library referenced by a service running under .NET Core 3.0. This so far has worked without any needed configuration for me other than to compile the console application under <TargetFramework>netcoreapp3.0</TargetFramework>. - Asynchronous log monitors can be attached to Serilog with the ability to call back into Runtime or Platform as needed. These can be used to monitor flow, handle dropped log events, and handle deterministic internal logger exceptions. - An Event-Sourcing timeline, Inter-Process Communication Channel, or API can all be attached to the service actor model. Each actor can write events back to a central source asynchronously while guaranteeing the messages are threaded properly. Final Remarks I will attach the source code for this entire project below if you’d like to clone it and play around with the solution. Feel free to modify or redistribute it as needed. Hopefully this article was able to show you the power of Aspect Oriented Programming when combined with the new .NET Core architecture to provide highly extensible service hosting on many platforms. If you ever have questions related to PostSharp or .NET Core then feel free to comment or get in touch with me any time. AlexanderJohnston / SharpCrafting Exploring PostSharp AOP with .NET Core Generic Host SharpCrafting Exploring PostSharp AOP with .NET Core Generic Host. See my article on Medium for a detailed explanation. Requirements - PostSharp Essentials or Ultimate. - Visual Studio 2017 - .NET Core SDK 2.1 and C# 7.3 Goals - Demonstrate cross-platform .NET Core services which are threaded for a multi-core computer and wrapped with logging. - Create an example of utilizing PostSharp with the Generic Host in a console app. - Explore the benefits of Aspect Oriented Programming by masking the boundaries solved through use of PostSharp.
https://dev.to/dealeron/automating-net-core-services-with-postsharp-and-aspect-oriented-code-2j8i
CC-MAIN-2019-43
refinedweb
3,094
56.05
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rtl.h> int os_tick_init (void); The os_tick_init function initializes the hardware timer as a system tick timer and starts it. It is used in Cortex™-M library, if you want to use alternate peripheral timer as RTX tick timer. If this function does not exist in a project, the default SysTick timer is used as RTX tick timer. The os_tick_init function is part of RL-RTX. The prototype is defined in rtl.h. You can customize the function in rtx_config.c. Note The os_tick_init function returns the Cortex-M interrupt number of alternate peripheral timer. OS_Tick_Handler, os_tick_irqack #include <rtl.h> int os_tick_init (void) { /* Initialize hardware timer as system tick timer. */ LPC_SC->PCONP |= (1<<16); // Enable power for RIT LPC_SC->PCLKSEL1 &= ~(3<<26); LPC_SC->PCLKSEL1 |= (1<<26); // RIT Clock = CCLK LPC_RIT->RICOMPVAL = OS_TRV; // Set match value LPC_RIT->RICOUNTER = 0; // Set count value to 0 LPC_RIT->RICTRL = (1<<3) | // Timer enable (1<<1) | // Enable clear on match (1<<0); // Clear interrupt flag return (RIT_IRQn); /* Return IRQ number of timer (0..239) */ }.
http://www.keil.com/support/man/docs/rlarm/rlarm_os_tick_init.htm
CC-MAIN-2020-05
refinedweb
182
65.22
[Android] Building a simple menu in Android 5 August, 2008 7 Comments 25 Nov 2008, This tutorial has been superceded by Building a Menu for your Android (V1.0 R1) App. 19 Aug 2008, Note: Due to changes to the Android SDK, the code in this example does not work in 0.9 beta. The menu builder class provides a way to build a simple menu, similar to the one below, in Android. To do anything useful with the menu, you need to specify what to do when an item is selected. A class that implements the MenuItem.OnClickListener interface is required to perform these actions. Here is an example of a listener that popups a dialog with the selection: 1 public class AndroidMenuButton extends Activity 2 { 3 private View menuInstance = null; 4 5 private class ReactToClick implements Menu.OnClickListener 6 { 7 public ReactToClick() 8 { 9 // Empty constructor. Do nothing. 10 } 11 12 /** 13 * React to an item being clicked. 14 */ 15 public boolean onClick(Item item) 16 { 17 // Display a that "echoes" the item that was // selected. 18 AlertDialog.Builder dialogBuilder = new 19 AlertDialog.Builder(AndroidMenuButton.this); 20 21 dialogBuilder.setMessage(" You selected " + 22 item.getTitle()); 23 dialogBuilder.setCancelable(true); 24 dialogBuilder.create().show(); 25 26 // Click has been processed, so consume it. 27 return true; 28 } 29 } 30 A layout can be setup to place the view on. For this example, I’ve set up a vertical linear view using XML and I grab the layout with the findViewById method: 31 /** 32 * Called when the activity is first created. 33 */ 34 @Override 35 public void onCreate(Bundle icicle) 36 { 37 super.onCreate(icicle); 38 setContentView(R.layout.capbutton); 39 40 // Grab the view’s layout. 41 LinearLayout backView = (LinearLayout) 42 findViewById(R.id.backgroundView); 43 Next, create an instance of a MenuBuilder object and use the add method to place the menu items. Images for the menu items should be placed as a resource in res/drawables. 44 // Create the menu builder. 45 MenuBuilder builder = new MenuBuilder(this); 46 builder.setHeader("Menu Demo"); 47 Item newItem = null; 48 ReactToClick action = new ReactToClick(); 49 50 // Tell the menu builder how to build the menu. 51 newItem = builder.add(0, 1, "Photos", R.drawable.item1); The class, R, should be automatically be generated for you by the Android Eclipse plugin. R should contain references to all of your resources. The add method will return an Item object, to which you add your listeners to. 52 newItem.setClickListener(action); 53 newItem = builder.add(0, 2, "Painting", R.drawable.item2); 54 newItem.setClickListener(action); 55 newItem = builder.add(0, 3, "Science", R.drawable.item3); 56 newItem.setClickListener(action); 57 Once all of the menu items have been added, the menu view can be constructed by the viewer and added to your own view. 58 // Get the menu instance and add it the view. 59 menuInstance = builder.getMenuView 60 (MenuBuilder.TYPE_ICON, backView, true); 61 menuInstance.setBackgroundColor(Color.WHITE); 62 63 backView.addView(menuInstance); 64 } 65 } It is also possible to have Android create the menu in different formats, such as the icon view (pictured in the first screenshot) or the context menu (pictured in the screenshot below). The type of menu displayed is controlled by the first parameter to the MenuBuilder’s getMenuView method. The other two types of menus that have not been mentioned are the expanded menu and submenus. The MenuBuilder documentation details which constants the parameter needs to be set to in order to obtain the different types of menus (see the Constants section). Nice tutorial, Would it be possible to make the similar one for the last version of SDK (1.0)? Or are there any similar ones to this? Would be much appreciated. It should definitely be possible. I’ll have to have a look at how to do it first, but I reckon there is another tutorial out there somewhere for v1.0 Hi, i just wan to know what is MenuBuilder? i m not getting it Menu builder used to be something you could use to build a simple menu (like the one in the screenshot). It was removed since version 1 though. Nice tuts, really helpful for beginer like me. Can you post xml fil e ? Thanks again ! Hi meojunior! There is a more up-to-date tutorial for building menu is here: . I can look for the XML specific to this tutorial if you really need it, but I suggest looking at the updated tutorial first. Fastidious answers in return of this issue with genuine arguments and telling the whole thing about that.
https://kahdev.wordpress.com/2008/08/05/building-a-simple-menu-in-android/
CC-MAIN-2019-13
refinedweb
769
68.36
User account creation filtered due to spam. Hello, Here is a small sample to repeat the case: ------------ #include <stdio.h> main() { double d1, *pd1; char *c = (char*)&d1; pd1 = &d1; ((int*)pd1)[0] = -1; ((int*)pd1)[1] = -1; fprintf(stderr,">> d1 = %lf\n", d1); fprintf(stderr,">> int: %d %d\n", ((int*)pd1)[0], ((int*)pd1)[1]); fprintf(stderr,">> c1 = %02x\n", c[0]); fprintf(stderr,">> c2 = %02x\n", c[1]); fprintf(stderr,">> c3 = %02x\n", c[2]); fprintf(stderr,">> c4 = %02x\n", c[3]); fprintf(stderr,">> c5 = %02x\n", c[4]); fprintf(stderr,">> c6 = %02x\n", c[5]); fprintf(stderr,">> c7 = %02x\n", c[6]); fprintf(stderr,">> c8 = %02x\n", c[7]); } ------------ When I compile with `gcc -m64 -o b64 b64.c`, the output is correct: >> d1 = nan >> int: -1 -1 >> c1 = ff >> c2 = ff >> c3 = ff >> c4 = ff >> c5 = ff >> c6 = ff >> c7 = ff >> c8 = ff But when I use the optimise flag, `gcc -O2 -m64 -o b64 b64.c`, and run again the sample, there is a problem with the results. See bellow: >> d1 = 0.000000 >> int: -1 -1 >> c1 = ff >> c2 = ff >> c3 = ff >> c4 = ff >> c5 = ff >> c6 = ff >> c7 = ff >> c8 = ff Gcc release: Using built-in specs. Target: ppc64-redhat-linux Configured with: ../gcc-4.0.0/configure --prefix=/home/comp/gcctest4.0.0 --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --host=ppc64-redhat-linux --build=ppc64-redhat-linux --target=ppc64-redhat-linux --with-cpu=default32 --enable-languages=c,c++ Thread model: posix gcc version 4.0.0 Environment: Linux 2.6.9-11.EL #1 SMP Fri May 20 18:18:48 EDT 2005 ppc64 ppc64 ppc64 GNU/Linux Best regards. Created attachment 10589 [details] Small sample to illustrate the problem How to repeat sample You are violating C aliasing rules as you acess d1 via an int. *** This bug has been marked as a duplicate of 21920 *** Maybe... But I made some tests under Linux X86 and some AIX 64 bits. This code works as expected everywhere... So, I wonder why gcc behaviour is différent under this Linux PPC64 ? (In reply to comment #3) > Maybe... > > But I made some tests under Linux X86 and some AIX 64 bits. This code works as > expected everywhere... > So, I wonder why gcc behaviour is différent under this Linux PPC64 ? Because PPC 64 schedules code more aggressively. Anyways the code is undefined so anything can happen.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25692
CC-MAIN-2017-13
refinedweb
408
65.01
This article explain shortly how implement NAT discovery with the ByteBlower API. We'll focus on the basic use-case and provide pointers for more in-depth info. Some experience with FrameBlasting using the ByteBlower API is assumed. Throughout the text we'll use Python but the same principles also apply to the Tcl version of our API. NAT discovery in the ByteBlower GUI is enabled in the Port View. No such method is available in the API reference for the ByteBlower. Luckily implementing NAT discovery is very easy. Before we start let's briefly make the setup clear. We'll use the terms upstream and downstream. In this text we'll use them as followed: A good starting point for NAT discovery is first sending traffic between two interfaces in the local network.This is the basic example shown on our GitHub page. You can do this by connecting both interfaces to the same modem or access Point. Next is creating Upstream FrameBlasting UDP traffic. This requires one ByteBlower interface in the private network and one outside. As mentioned above, although the addresses are translated, the upstream traffic isn't blocked, at the wan_port is will received with a different source IP address and different source UDP port. The easiest way is to count all this traffic is by leaving the BPF filter empty. Keep in mind this counts all traffic now, including test-runs from other users. trigger = wan_port.RxTriggerBasicAdd() trigger.FilterSet('') The RxTriggerBasic is a traffic that only counts traffic. The next step is capturing the raw frame-data, very similar to how you'd use Wireshark. This is possible with the ByteBlower API using a different kind of filter: RxCaptureBasic. The example code below shows how to add this filter. Unlike the previous trigger, this type needs to be started explicitly. This filter has a performance impact, but on most systems receiving multiple Mbits/s is no issue. captureRaw = wan_port.RxCaptureBasicAdd() captureRaw.FilterSet('') captureRaw.Start() The final step in the NAT discovery is dissecting the received packets to learn the translated addresses. The ByteBlower API offers you the raw Ethernet frame as it was received. With an external library, SCAPY, you can convert these bytes something easier to inspect in Python. from scapy.all import * # Process the response: retrieve all packets. for f in sniffed.FramesGet(): data = bytearray(f.BufferGet()) raw = Ether(data) if IP in raw and UDP in raw: discovered_ip = raw['IP'].getfieldval('src') discovered_udp_port = raw['UDP'].getfieldval('sport') print('Discovered IP: %s' % discovered_ip) print('Discovered UDP port: %s' % discovered_udp_port) Finally the discovered public IP and UDP port now have a NAT-entry. You can use them as destination for downstream traffic. Without any upstream traffic, this typically remains saved for about 5 minutes. More info, beyond the basic NAT use-case can be found in the following article: I consent for Excentis to process my data and agree to the terms of the Privacy Policy
https://support.excentis.com/index.php?/Knowledgebase/Article/View/doing-nat-discovery-with-byteblower-api
CC-MAIN-2020-40
refinedweb
492
58.18
Singletons. They’re your worst nightmare — or at least that’s what you’ve been led to believe. Are they really so bad? Why are they considered evil? And were they always on the wrong side of public opinion? Singletons have been called a design pattern. They have also been called an anti-pattern. So which is it? Surely it can’t be both. Here’s my guilty confession: I still use singletons. But I found a way to mitigate the drawbacks, so I happily use singletons for their benefits without suffering their problems. In this blog post, we examine where singletons came from, where it all went wrong, and what you can do now to make use of singletons for their originally intended benefits — without guilt or fear. Read on to find out more. Background Given the amount of fear and loathing that surrounds singletons, it might surprise you to know that they weren’t born evil. In fact, singletons were in common use for at least 10 years before notions of their being evil had filtered throughout the blogosphere. Let’s have a quick look at the history. Singletons were introduced to the world in 1995 through the now-classic software development book Design Patterns by the “Gang of Four” (shown in Figure 1), although certainly the concept of the singleton (if not the actual name singleton) had been around for many years before this book was published. Figure 1: My personal copy of the Design Patterns book by the Gang of Four. This book introduced the world to the singleton design pattern in 1995. While researching for this post, I wanted to know exactly when the love for singletons stopped. By at least 2007, hate had blossomed. Here is the earliest (still online) blog post I could find. I also found this one on the Wayback Machine from 2008. Then fast-forward to 2020 for this one. So singletons had enjoyed more than 10 years of use before the anger against them bubbled to the surface. That’s a good run, but now it’s been over 10 years since they were considered an anti-pattern. It made me wonder why we are still talking about this after so long. Shouldn’t people have stopped using singletons already? Then I realized, I myself had never actually stopped using singletons. In fact, I still use them frequently. I knew how bad they were; the years of arguments hadn’t escaped my attention. Yet somehow I’d found a way to make singletons work. My code today is cleaner and more elegant than it ever was. I use singletons, but I also do significant automated testing, and I am constantly refactoring my code easily and safely. How is it possible that the maligned singleton has not destroyed my development process? Development for me is a constant process of improvement and evolution. Yes, singletons have caused problems for me from time to time, but did I throw them out? No, because singletons are still useful. Indeed, that’s why people still use them; if people weren’t still using them, we wouldn’t still be arguing about them. Instead of throwing out the singleton design pattern, I evolved it. I learned the problems with it (firsthand) and I adjusted how I used it. I found a way to use singletons without suffering the (by now) well known drawbacks. In a moment I’ll show you how. What is a singleton? Let’s start with a simple overview of the singleton pattern, just to get you up to speed. Sometimes when coding, we need the concept of a global object. This is an object that only has one instance in our application. Design Patterns uses the following examples: printer spooler, file system, and window manager. There can and should be only one instance for these types of objects. The singleton design pattern makes the class responsible for its own creation and controls access to the instance so that its single-instance nature cannot be subverted. We can therefore ensure this object is never created more than once. The singleton is one of a handful of creational patterns covered in Design Patterns. It’s just one of a number of methods for creating objects. Figure 2: Illustration of the traditional singleton design pattern. Modern examples of singletons To understand what a singleton is and how it’s useful, let’s consider some more modern examples of objects that can be represented well as singletons. Dialog provider One good example is the dialog provider. A UI-based application can display dialogs to collect input from the user. It makes sense that we only have one instance of our dialog provider so we can control how it’s used. For example, we probably want to enforce only one dialog on screen at a time. Figure 3 illustrates how we might use a dialog provider as a singleton to easily and quickly connect it to deeply nested objects in your UI hierarchy. The code below in Listings 1 and 2 is an example of how this dialog provider might be coded in JavaScript. Figure 3: Directly connecting deeply nested objects in our UI hierarchy to a singleton dialog provider. Entity repository Here’s another example that might appeal to you. Almost every application needs some form of data storage, and this is often implemented using the repository pattern. It can be very tempting to store our respiratory objects as singletons so that they are easily accessible from anywhere in our code. This isn’t just for convenience, though: having a singleton instance of our entity repository means we have one place to implement caching for our entities and optimize so that subsequent data loads don’t have to go to the file system or database. Listing 1: An example singleton implementation for our dialog provider in TypeScript export class DialogProvider { // // Gets the singleton instance. // Lazily creates the singleton when first called. // public static getInstance(): DialogProvider { if (!this.instance) { this.instance = new DialogProvider(); } return this.instance; } // // Instance of the singleton, after it has been created. // private static instance?: DialogProvider; // // Presents the dialog box to the user. // public async showDialog(question: string): Promise<string> { // ... code here to display the dialog box .... } // // ... other functions go here ... // } Listing 2: Example of using the singleton string question = ... string answer = await DialogProvider.getInstance().showDialog(question); // ... do something with the answer received from the user ... Wiring dependencies Traditionally, when wiring up dependencies through our codebase, we had two choices: - Wire dependencies all the way through our potentially deeply nested code structure (see Figure 4 for an illustration) - Directly access the dependency as a global object Figure 4: When not using a singleton for the dialog provider, we must wire this dependency all the way through our deeply nested UI hierarchy. The first option is tedious and painful, and such hardwiring makes it difficult to restructure our application. The second option, directly accessing a global object, is much easier but, again, makes it difficult to restructure our application. Arguably, the second option is better. Both alternatives lead to hardwired code that is difficult to modify. But the second is easier to put in place, and there is less wiring to change later — because we don’t have to wire it through all the intermediate layers. But globals are bad, right? Well, not so much back in the days when the singleton was invented. Back then, computer programs were not quite as large and complicated as they are now, and automated testing was rare. The singleton design pattern introduces control over access while still retaining the convenience of having direct access from anywhere in our codebase. To an extent, the singleton design pattern legitimized the use of global objects. The problems start Over the years, our computer programs became larger and more complex. The teams developing them grew bigger. Automated testing became popular. The singleton design pattern was overused and was probably often misused. The problems with the singleton manifested to the point where it became known as an anti-pattern. A singleton by itself is hardly better than just accessing a global object, with all the problems that implies: - Objects that depend on singletons are not easily isolated for testing - Our codebase is hardwired, and it’s not easy to restructure it - Changing from a global object to a non-global object (if we decide that singletons are wrong in a particular case) is particularly difficult. Imagine having to wire it all the way through your codebase Singletons (indeed any global references) and side effects are probably the biggest reason why legacy applications are difficult to restructure and difficult to adapt to automated testing. You’re using singletons the wrong way Let’s just face it — coding is difficult. Every design pattern, every technique, every best practice can be used the wrong way, and it can be overused. One coder’s design pattern is another’s anti-pattern. The singleton is no exception. The thing is, you are using singletons the wrong way. In most cases, we probably don’t even care if there’s a singleton instance, we mostly just want the convenience of an easily accessible object when that makes sense (and later, when it no longer makes sense, we’d like an easy way to rectify the situation). We’d also like the convenience of not having to worry about startup ordering issues. Ideally, we just want start up dependencies to resolve themselves and figure out their own order of initialization. That’s something awesome we got from self-creating lazily instanced singletons. So generally, we’d like the convenience of the singleton without having to take on any of the negative stuff. Is there a way to get the benefits of the singleton without the drawbacks? Yes, there most certainly is! Fixing singletons Singletons are just so damn convenient. There is a reason people are still using them! How can we use singletons but still be able to do automated testing and have an architecture that’s amenable to restructuring? We can salvage the singleton, and it’s easier than you might think. Let’s make some changes to it: - The singleton class itself should not be responsible for its own creation - Other classes should not be hard-linked to the singleton Solving these problems isn’t that difficult, but what we really need for it to be as convenient as the original singleton is for the wiring of dependencies to be automatic. We don’t want to have to wire through a dependency all the way through our codebase to get it to be everywhere that it needs to be accessed. Such manual wiring is tedious and is the opposite of convenience. What we need is another design pattern — something that can automate the wiring of dependencies within our codebase. DI saves the day The good news is that dependency injection (DI), a design pattern that came a bit later, saves the day for singletons. Singletons coupled with DI gives us the convenience of singletons without the remorse or guilt (see example code in Listings 3 and 4 using the Fusion DI library). Automatic dependency injection is specifically what I’m talking about; sometimes it’s called inversion of control (IoC). It automates the creation and wiring-through of our dependencies. We can use DI to wire our global objects (aka singletons) through our codebase without having to do any manual setup. This automation makes it trivial to rewrite and restructure the connections between components in our application, even when those connections are to singletons. When a dependency is injected into an object, that object does not need to know that it is actually connected to a singleton! Then, for automated testing, we inject a mock object as the dependency instead of the real object. This means we can do automated testing against objects that depend on singletons. Automated DI also figures out the initialization order for our application. It automatically and lazily instantiates dependencies and dependencies of dependencies and creates them in the right order and at the right time, just before they are needed. Singletons on their own no longer need to manage their own creation. The DI framework manages their creation, so singletons can be instantiated just like normal objects, and we can therefore instantiate them in our automated tests and run tests against them. The problems with singletons have evaporated! Now, some would argue that what I’m describing is simply DI and not singletons at all. Well, that’s just semantics. I would argue that this is an evolution of how we create and consume global objects; it’s an evolution of how we use singletons. From my perspective, I never stopped using singletons. I even still call them singletons in the DI library I created for TypeScript (Listing 3 shows how a singleton is defined using the Fusion DI library). Listing 3: Example of a dependency-injectable, lazily created singleton in TypeScript import { InjectableSingleton } from "@codecapers/fusion"; export interface IDialogProvider { // // Presents the dialog box to the user. // showDialog(): Promise<void> } @InjectableSingleton("IDialogProvider") export class DialogProvider implements IDialogProvider { // // Presents the dialog box to the user. // public async showDialog(): Promise<void> { // ... code here to display the dialog box .... } // // ... other functions go here ... // } Listing 4: Example of dependency-injecting a lazily created singleton into a TypeScript class import { InjectProperty } from "@codecapers/fusion"; export class SomeUIComponent { @InjectProperty("IDialogProvider") dialogProvider!: IDialogProvider; // ... other code here ... public async onButtonClicked(): Promise<void> { await this.dialogProvider.showDialog(); } } To learn more about the Fusion DI framework, you can read my earlier blog post. Conclusion Singletons have been considered both a design pattern and an anti-pattern, but you need to remember that one person’s design pattern is another’s anti-pattern. All design patterns can be applied to the wrong situations (wherein they become an anti-pattern) and all design patterns that are misused or overused can cause damage. I want you to come away from this blog post with an understanding that it’s not all black and white. There are many shades of gray. Arguably, the singleton is the most overused and badly applied design pattern, and that’s why it has suffered the backlash that it has received. But don’t just believe what you hear; you need to be able to think about these things for yourself. Think critically, and try it out before you form an opinion on it. There is a reason why people are still complaining about singletons! It’s because they are still being used, even after 10 years of being considered evil! Why are singletons still being used? Is it because some devs didn’t get the memo that singletons are bad? No, it’s because singletons are actually convenient and useful despite the various potential drawbacks. If devs weren’t using singletons, we simply wouldn’t be hearing about them anymore. If you are going to use singletons, please make sure you are also using dependency injection. DI saves the day for singletons. Using DI means we can have global singleton objects and can benefit from automated dependency wiring and the ability to isolate using mocking to enable automated testing. We can use the singleton design pattern for its originally intended benefits without exposing ourselves to the risks normally associated with singletons. So stop worrying and just use singletons.* * Make sure you are using DI as well, though.
https://codecapers.com.au/singletons/
CC-MAIN-2021-49
refinedweb
2,577
55.95
I'm trying to configure a bridge between two TAP interfaces each created inside their own network namespace, on Linux. I'm using OpenVSwitch as software bridge. These are the steps that I believe should work: ip netns add test_ns1 ip netns exec test_ns1 ip tuntap add mode tap testif1 ip netns exec test_ns1 ip addr add 192.168.1.1/24 dev testif1 ip netns exec test_ns1 ip link set testif1 up ip netns add test_ns2 ip netns exec test_ns2 ip tuntap add mode tap testif2 ip netns exec test_ns2 ip addr add 192.168.1.2/24 dev testif2 ip netns exec test_ns2 ip link set testif2 up ovs-vsctl add-br test_br ip netns exec test_ns1 ovs-vsctl add-port test_br testif1 ip netns exec test_ns2 ovs-vsctl add-port test_br testif2 ip netns exec test_ns1 ping -c 2 192.168.1.1 ip netns exec test_ns2 ping -c 2 192.168.1.2 ip netns exec test_ns1 ping -c 2 192.168.1.2 ip netns exec test_ns2 ping -c 2 192.168.1.1 All four ping commands will not work and report 100% packet loss. I would expect to be able to ping the interface from inside its own namespace (testif1 from test_ns1, for example). I can do that with the Quantum interfaces, but not with mine, why? Then, I am quite sure OpenVSwitch is installed correctly because I am running the stock Ubuntu version and I have OpenStack Quantum running on the same machine. OpenStack doesn't create tap devices with ip tuntap add. Instead, it creates internal ports on the openvswitch bridge using the ovs-vsctl add-port command. Because openvswitch implements internal ports as tap devices, OpenStack labels these ports as "tapXXXX". ip tuntap add ovs-vsctl add-port To create a testif1 interface on an openvswitch bridge and put it in the test_ns1 namespace, try doing this instead: ovs-vsctl add-port test_br testif1 -- set interface testif1 type=internal ip link set testif1 netns test_ns1 ip netns exec test_ns1 ip addr add 192.168.1.1/24 dev testif1 ip netns exec test_ns1 ip link set testif1 up By posting your answer, you agree to the privacy policy and terms of service. asked 2 years ago viewed 1654 times active
http://serverfault.com/questions/515500/openvswitch-between-namespaces/532044
CC-MAIN-2015-48
refinedweb
380
69.21
IRC log of er on 2008-05-28 Timestamps are in UTC. 12:22:02 [RRSAgent] RRSAgent has joined #er 12:22:02 [RRSAgent] logging to 12:22:11 [Zakim] Zakim has joined #er 12:22:17 [shadi] zakim, this will be ert 12:22:17 [Zakim] ok, shadi; I see WAI_ERTWG()8:30AM scheduled to start in 8 minutes 12:22:25 [shadi] meeting: ERT WG 12:22:30 [shadi] chair: Shadi 12:23:00 [shadi] agenda: 12:23:15 [shadi] agenda+ "HTTP Vocabulary in RDF" 12:23:25 [shadi] agenda+ "Representing Content in RDF" 12:23:37 [shadi] agenda+ Draft ERT WG Charter 12:26:44 [MikeS] MikeS has joined #er 12:29:31 [shadi] zakim, code? 12:29:31 [Zakim] the conference code is 3794 (tel:+1.617.761.6200 tel:+33.4.89.06.34.99 tel:+44.117.370.6152), shadi 12:29:39 [Zakim] WAI_ERTWG()8:30AM has now started 12:29:39 [JohannesK] JohannesK has joined #er 12:29:46 [Zakim] +??P6 12:29:54 [shadi] zakim, ??p6 is really me 12:29:54 [Zakim] +shadi; got it 12:29:57 [Zakim] +[IBM] 12:30:17 [shadi] zakim, ibm is really Mike 12:30:17 [Zakim] +Mike; got it 12:30:39 [Zakim] +CarlosV 12:30:48 [JohannesK] Zakim, CarlosV is really Johannes 12:30:48 [Zakim] +Johannes; got it 12:32:08 [shadi] scribe: Mike 12:32:13 [shadi] scribenick: MikeS 12:32:45 [shadi] regrets: CarlosI 12:33:12 [MikeS] zakim, mute me 12:33:12 [Zakim] sorry, MikeS, I do not know which phone connection belongs to you 12:33:20 [MikeS] zakim, mute mike 12:33:20 [Zakim] Mike should now be muted 12:33:39 [shadi] zakim, Mike is really MikeS 12:33:39 [Zakim] +MikeS; got it 12:33:46 [MikeS] ok 12:34:45 [shadi] agenda? 12:35:01 [shadi] zakim, take up agendum 1 12:35:01 [Zakim] agendum 1. ""HTTP Vocabulary in RDF"" taken up [from shadi] 12:35:11 [shadi] 12:35:40 [MikeS] SAZ: Changes from telecon on 05/21 have been completed and are in latest editor's draft 12:35:55 [MikeS] ..JK sent more comments and fixes are in place 12:36:39 [MikeS] ....will clean up references and history sections 12:37:14 [MikeS] ...work on 1) status of document and 2) are we willing to publish as is? 12:37:59 [MikeS] ...any pubilcation show-stoppers? 12:38:07 [MikeS] +1 12:38:51 [MikeS] ok 12:39:09 [shadi] action: SAZ remove "namespace" from table 2 (these are not namespaces) 12:39:44 [MikeS] ...note that we do not have 2/3 of group present 12:40:00 [MikeS] ....follow-up with CI and CV for any last-minute comments 12:40:39 [shadi] RESOLUTION: go ahead with publishing HTTP Vocabulary in RDF 12:41:12 [MikeS] SAZ: What are we looking for from public feedback and status? 12:41:24 [MikeS] ...how these documents relate to POWDR 12:42:06 [Zakim] +Johannes.a 12:42:13 [MikeS] ...feedback from other semantic web groups 12:42:21 [CarlosV] CarlosV has joined #er 12:42:40 [MikeS] CV: no ojbections to publication 12:43:44 [MikeS] SAZ: in particular, how schema performs and is evaluated by other semantic web groups and technologies 12:43:56 [MikeS] ...Mobile Web group also interested in serialization of HTTP 12:45:15 [MikeS] ..question for Mobile Web is how our XML representation would "play" with their representation 12:47:24 [shadi] zakim, take up next 12:47:24 [Zakim] agendum 2. ""Representing Content in RDF"" taken up [from shadi] 12:47:35 [shadi] 12:48:18 [MikeS] SAZ: very well-written; many comments already incorporated 12:48:28 [MikeS] ...abstract too brief 12:48:42 [MikeS] definitely 12:49:12 [MikeS] ...merge section 1.3 use cases into itnroduction 12:49:31 [MikeS] Quick question - why is XMLContent not a sublcass of TextContent? 12:51:01 [MikeS] JK: separate classes bc they have different properties; e.g. XmlContent does not have chars but might be representation of in-memory DOM 12:51:24 [MikeS] ok - just curious from a new-commers perspective 12:51:54 [MikeS] JK: TextContent could be subclass of Base64Content since text could be represented that way 12:51:59 [MikeS] got it. 12:53:54 [MikeS] CV: too brief and possibly redundant 12:54:23 [MikeS] ...content in RDF is a complementary document to Http in RDF so don't want to spend too much time on it 12:54:52 [MikeS] no 12:55:58 [MikeS] SAZ: keep in mind that this a distinct publication and needs a context 12:56:19 [MikeS] ...people could randomly land on the document and abstract should spell out relationships and context 12:57:06 [MikeS] agree - especially spelling out the rleationships to EARL and Http in RDF 12:58:30 [MikeS] SAZ: part of a suite 13:00:00 [MikeS] ...mimick format of Http in RDF 13:00:47 [MikeS] third bullet says, " 13:01:38 [MikeS] SAZ: can we have a provisional relation to publish contingent upon discussion of abstract on mailing list? 13:02:26 [MikeS] third bullet implicitly refers to EARL - might be a good palce to actually repeat or reiterate the relationship once abstract/intro is redone 13:02:45 [MikeS] under use cases 13:02:54 [MikeS] zakim, unmute me 13:02:54 [Zakim] MikeS should no longer be muted 13:04:59 [shadi] 13:05:31 [MikeS] SAZ: WAI web site lists all publications and relationships betwen them 13:05:46 [MikeS] ...who is each doc for, what is it used for, etc. 13:06:14 [MikeS] ...is it worth pointing back to this URL 13:06:24 [MikeS] ..to provide an overview for first-time readers 13:06:27 [MikeS] zakim, mute me 13:06:27 [Zakim] MikeS should now be muted 13:07:41 [MikeS] given our time-frame, +1 for working it out on list 13:08:42 [shadi] RESOLUTION: go ahead with publishing Representing Content in RDF, pending changes to the abstract and introduction sections 13:09:24 [shadi] action: CV to provide an updated abstract and introduction section for Representing Content in RDF document 13:10:04 [shadi] zakim, take up next 13:10:04 [Zakim] agendum 3. "Draft ERT WG Charter" taken up [from shadi] 13:10:52 [MikeS] SAZ: publication of charter must occur in June so little time left 13:11:28 [MikeS] ..time line needs adjustment; far too agressive 13:11:48 [MikeS] ...on the other hand, need to push as far as possible to get EARL out 13:11:56 [shadi] 13:12:01 [MikeS] zakim, unmute me 13:12:01 [Zakim] MikeS should no longer be muted 13:14:57 [MikeS] SAZ: heading is missing bc missing in W3C-wide template 13:16:04 [MikeS] MS: test description language part of charter for a potential deliverable? 13:18:54 [MikeS] SAZ: need to recruit members and otehr development/test organizations for feedback, requirements, and support 13:19:17 [MikeS] ...part of TCDL is in Bentoweb project 13:19:58 [MikeS] CV: +1 for committing resources to effort 13:20:46 [MikeS] JK: +1 13:21:08 [MikeS] SAZ: believe CI was also interested so unanimity in effort 13:21:27 [MikeS] ...how does it look in teh charter? 13:22:25 [MikeS] ...proposed an analysis and requirements document as a deliverable 13:22:56 [MikeS] ...once completed, we can recharter with more specific deliverables 13:23:27 [JohannesK] RDFa test case descriptions: < > 13:23:38 [MikeS] ...workging group note 13:26:06 [MikeS] SAZ: in parallel with completion of EARL, consider a reorientation of the group 13:26:25 [MikeS] ...test description languages 13:26:53 [MikeS] ...how does EARL and supplementary docs fit into toher W3C work - RDFA, POWDER, Content Transformation, Mobile web 13:27:39 [MikeS] ...focus deliverable that describs how EARL fits into these other efforts 13:30:29 [EtnaRosso] EtnaRosso has joined #er 13:30:38 [EtnaRosso] hi all, hi shadi 13:30:50 [EtnaRosso] Is a meeting in progress here? 13:30:56 [shadi] yes 13:30:59 [CarlosV] Christophe's analysis: (Test Suites' State of the Art and Quality Assurance Methods for W3C Recommendations) 13:31:31 [CarlosV] Date: 28 February 2005 (a little bit old) 13:31:53 [EtnaRosso] see you 13:31:58 [EtnaRosso] EtnaRosso has left #er 13:36:18 [MikeS] SAZ: no meeting Jun 2 13:36:29 [MikeS] ..sorry - Jun 4 13:36:47 [MikeS] on vaca week of Jun 9 13:37:13 [Zakim] -Johannes.a 13:37:15 [Zakim] -Johannes 13:37:18 [Zakim] -shadi 13:39:33 [shadi] zakim, drop mikes 13:39:33 [Zakim] MikeS is being disconnected 13:39:35 [Zakim] WAI_ERTWG()8:30AM has ended 13:39:36 [Zakim] Attendees were shadi, Johannes, MikeS 13:39:39 [shadi] zakim, bye 13:39:39 [Zakim] Zakim has left #er 13:39:44 [shadi] rrsagent, make logs world 13:39:47 [shadi] rrsagent, make minutes 13:39:47 [RRSAgent] I have made the request to generate shadi 13:39:48 [shadi] rrsagent, make logs world 13:39:58 [shadi] rrsagent, bye 13:39:58 [RRSAgent] I see 2 open action items saved in : 13:39:58 [RRSAgent] ACTION: SAZ remove "namespace" from table 2 (these are not namespaces) [1] 13:39:58 [RRSAgent] recorded in 13:39:58 [RRSAgent] ACTION: CV to provide an updated abstract and introduction section for Representing Content in RDF document [2] 13:39:58 [RRSAgent] recorded in
http://www.w3.org/2008/05/28-er-irc
CC-MAIN-2016-44
refinedweb
1,605
53.75
Android, Rx and Kotlin: a Case Study Android, Rx and Kotlin: a Case Study Join the DZone community and get the full member experience.Join For Free Learn how to build stream processing applications in Java-includes reference application. Brought to you in partnership with Hazelcast. There are countless introductions to Rx and quite a few discussing Rx on Android, so instead of writing another one, I decided to come up with a simple activity and go through the entire exercise of implementing it using Rx and Kotlin. I’m sure you’ll be able to follow these article easily even if you’re not familiar with Kotlin because the syntax is remarkably similar to what you would write if you were using Java 8 (just with fewer semi colons). The activity It’s shown at the top of this article. It’s pretty simple while covering some important basics and, as we’ll find out along the way, the devil is in the details. Here is a simple functional specification of this activity: - The user types a nick name in an EditText. The activity asks the server if such a name is known and if it is, it returns a user record. - At this point, the user can “Add” this person as a friend, which triggers another call to the server to verify that the addition is allowed. The server returns a simple “ok” or “error” if that person can’t be added as a friend. A few additional details: - We want to display a progress bar during all server calls. - Since we don’t want to bother the server too much, we only start sending requests for names that have three or more characters (we’ll add to this condition later). Without Rx Implementing this activity with “regular” Android practices is straightforward: - Add a listener to the EditText so we get notified each time a character is typed. - Send a network request with an AsyncTask. - When the result comes, update the UI (on the main thread and not in whatever thread AsyncTask ended up running). - Enable the “Add friend” button and listen to it, calling the server if pressed to verify that the friend can be added (one more AsyncTask + main thread post tap dance). This implementation is straightforward but it’s very scattered. You will very likely end up with a lot of empty methods added just to satisfy listener requirements, storing state in fields to communicate between the various asynchronous tasks and making sure your threading model is sound. In other words, a lot of boiler plate, a messy mix of headless and graphical logic and graphical update code spread a bit everywhere. There is a better way. Kotlin and Android I found Kotlin to be a very good match for Android even in the early days but recently, the Kotlin team has really cranked up their support for Android and adding specific functionalities for the platform in their tooling, which makes Kotlin even more of a perfect match for Android. Kotlin M11 was released about a week ago and it added a functionality that makes the appeal of Kotlin absolutely irresistible for Android: automatically bound resources. Here is how it works. Suppose you define the following View in your layout activity_search.xml: <Button ... android: All you need to do is add a special kind of import to your source: import kotlinx.android.synthetic.activity_search.addFriendButton The server For the purpose of this article, I’m just mocking the server. Here is its definition: trait Server { fun findUser(name: String) : Observable<JsonObject> fun addFriend(user: User) : Observable<JsonObject> } If you think this definition looks a lot like a Retrofit service interface, it’s because it is. If you’re not using Retrofit, you should. Right now, I’ll be mocking this server by returning a set of hardcoded answers and also making each call sleep one second to simulate latency (and so we can see the progress bar on the screen). Note that each call on this interface returns an Observable, so they fit right in with our Rx implementation. In this example, I hardcoded the server to know about two friends (“cedric” and “jon”) but only “cedric” can be added as a friend. The Rx mindset Switching to the Rx mindset requires you to start thinking in terms of event sources (observables) and listeners (subscribers). If this idea doesn’t sound that novel, it’s because it’s not. This model was already being advocated in the book “Design Patterns” in 1994 and even in the early versions of Java twenty years ago (and no doubt you can find traces of it in the literature before that). However, Rx introduces new concepts in this idea that we’ll explore in this series. So let’s rethink our activity in Rx terms: what are event sources (I’ll use the name “observable” from now on) in this activity? I can count four observables: - First, we have the EditText: whenever a new character is typed, it emits an event that contains the entire text typed so far. We can emit a new name once we have more than three characters. - Next is the name observable, which calls the server and emits the JsonObject it receives in response. - Next in the chain, we have a “user” Observable, which maps the JsonObject into a User instance with the name and id of that person. - Finally, the “Add friend” button is another observable: if the user presses that button, we make another call to the server with the User we have and we update our UI based on the results. There are various ways we can break this problem into observables and the final result depends on how you want to handle various tasks, which observables you want to reuse, the threading model you prefer, etc… Implementation The “EditText” Observable Let’s start with our EditText. Its implementation is pretty straightforward: WidgetObservable.text(editText) .doOnNext { e: OnTextChangeEvent -> addFriendButton.setEnabled(false) loading.setVisibility(View.INVISIBLE) } .map { e: OnTextChangeEvent -> e.text().toString() } .filter { s: String -> s.length() >= 3 } .subscribe { s: String -> mNameObservable.onNext(s) } Let’s go through each line in turn: - WidgetObservable turns an ordinary View into an Observable. It’s a wrapper coming from RxAndroid that calls all subscribers with the full text whenever a new character is typed. - Next we reset the UI to its default state. - The map line converts an OnTextChangeEvent into a string. It’s a purely convenience step, so that the next operators in the chain can deal with the context of the EditText as a String instead of having to repeatedly extract it from the event (e.text().toString() everywhere). - Next, if the text is less than three characters long, we stop right there. - Finally, we subscribe to the value we have obtained if we have reached this far: a string that's at least three characters long. We pass this string to our name observable. The "name" Observable val mNameObservable: BehaviorSubject<String> = BehaviorSubject.create() Let's see how we use that Observable now, by simply subscribing to it, which means receiving names that have three or more characters in them. All we do is call the server and pass the result to the "user" observable: mNameObservable .subscribe{ s: String -> mServer.findUser(s).subscribe { jo: JsonObject -> mUserObservable.onNext(jo) } } We're not quite done, though: we actually have another subscriber to that Observable: mNameObservable .subscribe { s: String -> loading.setVisibility(View.VISIBLE) } We need to let the user know we just issued a network call, so we show the progress bar (this is a suboptimal implementation, this logic should be done at the server level, but we'll save this for later). Note that I'm intentionally hiding a very important part of this logic in order to stay focused on the topic, and this also explains why we have two separate subscriptions. I explain why at the end of this article. The "User" Observable Next, we have the User Observable, which gets notified when the server sends us a response to the query "Does the user named 'foo' exist?": mUserObservable .map { jo: JsonObject -> if (mServer.isOk(jo)) { User(jo.get("id").getAsString(), jo.get("id").getAsString()) } else { null } } .subscribe { user: User? -> addFriendButton.setEnabled(user != null) loading.setVisibility(View.INVISIBLE) mUser = user } This Observable does two things: it updates our UI and it maps the JsonObject response to our data classUser. If the call was a success, we assign this value to the field mUser. The "Add friend" Observable Finally, we have the "Add friend" button, which only gets enabled once we have a valid User. If the user presses that button, we issue another call to the server to request that person to be added as a friend and then we update the UI depending on the response: ViewObservable.clicks(addFriendButton) .subscribe { e: OnClickEvent -> mServer.addFriend(mUser!!) .subscribe { jo: JsonObject -> val toastText: String if (mServer.isOk(jo)) { toastText = "Friend added id: " + jo.get("id").getAsString() editText.setText("") } else { toastText = "ERROR: Friend not added" } Toast.makeText(this, toastText, Toast.LENGTH_LONG).show(); } } Stepping back This is a very different implementation of how you would write the code with regular Android calls, but in the end, it's not just compact but it also divides our entire logic in four very distinct components that interact with each other in very clear ways. This is the macro level. At the micro level, these four components are not just self contained, they are also highly configurable thanks to operators, operations you can insert between your Observable and your Subscriber and which transform the data in ways that are easier for you to handle. I only have one such example of this in the code above (transforming anOnTextChangeEvent into a String) but you get the idea. Another benefit that should be immediately obvious to you even if you don't buy into the whole Rx paradigm shift yet is that thanks to Rx, we now have a universal language for observables and observers. I'm sure that right now, your Android code base contains a lot of such interfaces, all with subtly different method names and definitions and all needing some adapaters to be inserted before they can talk to each other. If ever you felt the need to write an interface with a method called "onSomethingHappened()", Rx will be an immediate improvement. Operators I have barely touched upon operators and this topic in itself is worthy of an entire book but I'd like to spend a few minutes to give a quick example of the power of operators. Going back to our activity, remember that as soon as the user types more than three characters, we send a query to the network for each character typed. This is a bit wasteful: a lot of phone users are very fast typists and if they type letters in quick succession, we could be sparing our server some extra work. For example, how about we define that we only call the server when the user stopped typing? How do we define "stopped typing"? Let's say that we'll decide that the user stopped typing if two keypresses are separated by more than 500ms. This way, a quick typing of "cedric" will result in just one server call instead of four without this function. How do we go about implementing this? Again, the traditional approach would mean that each time our text change listener is invoked, we compare the current time with the timestamp of the last character typed and if it exceeds a certain value, we trigger the event. As it turns out, observables have an operator that does this for us called debounce(), so our code becomes: WidgetObservable.text(editText) .doOnNext {(e: OnTextChangeEvent) -> addFriendButton.setEnabled(false) loading.setVisibility(View.INVISIBLE) } .map { e: OnTextChangeEvent -> e.text().toString() } .filter { s: String -> s.length() >= 3 } .debounce(500, TimeUnit.MILLISECONDS) .subscribe { s: String -> mNameObservable.onNext(s) } I know what you're thinking: "You just picked a problem that could be solved by an operator that already exists". Well, kind of, but that's not my point. First of all, this is not a made up problem and I'm sure a lot of developers who write user interface code will agree that this is pretty common. However, my point is more general than this: the debounce() operator has nothing to do with Android. It is defined on Observable, which is the base library we are using. It's an operator that's generally useful to have on any source that emits events. These events might be graphical in nature (as is the case here) or of any other kind, such as a stream of network requests, coordinates of a mouse cursor or capturing data from a geolocation sensor. debounce() represents the general need for getting rid of redundancies in streams. Not only do we get to reuse an existing implementation without having to rewrite it ourselves, we preserve the locality of our implementation (with the traditional approach, you would probably have polluted your class with a couple of fields) and we maintain the composition abilities of our observable computations. For example, do you need to make sure that the user is not adding themselves before calling the server? Easy: WidgetObservable.text(editText) // ... .filter { s: String -> s.length() >= 3 } .filter { s: String -> s != myName } Wrapping up At this point, you should probably take a look at the full source so you can step back and see how all these pieces fit together. It's obvious to me that the view of decomposing your problem in terms of observables that emit values that subscribers observe is extremely powerful and leads to cleaner, more self contained and composable code. The non-Rx version of this class feels incredibly messy to me (a lot more fields holding state, methods added just to satisfy slightly incompatible listener interfaces and a total lack of composability). Having said that, our work here is not over: - The threading model is all wrong. I intentionally omitted any thread consideration in this article in order to stay on topic but the code as it is right now is extremely suboptimal. It works but you shouldn't ship it in its current form. In the next installment, I will show how Rx makes it trivial to get Android's multithreaded model right. - There is a lot of UI code peppered through the business logic. It's messy, it obfuscates how our UI works and it's hard to maintain. We'll have to fix that as well. Stay tuned! Learn how to build distributed stream processing applications in Java that elastically scale to meet demand- includes reference application. Brought to you in partnership with Hazelcast. Published at DZone with permission of Cedric Beust , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/android-rx-and-kotlin-case
CC-MAIN-2018-30
refinedweb
2,496
61.06
Opened 7 months ago Closed 7 months ago #8371 closed bug (invalid) ghci byte compiler + FFI crashes when used with embedded R Description The ghci interpreter destroys the C stack when initializing embedded R (the statistical software system available at). There is no problem using embedded R with ghc (compiled code). I have had no problems using ghci with other FFI projects, and this does not appear to be a linking problem (there are no undefined references). To reproduce the problem (under Fedora Linux using ghc 7.6.3) download the R source code, unpack, and (using haskellRtest.hs is attached): - cd R-3.0.2 - ./configure --enable-R-shlib - make - make install - cd <haskelltestdir> - ghci -L/usr/local/lib64/R/lib -lR haskellRtest.hs - Main> main Initialize R session... Error: C stack usage is too close to the limit Notes: - No computations are done, the failure happens during startup. - The C functions called are in <R source>/src/unix/Rembedded.c - The error message is issued from <R source>/src/main/errors.c - I tried increasing the system level C stack size limit but this didn't help. - As noted above, there are no problems when ghc is used. Attachments (1) Change History (9) Changed 7 months ago by dsamperi comment:1 Changed 7 months ago by rwbarton comment:2 Changed 7 months ago by dsamperi It works with the command line you provide here, but as I noted in the report there are no problems when ghc is used. When I try to use -threaded with ghci I get the warning "-debug, -threaded and -ticky are ignored by GHCi". comment:3 Changed 7 months ago by dsamperi This is just a stab in the dark, but while reviewing the docs on FFI I discovered that it is assumed ints can be used for 64-bit addressing, that is, the difference between two pointer values can be stored in an int. But under Windows this is not so (32-bit ints), and I think R also employs 32-bit ints. If this is the source of the problem then it should show up in both ghc and ghci, but it does not. Again, just a stab in the dark... comment:4 Changed 7 months ago by carter Have you tried testing to see if the problem also happens with ghc head ? Ghci prior to 7.7 has it's own custom linker and is the culprit behind many ghci specific bugs. comment:5 Changed 7 months ago by dsamperi Thanks for the suggestion. I tried to build from HEAD but it requires Happy 1.19, and only version 1.18 would install (due to a global constraint?). So I used the lazy method of downloading a pre-built binary for Linux from, specifically, I installed from ghc-7.7.20130720-x86_64-unknown-linux.tar.bz2. Unfortunately, this did not resolve the problem, as I still get the C stack usage Error. comment:6 Changed 7 months ago by rwbarton I can reproduce this without ghci, by putting a forkIO around the body of main (and adding a threadDelay in the main thread). It seems to just be an interaction between R's method for determining the base address of the stack and the way pthread allocates stacks for new threads. Try this C example program pt.c. #include <stdio.h> #include <unistd.h> #include <pthread.h> int Rf_initEmbeddedR(int argc, char **argv); void *foo(void *blah) { char *args[] = {"pt", "--gui=none", "--silent", "--vanilla"}; int r; setenv("R_HOME", "/usr/lib/R", 1); r = Rf_initEmbeddedR(sizeof(args)/sizeof(args[0]), args); printf("r = %d\n", r); } int main(void) { pthread_t tid; pthread_create(&tid, NULL, foo, NULL); while (1) sleep(1); return 0; } rwbarton@adjunction:/tmp$ gcc -o pt pt.c -lpthread -lR rwbarton@adjunction:/tmp$ ./pt Error: C stack usage is too close to the limit Error: C stack usage is too close to the limit r = 1 It would probably be best to just disable R's stack limit checks, if possible. comment:7 Changed 7 months ago by dsamperi I accidentally replied to you in gmail (sent to ghc-devs) instead of in this comment thread, sorry! Your comment combined with the suggestion that I use ghc-7.7 provides a work-around. I tried disabling R's stack limit checks, but this leads to a segfault. A correct workaround is to use the flag -fno-ghci-sandbox, as this prevents ghci from forking a thread (all computations are run in the main thread). As noted previously R is not thread-safe. This eliminates the "C stack usage" error messages, but there is still a segfault when ghc-7.6.3 is used (and a non-trivial computation is done). Using ghc-7.7 fixes this. Thanks! comment:8 Changed 7 months ago by rwbarton - Resolution set to invalid - Status changed from new to closed Great, glad you were able to get it working! Does it work when you compile with the threaded runtime, like ghci uses? (ghc -threaded haskellRtest.hs -L/usr/local/lib64/R/lib -lR should do it)
https://ghc.haskell.org/trac/ghc/ticket/8371
CC-MAIN-2014-15
refinedweb
852
72.66
A module is a Python file that contains Python executable statements and methods; while, a Python function is a group of related statements that are called to perform a specific task. One of the Python modules is the aifc module, which has the getparams() function. The getparams() function of the aifc module will form the basis of this shot. The AIFC module supports the reading and writing of the Audio Interchange File Format, a format for storing digital audio samples in a file. This module helps a programmer to write into and read from an audio file with ease. AIFC files contain digitally sampled sound, like the ones stored in CD-ROMs. An AIFC file, on the other hand, is a compressed AIFF audio file used by media players and gaming consoles. This implies that an AIFC file has a smaller file size compared to same file of AIFC format. getparams()function The getparams() function is a function inside the AIFC module. From our definition of a earlier, we understood that a function is a group of statements that perform a specific task. The getparams() function of the aifc module is a function that returns a namedtuple(). See the syntax below: aifc.getparams() namedtuple() namedtuple()contents: (nchannels, sampwidth, framerate, nframes, comptype, compname) Let’s understand what happens when we call the getparams() method: import aifc aifc_object = aifc.open('beats.aiff','r') print ( "params:", aifc_object.getparams()) aifc_object.close() Output => params: _aifc_params(nchannels=2, sampwidth=3, framerate=51200, nframes=88977, comptype=b'NONE', compname=b'not compressed') Note: We used an imaginary audio file called beats.aiff. The first line of the code snippet is used to import the aifc module, which houses the getparams() function. After we have imported the aifc module, we will have access to all functions inside it, including getparams() (the interest in this shot). The second code snippet allows us to open and read the content of our audio file (beats.aiff). This creates an instance of the aifc class that makes the getparams() function accessible to us. The third line that contains the print statement is used to print the output of the getparams() function call. We will look into the interesting output of this line of code soon. We are required to close the file after we are done with the operation we want to perform. This is the function of line 4. The output of the getparams() object method is namedtuple(). To better understand this output, let us consider what a namedtuple() is. namedtuple() namedtuple() is a Python function inside the collections module. This is used to create tuples with named fields – the items of the tuple can be accessed using the field names and the dot notation. namedtuple() makes Python codes more readable by accessing values through field names instead of integer indices, which is difficult to read and understand. In addition to code readability, namedtuple() helps to write cleaner codes, which are easy to maintain. Let us delve into the content of the namedtuple(), which is returned by the getparams. An audio file has number of parameters describing the audio data as demonstrated in the output of the code snippets above. They are as follows: Sampling rate or frame rate: This counts how many times a sound is sampled and it is measured per seconds. Number of channels: There are different types of audio files and this ranges from stereo, mono, quadro, etc. This function of this parameter is to detect and indicate if an audio file is of type stereo, mono, or quadro. Frame: This consists of one sample per channel. Sample size: This is the size in bytes of each sample. A frame is made up of nchannels * samplesize bytes, and a second’s worth of audio consists of nchannels * samplesize * framerate bytes. From the example above, we have a CD quality audio has a sample size of two bytes (16 bits), uses two channels (stereo) and has a frame rate of 51200 frames/second. This gives a frame size of 4 bytes (2*2), and a second’s worth occupies 2*2*51200 bytes (204,800 bytes). Python, as a high-level language, has so many modules that makes the work of developers simple. File handling is an important operation in every programming language, including python; and, because it is open source, more modules will be added. The aifc module is just one of many wonderful modules in Python. Also, the getparams() function is one of many functions in the aifc module. You may want to visit the official Python docs to read more on the Python aifc module. RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/what-is-aifc-getparams-function-in-python
CC-MAIN-2022-33
refinedweb
776
63.09
OK…here’s a list of links that grabbed my attention this week: - The PHP on Windows Training Kit (which contains LOTS of great demos for almost anything that is PHP on Windows) has been updated so it can be installed on Windows 7: - Are you ever been annoyed by having to restart your Web server or application pool after modifying your php.ini file? With IIS, now you don’t have to…just update the MonitorChangesTo setting in FastCGI to automatically pick up changes to your php.ini file: - There has been lots of talk about the NoSQL movement recently. I thought Anders Karlsson took a fair look at NoSQL vs. RDBMS in his blog (and the discussion that follows is good too): - PHP 5.3 namespaces explained: - 10 regular expressions for efficient Web development: - This is actually a link a discovered a while back, but it came up again in conversation this week (Building the PHP MS SQL Server extension from source on Ubuntu 8.10): As always, I hope some of those are useful…or at least interesting. Feel free to share your favorite links in comments. Thanks. -Brian
https://blogs.msdn.microsoft.com/brian_swan/2010/04/02/this-weeks-link-list-april-2-2010/
CC-MAIN-2017-13
refinedweb
192
65.15
That is because the ethernet add-on that you're using is more than likely also using the SPI bus. .......For my own project last year, I went the bit-bang route. I only had two strings of 20 LEDs each. I used the analog pins (of all things) to control the strings, A0 and A1 for one, and A2 and A3 for the other. Note: bit banging IS slower than SPI, so depending on how fast you plan on sending data to the LEDs, bit-banging them may not work for you. For me it was plenty fast still. Just set everything to white first (you don't need an array for that), then cycle through the BlueLEDgroup array and turn those blue. When you're done with that, then you can call FastSPI_LED.show() which will turn the LEDs on. strip.setPixelColor(21,Color(0, 0, 255)); #include "SPI.h"#include "Adafruit_WS2801.h"//DEFINE OUTPUT PINSint dataPin = 2; //Yellow wireint clockPin = 3; //Green wire//SET NUMBER OF PIXELSAdafruit_WS2801 strip = Adafruit_WS2801(20, dataPin, clockPin);//PIXEL ARRAYSbyte Pete[] = { 0, 19, 43, 63};byte Stephen[] = { 25, 32, 37, 59, 60, 63, 71};byte Jack[] = { 20, 59, 61, 68};//SETUPvoid setup(){ strip.begin(); strip.show(); Serial.begin(9600);}//CHECK & UPDATE LOOPvoid loop(){ colorFade(Color(0, 0, 255), "Pete"); } delay(10000); //wait 10 seconds before connecting again }// MAIN FUNCTIONS//Fade to colorvoid colorFade(uint32_t c, char* personsname) { int i, j; for (c=0; c < 256; c++) { for (i=0; i < sizeof(personsname); i++) { //Can't get this to work. I can't figure out how to make the function look up the values of the pixel array using the variable 'personsname'. It works if a name is entered directly instead of "personsname", e.g. "Jack" will light up the correct LEDs. strip.setPixelColor(personsname[i], c); //Same here. } strip.show(); // write all the pixels out delay(50); Serial.print("Fade In: ");Serial.print(personsname);Serial.println(""); }} Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=122793.msg937737
CC-MAIN-2015-11
refinedweb
358
64.91
#include "FBX_API.h" #include "FBX_SceneProxy.h" #include <UT/UT_Map.h> #include <UT/UT_String.h> #include <UT/UT_StringHolder.h> Go to the source code of this file. Definition at line 24 of file FBX_AnimationUtils.h. Add extra channels to the clip for any geometry nodes with blendshapes. Add extra channels to the clip for any user-defined properties. Find nodes to bake animation data and geometry for. If minimal_nodes is enabled, only joints and visible nodes with geometry will be included in the rig. If keep_deforming_shape_xforms is disabled, nodes for deforming geometry will be omitted from the rig but still included in the list of geometry nodes ('geo_infos').
https://www.sidefx.com/docs/hdk/_f_b_x___animation_utils_8h.html
CC-MAIN-2022-05
refinedweb
107
62.54
On Thu, Jan 15, 2009 at 02:37:56PM +0000, M?ns Rullg?rd wrote: > Michael Niedermayer <michaelni at gmx.at> writes: > > > On Thu, Jan 15, 2009 at 12:43:27AM +0000, M?ns Rullg?rd wrote: > >> Aurelien Jacobs <aurel at gnuage.org> writes: > >> > +/** > >> > + * converts fourcc string to int > >> > + */ > >> > +static inline av_pure int ff_get_fourcc(const char *s){ > >> > + assert( strlen(s)==4 ); > >> > + return (s[0]) + (s[1]<<8) + (s[2]<<16) + (s[3]<<24); > >> > +} > >> > >> This looks a lot like AV_RL32(). > > > > indeed and i wouldnt mind seeing all ff_get_fourcc replaced by it > > > >>? good point even if i wouldnt consider this a very realistic scenario but as the code can and should be replaced by direct use of AV_RL32() theres little point in fixing: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-January/067530.html
CC-MAIN-2014-42
refinedweb
121
73.78
I've been developing for nearly 20 years now, and in all that time I've had the privilege to program in a multitude of different languages. Each language has its own beauty and features that make it great, but if I had to choose one feature I would miss greatly if I could never use it again, it would be LINQ. LINQ adds enormous power to the .NET Framework through both the libraries it contains and the language additions that power it. It can help you write powerful code faster and that is less error prone, and yet some people still seem to eschew it for various reasons. More times than not, I believe this is still because people don't really understand what LINQ can offer or how to use it, and thus avoid it. My goal in this post is to demystify LINQ for the .NET beginners and show it for the little wonder that it is. What is LINQ? LINQ is a major component of the .NET Framework and is one of the things that makes the platform so truly unique. LINQ is an acronym that stands for Language INtegrated Query and has several components: - Providers - Libraries that enable querying different types of collections (LINQ to objects, LINQ to SQL, etc.) - Language Extensions - Several new language features were added to .NET languages to support LINQ (lambda expressions, extension methods, anonymous types, etc.) - Operations - Defines several ways to query sequences (Where, Select, etc.) Each of these components help to give LINQ its power and ease-of-use. Fortunately, you don't need to know about everything in LINQ to begin using it immediately, so let's just take a brief look inside. Providers The providers are libraries that enable you to query a given source using LINQ. Think of a LINQ provider as the libraries that define operations that use the language extensions to allow LINQ to query the provided data. There are providers for SQL Databases (LINQ to SQL), for sequences of objects (LINQ to objects), for XML (LINQ to XML), etc. For now, let's stick with LINQ to objects, since it is one of the simpler concepts and yet has the widest applicability - nearly any program can benefit from it as nearly all programs have sequences of objects. Language Extensions Microsoft added several new framework components to help make LINQ a reality. The bonus is, this not only benefits LINQ, but they are useful features in their own right.Extension Methods Extension methods allow you to essentially call a static utility method that "extends" a type in a clean, fluent syntax. As an illustration, say you have some (very contrived) static methods that operate on int: public static class IntExtensions { public static int Half(int source) { return source / 2; } public static int Cube(int source) { return (int)Math.Pow(source, 3); } public static int Square(int source) { return (int)Math.Pow(source, 2); } } These methods, in effect, extend the functionality of int in a logical way by adding additional methods that operate on the public interface of int. The problem is, they are bulky to call. Say you want to take 13, cube it, half it, then square it, you'd have to write: IntExtensions.Square(IntExtensions.Half(IntExtensions.Cube(13))); Which is very wordy and not nearly as easy to read. Extensions methods are just a bit of syntactical sugar that let utility methods like this that "extend" a type logically behave as if they were first-class methods. To make a static method an extension method, all we need do is put it in a static class and make the first argument an instance of the type we want to "extend" and precede it with the this keyword: public static class IntExtensions { public static int Half(this int source) { return source / 2; } public static int Cube(this int source) { return (int)Math.Pow(source, 3); } public static int Square(this int source) { return (int)Math.Pow(source, 2); } } Now, we can call the methods as if they were first-class methods and get: 13.Cube().Half().Square(); Which is much easier to read! Why is this syntactic sugar so important? Because many of the LINQ query operators we will see later are implemented through extension methods as you will see in a bit. This gives LINQ it's fluent feel and makes chaining operations together seem natural and fluid.Iterators Iterators are one of the core enhancements to the framework that give LINQ (and you) a lot of power to create queries with deferred execution. This means it provides a way for you to be able to return a sequence of objects one item at a time, as they are requested. For example, let's say you wanted to find the even numbers in a list, you could do this: public List<int> GetEvens<int>(List<int> source) { var results = new List<int>(); foreach (var item in source) { if ((item%2) == 0) { results.Add(item); } } return results; } While this works, if we only wanted the first five even numbers out of the list, this would be overkill! Iterators allow you to create an algorithm that returns the next item as it's requested: public IEnumerable<int> GetEvens(List<int> source) { foreach (var item in source) { if ((item%2) == 0) { yield return item; } } } Notice we don't create a container to hold every possible result, we just return each item with a yield return statement. Thus, each item is only computed when it is requested. So, if we only iterate over the first 5 items in the collection, only those get computed. This also means that the query is not run until you begin iterating over it. For example, lets say we have a List of 1000 integers and we want to find the evens, but clear it before we iterate: var items = Enumerable.Range(1, 1000).ToList(); var evens = GetEvens(items); items.Clear(); // no items are printed, because the source was cleared // before the query was iterated over foreach (var i in evens) { Console.WriteLine(i); } This is a key concept in LINQ, in fact you shouldn't think of calling a function that returns an iterator as returning all results, but returning a state machine that will give you the next result as you iterate over it. Thus, when we call var evens = GetEvens(items) we are only creating a query over the items, not the result set. So when we clear the source collection, and then execute the query, it will yield no results. The other language feature that helps make LINQ (and in general, .NET) so powerful are lambda expressions. Lambda expressions make it easy to write short, anonymous methods at the point where they are used. Is the syntax a bit new and frightening for new developers? Perhaps, but once you understand their syntax they are enormously powerful and truly improve a program's readability. The .NET Framework has had delegates since the beginning. Delegates are very powerful as they allow you to store a reference to a method in a variable, and use that variable to invoke the method later. Delegates give the programmer the power to be able to specify functionality to be invoked generically without needing to subclass. The only problem with working with delegates in early .NET was that you would need to define a full-blown method to assign to the delegate, even for potentially trivial functionality. Then, in .NET 2.0 they added anonymous method syntax, which let you assign an anonymous method to a delegate on the fly: Predicate<int> numCheck = delegate(int num) { return num % 2 == 0; }; Which we can then invoke: if (numCheck(13)) { ... } Well, lambda expressions just took the anonymous method syntax and simplified it even further: Predicate<int> numCheck = (int x) => { return (x % 2) == 0; }; The => operator is often pronounced as "goes to" and separates the args list from the body. There are a lot of simplifications that can be done with lambda expressions. First of all, if the type of the parameters can be inferred, you can omit the type. Further, if the body is a single statement you can omit the curlies and if the only statement is returning an expression you can omit the return. Thus, these are really the same delegate: Predicate<int> numCheck = (int x) => { return (x % 2) == 0; }; Predicate<int> numCheck = x => (x % 2) == 0; So again, why am I spending time discussing lambdas? Because they are the best way to specify logic concisely at the point of use. This is important because it can make expressions easier to read and maintain. Plus, you won't have to clutter up your source files with tons of single-line methods. There are other language additions as well (anonymous types, for example), but we'll save those for another time as you don't need them right away to get started with LINQ.Query Syntax The third language extension in .NET was the addition of the query syntax. As we will see in just a bit, many of the LINQ methods are handled through LINQ extension methods. While these read easy enough, Microsoft decided to give the query operations a more SQL-ish feel to make querying objects seem more natural. To truly appreciate the query syntax, we first need to discuss the different operations, so let's come back to this at the end. Operations There are many operations in LINQ, which are provided by extensions methods in the System.Linq assembly for querying sequences of object. Now, by sequence of object, we mean any IEnumerable<T>, such as List<T>, T[], HashSet<T>, etc. This is really where LINQ shines, because it can be used to query nearly any sequence! This is also why extension methods are so prominent, because they are used to extend IEnumerable<T> to add the operators in the System.Linq library. This is why extension methods were invented! It gives the ability to "add" functionality to an interface (among other types), which cannot be done directly in interfaces. And since most of the collections do not share a parent class, and different forms of querying would need different implementations of each operation, the extension methods are a clever way to add this functionality indirectly. Let's look at some of the key operations available, there are many more, but these are probably the most commonly used.Filtering We can filter any sequence of items using Where() to get a query that will provide the items that meet the criteria: ProjectionProjection // Get orders whose value is greater than 1000.00 var bigOrders1 = orders.Where(o => o.Price > 1000.0); Using Select(), we can transform a sequence from one type to another type. This is useful when you want to select a part of an object, or a composite object: Consistency CheckingConsistency Checking // Get just the list of order IDs from orders var orderIds = orders.Select(o => o.OrderId); Using consistency checking methods such as Any() and All() we can check if any one or all items meet a condition. UniqenessUniqeness // Return true if all orders are valid if (orders.All(o => o.IsValid)) { ... } // Return true if just one is invalid if (orders.Any(o => !o.IsValid)) { ... } The Distinct() operation will give us back the sequence with all duplicates removed. Now, it should be noted that to determine duplicates, your object has to correctly override both Equals() and GetHashCode(), in fact you will find this true for many of the LINQ methods that check equality. Positional SelectionPositional Selection // Get a list of unique order ids var ids = orders.Select(o => o.OrderId).Distinct(); There are several methods that allow you to get just the first, last, or an item that meet a given criteria. These methods will throw an exception if no such item exists, unless you use the ...OrDefault() variant of that method, in which case it returns the default(T) if not found. // Gets first order in list, or throws if empty var firstOrder = orders.First(); // Gets first order in list, or `null` if empty var firstOrderOrNull = orders.FirstOrDefault(); // Gets first order in list that is invalid, or throws if can't find one. var firstInvalid = orders.First(o => !o.IsValid); // Gets first order in list that is invalid, or null if can't find one. var firstInvalidOrNull = orders.FirstOrDefault(o => !o.IsValid); There Last() methods behave in the same manner, but return the last item in the sequence, or the last item that matches the condition respectively. In addition, there is a Single() method which is similar to First(), except it will throw if there is more than one item that matches as well. You can easily sort your sequences by one or more criteria in ascending or descending order. GroupingGrouping // get the list of items sorted ascending by order id, descending by last name var sorted = orders.OrderBy(o => o.OrderId).ThenByDescending(o => o.Name.Last); Using grouping, you can group items together based on a criteria. When you do this, the items will be collected into a sequence of groupings where the Key is the criteria you grouped on, and the grouping itself is a sequence of all items that match the key. // Get all orders grouped by department var grouped = orders.GroupBy(o => o.Department); foreach (var group in grouped) { Console.WriteLine("Department: " + group.Key); foreach (var item in group) { ... } } And so on, there are many operations that you can perform on sequences of objects, take a look at the System.Linq namespace to learn more. Query Language Now, we've seen that you can use the extension methods and query sequences of objects directly. This is all well and good and many people even prefer this syntax for representing their LINQ queries. That said, one of the language extensions in LINQ was adding a query language that makes the queries appear more SQL-esque. To use the query language, we start with a from statement that defines an item iterating over a sequence, for example from o in orders says that the sequence we are iterating over is orders and o will represent each item in turn (much like saying foreach (var o in orders) does). Then, each query must end with either a select clause (projection) or a group clause. // get list of order ids using query language var orderIds = from o in orders select o.Id; Once again, you can filter using the where clause to get items that satisfy a given condition: // get list of all valid orders var validOrders = from o in orders where o.IsValid select o.Id; SO which is better, the query language or using extension methods directly? That tends to be a matter of style and personal preference. There are some things the query language does not (yet) support directly (like FirstOrDefault()) but for many it can seem more natural. In the end, though, the same query written in either syntax will compile down to identical IL, so truly the choice is yours. Choose whichever you (and your team) find to be more readable and maintainable. Either way you should be happy with the results. Summary LINQ is one of the most wonderful things about working with .NET, I truly miss it when I code in other languages because of the ease in which it lets me write very complex code in a quick and maintainable way. In addition, these methods have all been thoroughly tested for you, so that's less custom code to test and maintain! Great article. I have to admit, I am new to Linq and love writing raw SQL. It's something I've done for over 20 years now. Do I lose any of that power if I move to Linq? I understand that I have one query language for a number of data stores, but does that come at a compromise? Great breakdown on the different features in LINQ. We're a C# shop at work, and it's become a staple in new development. There are some features I'm not completely comfortable with yet ("GroupBy" still trips me up sometimes), but in most cases I use it by default now without even thinking about it. Your description of the "yield" functionality was helpful. That's another one I've had a difficult time wrapping my head around, but describing it as a query instead of the actual results (similar to a "where" or "orderby" before calling "ToList") makes it much clearer. Thanks! As always great article Jim. Thanks Ash @JamesHare someone on reddit pointed out the following typo: where it returns nullinstead of throwing. @LelandRichardson: Doh! I'll get that cleaned up. Great article on LINQ! I've come to find LINQ extremely useful when manipulating collections of data, especially if I'm trying to transform a collection returned from the database to fit a UI design. I particularly enjoyed the fact that you took the time to break down the different language features that it utilizes. I believe the fastest route for developers to become comfortable with delegates/lambas and extension methods is through extensive LINQ utilization. One definite gotcha/pitfall is the delay of enumerations with LINQ due to the use of iterators. As you showed in the Iterators section, it's possible to delay enumeration until you call a method that forces it. As you demonstrate in the final code block of that section, your 'items' collection gets cleared before you actually enumerate, and therefore GetEvens()returns empty when it enumerates in your 'foreach' block. For that reason, I would suggest storing an enumerated result in a variable, such as a 'List' sooner rather than later if you know there's the potential for that collection to be altered before you have a chance to use it, or if you plan on using the results multiple times. If you use it multiple times, then the collection gets enumerated each time you use it. There are heavy implications there. Your collection could change underneath you without you realizing it, or there could be a performance hit because your method is being run every single time you use the object. As an aside, if one's company has the budget, I would strongly suggest looking into Resharper. (NOTE: I DON'T work at Resharper, and this isn't an ad for them.) It analyzes your code and makes suggestions for opportunities to use LINQ. For someone that's new to LINQ, it's nice to see how they could reorganize their code to use it with LINQ. @JesseLisby this is a good point. In general, I think a good rule of thumb is to make sure that an IEnumerablebe enumerated only once. Thus, if you are looping over a collection more than once, it is generally safe to store it in a list using the .ToList()method. @JesseLisby: agree completely. If you intend to store the result, drive it to a collection using things such as .ToList(), .ToDictionary(), .ToLookup(), .ToArray()etc. to remove the deferred execution. It should also be noted that some methods do not have deferred execution, such as First(), Count(), Any(), etc. And yes, I'm also a fan of tools such as ReSharper that will warn you when you are about to iterate a query multiple times as Leland notes. I think that's one of the things I always try to pound in is it doesn't return the results, it returns a query that serves the results. Thus, if you iterate over that query twice, you incur the cost of re-querying each time, which can be expensive if it has to, say, examine every element in the collection.
http://tech.pro/tutorial/1152/demystifying-linq
CC-MAIN-2014-10
refinedweb
3,292
61.26
Friday, July 06, 2001, 12:15:19 PM, dwall@myEastside.com wrote: >> RL> The InetAddress...getHostName() call will use the DNS DW> databases. >> RL> For most computers, however, this won't return anything useful. >> >> That is not true. Most of US IPs have PTR records. That includes your >> own IP, that you had when sending your msg. By far, most servers have DW> rDNS, >> most dynamic IPs do, most static IPs for cable/DSL do, and even most DW> routers >> do. DW> The IP address I was testing is 216.122.43.90 and I am able to do a reverse DW> lookup using dig from the webserver. It just seems to me that the DW> InetAddress class is perhaps not using whatever it needs to do to use DNS. DW> Does anybody know what the implementation of InetAddress is actually doing DW> under the hood? Well, the InetAddress methods do work correctly, Dave. Here is a quick demo: import java.net.*; public class IPGet { public static void main(String[] args) { try { System.out.println(InetAddress.getByName(args[0]).getHostName()); } catch (Exception e) { System.out.println(e); } } } and the console: C:\test>jikes -nowarn IPGet.java C:\test>java IPGet 216.122.43.90 r90-43-dsl.sea.lightrealm.net Now, for the kicker... On one run I got the same return as you did: the IP number instead of hostname - this happens when the lookup fails. Therefore, I would guess right now that here might be some problem in the nameservers at lightrealm. So, a partial dig shows: Dig 90.43.122.216.in-addr.arpa@199.224.86.20 ... Authoritative Answer Recursive queries supported by this server Query for 90.43.122.216.in-addr.arpa type=255 class=1 90.43.122.216.in-addr.arpa PTR (Pointer) r90-43-dsl.sea.lightrealm.net 43.122.216.in-addr.arpa NS (Nameserver) ns1.lightrealm.net and next: 07/06/01 12:50:19 ping ns1.lightrealm.net Ping failed, no such host That looks like a slam dunk. Lightrealm's problem, when they periodically can't resolve within their domain. Not a Java problem. HTH. DW> David
http://mail-archives.apache.org/mod_mbox/tomcat-users/200107.mbox/%3C10721667520.20010706132819@mailops.com%3E
CC-MAIN-2013-48
refinedweb
360
70.39
I found this code here which monitors the progress of downloads. - import urllib2 url = "" file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() while buffer = u.read(block_sz) read() while write() File objects and network sockets and other forms of I/O communication are data streams. Reading from them always produces the next section of data, calling .read() with a buffer size does not re-start the stream from the beginning. So yes, there is a virtual 'position' in streams where you are reading from. For files, that position is called the file pointer, and this pointer advances both for reading and writing. You can alter the position by using seeking, or by simply re-opening the file. You can ask a file object to tell you the current position, too. For network sockets however, you can only go forward; the data is received from outside your computer and reading consumes that data.
https://codedump.io/share/88pGPjM1hPzB/1/does-readsize-have-a-built-in-pointer
CC-MAIN-2017-09
refinedweb
213
70.09
MDX Custom Elements Disclaimer: This is an advanced topic that bends the internals of MDX to our will. It is not how you should be using MDX for everyday use. If you’re interested in some internal trickery then read on, if you’re looking to use MDX in a real project maybe check out the gatsby-mdx docs instead. The problem with HTML Long story short, when using MDX you end up with code block output that looks like this: <pre><code>const some = {}</code></pre> This means that to do interesting or novel things with the code from markdown code blocks, you have to replace the pre element in MDXProvider, not the code element… but the code element has all the interesting props. Also, if you plan to use pre without code you now have to check the children of the pre element to make sure it’s not code and then return a regular pre element. It’s all doable, but feels a bit messy. You can either cheat by just handling the code element and end up with an extra pre wrapping your code: <MDXProvidercomponents={{code: ({children,"react-live": useReactLive,...props}) =>useReactLive ? (<LiveCode {...props}>{children}</LiveCode>) : (<Code is="block" {...props}>{children}</Code>)}}/> or you can do some minor gymnastics to get the children’s props, etc. const components = {pre: ({ children: { props } }) => {// props is for MDXTag, props.props is for code elementconst lang =props.props.className &&props.props.className.split("-")[1];return <Code is="block" lang={lang} {...props} />;}}; An Alternative Path SO this is where we start talking about patching MDX. The patch isn’t terrible, but allows us to hook into the handlers during the MDXAST-to-MDXHAST conversion process. With these handlers we have a larger probability to do more damage, but also get more control because it’s where we determine props and how markdown gets converted into HAST (html ast). const toHAST = require('mdast-util-to-hast')const detab = require('detab')const u = require('unist-builder')+function mdxAstToMdxHast({ mdxAstHandlers }) {return (tree, _file) => {const handlers = {// `inlineCode` gets passed as `code` by the HAST transform.// This makes sure it ends up being `inlineCode`inlineCode(h, node) {return Object.assign({}, node, {type: 'element',tagName: 'inlineCode',properties: {},children: [{type: 'text',value: node.value}]})},code(h, node) {const value = node.value ? detab(node.value + '\n') : ''const lang = node.langconst props = {}if (lang) {props.className = ['language-' + lang]}// Mdast sets `node.meta` to `null` instead of `undefined` if// not present, which React doesn't like.props.metastring = node.meta || undefinedconst meta =node.meta &&node.meta.split(' ').reduce((acc, cur) => {if (cur.split('=').length > 1) {const t = cur.split('=')acc[t[0]] = t[1]return acc}acc[cur] = truereturn acc}, {})if (meta) {Object.keys(meta).forEach(key => {props[key] = meta[key]})}return h(node.position, 'pre', [h(node, 'code', props, [u('text', value)])])},import(h, node) {return Object.assign({}, node, {type: 'import'})},export(h, node) {return Object.assign({}, node, {type: 'export'})},comment(h, node) {return Object.assign({}, node, {type: 'comment'})},jsx(h, node) {return Object.assign({}, node, {type: 'jsx'})},+ ...mdxAstHandlers}const hast = toHAST(tree, {handlers})return hast}}module.exports = mdxAstToMdxHast After using this patch, we can set up our own handlers for code blocks for markdown. Here’s what it looks like for gatsby-mdx users {resolve: `gatsby-mdx`,options: {mdxAstHandlers: {code(h, node) {const value = node.value ? detab(node.value + "\n") : "";const lang = node.lang;const props = {};// Mdast sets `node.meta` to `null` instead of `undefined` if// not present, which React doesn't like.props.metastring = node.meta || undefined;const meta =node.meta &&node.meta.split(" ").reduce((acc, cur) => {if (cur.split("=").length > 1) {const t = cur.split("=");acc[t[0]] = t[1];return acc;}acc[cur] = true;return acc;}, {});if (meta) {Object.keys(meta).forEach(key => {props[key] = meta[key];});}return h(node.position, "code-block", { lang, ...props }, [u("text", value)]);}}}}; This is mostly the same as the default code node handler, but we’ve changed the output to be a code-block element and merged all the props into a single object. This means we can now use MDXProvider to replace code-block elements… That is, we’ve resolved our <pre><code> issue at the conversion to MDXHAST level, way before the eventual conversion into JSX, etc. Here’s how we can write an MDX components block to replace the code-block before it becomes HTML in the browser (or on SSR). import React from "react";import { MDXProvider } from "@mdx-js/tag";import Highlight, {defaultProps} from "prism-react-renderer";const components = {"code-block": ({ children, lang, ...props }) => {return (<Highlight{...defaultProps}code={children.trim()}language={lang}>{({className,style,tokens,getLineProps,getTokenProps}) => (<pre className={className} style={style}>{tokens.map((line, i) => (<div {...getLineProps({ line, key: i })}>{line.map((token, key) => (<span{...getTokenProps({ token, key })}/>))}</div>))}</pre>)}</Highlight>);}};export const wrapRootElement = ({ element }) => {return (<MDXProvider components={components}>{element}</MDXProvider>);}; Fin So, we’ve proved that hooking into the handlers is possible and also useful. We could expand on this to ship a set of handlers that makes working with markdown elements like code blocks, latex expressions, etc the responsibility of React components. If we shipped this by default with gatsby-mdx we could also ship a default set of components that handled the “custom elements” like code-block or inline-math, meaning that no one had to know but that also people who wanted to mess with internals have an easier time doing it. Is this a good idea? TBD. I haven’t thought through the ramifications of this approach in a widespread context, but I’m fairly certain it’s a better approach than advocating for AST manipulation across the board. That said, we do potentially lose the fact that html is sort of “standardized” in the sense that you can mash any pre element to see if it seems like it’s a code block (not everyone uses <pre><code> though, so it’s not foolproof anyway) in a document now but in this context you’d have to know about code-block. I made it! Here, have a git repo that shows you how to do this.
https://www.christopherbiscardi.com/post/mdx-custom-elements/
CC-MAIN-2019-47
refinedweb
1,017
58.08
This. A number of issues regarding the use of XML[XML] in HTML documents were brought to the attention of the W3C Hypertext Coordination Group. In particular, MathML[MathML] and RDF[RDF] are written in XML and intended to be used in HTML documents. In response, the coordination group held a meeting 11-12 Feb 1998 in San Jose, CA. We would like to thank the host, Sun Microsystems. As discussed in [Dialects], evolution of the HTML specification proceeds by introduction of new idioms which interact with deployed software in one of the following ways: For the past few years, the HTML Working Group has vetted new proposals on behalf of the web community, considering the value of each versus the cost of deployment. But with the introduction of XML into the web, markup design is decentralized. Each community or even each user can use whatever elements and attributes they choose and give them whatever meaning and significance they choose. As MathML and RDF show, at least some of this XML markup is intended for use inside HTML documents. This meeting explored mechanisms to use XML markup in HTML documents: existing mechanisms and possible enhancements. In particular: Participants from all W3C working groups, especially RDF, MathML, CSS&FP, and XML, and DOM were invited. A wide variety of experience and requirements were represented by the meeting participants: The participants request that W3C make the W3C site searchable. The Appendix B of [RDF] says: The recommended technique for embedding RDF statements in an HTML document is simply to insert the RDF in-line. This will make the resulting document non-conformant to HTML specifications up to and including HTML 4.0 but the RDF Working Group hopes that the HTML specification will evolve to support this. The discussion around the RDF requirements showed that possible solutions for RDF included putting all the information into attributes; putting it in an external file; and putting it at the end of the document. in general the participants thought that putting information into attributes was safer than putting it in an external file because of worries about security and forcing tools to be able to cope with multiple files. Since many tools already have to cope with multiple files, other participants thought this was not a drawback where security was not an issue. Some participants thought that putting the information in an external file would sometimes be a necessity, so tools would have to learn to cope. MathML has many requirements. One of these is a system that can cope with several small chunks of XML in one document, since a document may have many small equations. It has extreme formatting requirements, only some of which are shared by other objects. There was some discussion of MathML needs in terms of the DOM and formatting properties. The MathML has to be able to be passed as a chunk to an external renderer, and the XML has to be able to be formatted in a reasonable way. The MathML does not include HTML elements within it. That was discussed within the MathML WG, but rejected. The requirement that the content of MathML should not show up in down-level browsers was not as strong for MathML as for RDF, although some of the participants thought it would be best. The participants came to the conclusion that there was definite agreement on doing an XML block, where the contents of the block are well-formed XML, without any HTML semantics. There was much discussion about whether there was a reasonable method to include significant non-standard non-empty elements could be found, and whether there was a possibility of defining some sort of "good" HTML that people would use. Reasons for not allowing HTML semantics in the XML block, even on elements with the same element types as exist in HTML, included There was also some support for doing an XML version of HTML, where all the XML rules would apply. The discussion about whether it was possible to require that the contents of any non-standard elements be well-formed XML mostly came to the conclusion that it wasn't; or that it would be extremely expensive for those users simply wanting to add, e.g., a CHAPTER element to their pages. There was support for the notion that there is a difference between adding XML to pages (where the contents of the XML would be well-formed XML) and adding unknown elements in a standard way to HTML (where the contents of the unknown element would not follow XML well-formed rules.) Whether the HTML in an unknown HTML element needed to be "good" HTML wasn't fully clarified at the meeting. Another problem is that old browsers render PIs. During the discussion the following requirements were generally agreed upon. Agreement on terminology: XML blocks, significant non-standard HTML elements (sometimes also called sprinkles), and crud (or real-world HTML). But how do we distinguish between XML blocks and significant elements? An XML block contains XML -- not HTML. A significant element contains HTML -- not XML (unless it's empty, of course; we have to be able to distinguish between empty and non-empty). The question of how to "sprinkle" non-standard elements in an HTML document while retaining HTML semantics of all elements with HTML element and attribute types devoured most of the meeting. We did not come to a final conclusion on this subject. One proposed solution was to use new elements called CONTAINER and LEAF, with the CLASS attribute used to show the type. The drawback is that users can't define non-standard attributes. There was also much discussion as to whether users would accept this sort of solution, or whether they would want to invent their own element types. It was felt that this solution would allow users to keep on using "real" HTML (a.k.a crud) inside the wrapper elements. Another proposal was to allow users to define their own wrapper elements. If all elements within the block have end tags, even if they are EMPTY elements, then this could be the way to extensible HTML (not XML). There were several points against this, including the large number of non-standard EMPTY elements that already exist. Many participants thought that defining browser behaviour for this would be almost impossible, and that migrating HTML users to XML with the HTML tagset was a better solution. How to clean up HTML came up again and again in the discussions. The participants agreed that it is impossible in the general case to create valid HTML from an arbitrary page on the Web without human intervention. Users will not want to risk breaking documents which function. Current HTML has three components: the element type names, default rendering, and semantics (e.g. forms). There was a strong contingent that said users should wait for XML tools to become generally available and use those, rather than trying to add XML to HTML. The MathML group would like a mechanism to tell browsers a plain-text string to render, if the equation can't be rendered. This sort of mechanism would potentially be useful for other XML content with high rendering requirements as well. The biggest reason to come up with a standard method for adding XML (or unknown HTML) to HTML is to allow poeple to use styles and the DOM with these elements. Currently they can't. Browsers do not apply CSS styles to unknown elements, and unknown container elements are not exposed as containers in the MSIE object model. (The DOM WG decided not to tackle the problem, and only talks about valid HTML 4.0 documents, and XML as a separate entity.) A potential solution was to write HTML as XML, i.e. with MIME-type text/xml. Then all the XML rules would apply. One problem with this is that some browsers sniff the document irrespective of MIME-type and display the content if it looks like HTML according to some heuristic[InetSDK], Appendix A. This may include, for example, having a TITLE element anywhere within the first 200 bytes of the document. Thus document providers may have to add a comment long enough to get rid of the heuristics. The first option for using XML in HTML documents is to include it by reference, using <LINK>, <A>, <OBJECT> or perhaps even <IMG>. This markup conforms to existing W3C Recommendations. This gives predictable behaviour across the whole spectrum of HTML user agents, at the cost of managing and accessing the compound document. Another option with predictable behaviour is to use tags and attributes only, and avoid character data which will be displayed by deployed software. Strictly speaking, documents enhanced this way do not conform to the HTML 2, 3.2, or 4.0 specification, but each of those specifications included a note to implementors to ignore unknown attributes. The XML namespace facility[XML-Names] should be used to manage the risk of name collisions for new attributes and elements. Note that unfortunately, much of the deployed base of user agents will display XML namespace declarations as text. The linking and attributes mechanisms do not satisfy all of the requirements presented at the meeting. It was agreed that an enhancement to HTML to accomodate XML blocks is necessary. The definition of an XML block is a chunk of well-formed XML that is inside an HTML document. Any elements within the chunk that happen to have the same element types as HTML elements are not considered to be HTML elements. The error-handling as defined in the XML specification applies, i.e. the processor must halt on well-formedness errors. There were two proposals for this. (Other proposals that were discussed were discovered to be variations of these). Using a specific element type has the advantage that the meaning is clear, and that attribute can be added to the element for such things as MIME-type and a link to an external file containing the XML content. For the XML block case, the group decided on a vote of 10 for and 1 abstension (none against) to use an element called XML. This must be added to a future version of HTML. The attributes are TYPE for the MIME-type and SRC for the URL of the content if it is in an external file. The contents of the XML element are XML. There is an xml PI at the beginning of the XML block that contains all other information that the XML block needs. Interoperability with the 3.0 generation of browsers is required for successful deployment of RDF, among other applications. This means that the XML block is not a complete solution either. There are a number of ways in which content can be made to not show up in browsers that don't understand the element. Of these, putting the content in the HEAD is the most problematic because of the difficulties for HTML browsers of defining where the HEAD ends. Any of these methods would be considered to not break HTML or XML, and the participants decided that these should be written up (with the exception of putting content in the HEAD) as the recommended methods for coping with XML where the content should not show up in older browsers. There are, of course, times when none of these methods are suitable for some reason. The group therefore decided to also figure out which of the many unliked methods was the least undesirable. The choices were The proposal to put the XML content inside an OBJECT element was quickly rejected, as it would not work in Netscape Navigator 3.0. The problem with APPLET is that if the user has applet loading turned off, the content will show. The problem with SCRIPT is that it breaks the currently defined content model of SCRIPT. There were also worries about whether future XML users will use the SCRIPT element themselves, which would not be possible if it were a reserved element. This concern wasn't shared by the entire group. The problem with using comments is that comments are meant to not contain parsed data, and users couldn't put another comment inside the XML content. The vote (1 per company) was 1 for comments, 1 for APPLET, and 8 for SCRIPT. Details of the XML block and SCRIPT mechanisms are the subject of a Working Draft in progress. The discussion of using XML markup in HTML documents such that it would be "significant" to stylesheet and DOM implementations did not reach a clear consensus. We observed that XML can be modelled using the HTML 4.0 DIV, SPAN, and CLASS markup, which are significant to stylesheet and DOM implementations. Some experience with this style suggested the community would not embrace it, but the discussion was not conclusive. A proposal for a "sprinkles" mechanism is the subject of a Working Draft in progress.
http://www.w3.org/TR/NOTE-xh.html
CC-MAIN-2013-48
refinedweb
2,163
60.85
and the LDAP server should be encrypted using SSL/TLS. Clients and nodes that connect via SSL/TLS to the LDAP server need to have the LDAP server’s certificate or the server’s root CA certificate installed in their keystore or truststore. For more information about installing certificates, see Setting up SSL Between Elasticsearch and LDAP. LDAP stores users and groups hierarchically, similar to the way folders are grouped in a file system. An LD). The ldap realm supports two modes of operation, a user search mode and a mode with specific templates for user DNs. See with User Search: Add a realm configuration of type ldapto elasticsearch.ymlunder the xpack.security.authc.realmsnamespace. At a minimum, you must set the realm typeto ldap, specify the urlof the LDAP server, and set user_search.base_dnto the container DN where the users are searched for. a user search: xpack: security: authc: realms: ldap1: type: ldap order: 0 url: "ldaps://ldap.example.com:636" bind_dn: "cn=ldapuser, ou=users, o=services, dc=example, dc=com" bind_password: x-pack-test-password user_search: base_dn: "dc=example,dc=com" filter: "(cn={0})" group_search: base_dn: "dc=example,dc=com" files: role_mapping: "ES_PATH_CONF If your LDAP environment uses a few specific standard naming conditions for users, you can use User DN templates to configure the realm. The advantage of this method is that a search does not have to be performed to find the user DN. However, multiple bind operations might be needed to find the correct user DN. To configure an ldap Realm with User DN templates: Add a realm configuration of type ldapto elasticsearch.ymlin the xpack.security.authc.realmsnamespace. At a minimum, you must set the realm typeto ldap, specify the urlof the LDAP server, and specify at least one template with the user_dn_templatesoption. User DN templates: xpack: security: authc: realms: ldap1: type: ldap order: 0 url: "ldaps://ldap.example.com:636" user_dn_templates: - "cn={0}, ou=users, o=marketing, dc=example, dc=com" - "cn={0}, ou=users, o=engineering, dc=example, dc=com" group_search: base_dn: "dc=example,dc=com" files: role_mapping: "/mnt/elasticsearch/group_to_role_mapping.yml" unmapped_groups_as_roles: false -. An integral part of a realm authentication process is to resolve the roles associated with the authenticated user. Roles define the privileges a user has in the cluster. Since with the ldap realm the users are managed externally in the LDAP server, the expectation is that their roles are managed there as well. If fact, LDAP supports the notion of groups, which often represent user roles for different systems in the organization. The ldap realm enables you to map LDAP users to roles via their LDAP groups, or other metadata. This role mapping can be configured via the role-mapping API, or by using a file stored on each node. When a user authenticates with LDAP, the privileges for that user are the union of all privileges defined by the roles to which the user is mapped. Within a mapping definition, you specify groups using their distinguished names. For example, the following mapping configuration maps the LDAP admins=admins,dc=example,dc=com" For more information, see Mapping Users and Groups to Roles. When a user is authenticated via an LDAP realm, the following properties are populated in user’s metadata. This metadata is returned in the authenticate API, and can be used with templated queries in roles. Additional fields can be included in the user’s metadata by configuring the metadata setting on the LDAP realm. This metadata is available for use with the role mapping API or in templated role queries.: [ "ES_PATH_CONF certificate.
https://www.elastic.co/guide/en/x-pack/current/ldap-realm.html
CC-MAIN-2019-22
refinedweb
598
54.42
I have a question about a script i'm making. It asks the user to input an integer, then finds two prime numbers that sum up to the number, and displays what those two prime numbers are ( something like "54 = 5 + 49" ). I have most of the code working, but i'm not sure how to finish it up. So far, it finds the prime numbers that make up the number, but when it encounters a number that doesnt sum up to two prime numbers the program exits and goes back to the prompt with no message of any kind. Primarily, what i'd like to do is create a check to see if the number the user entered is even. IF the number is even, the program then finds the two prime numbers that sum to that number. If it is NOT even, the program should exit with a "Number not even" message or similar. Heres my code so far, can someone provide some input? def main(): import math def is_prime(p): prime = True if p%2 == 0: prime = False else: for i in range(3, math.ceil(math.sqrt(p/2)), 2): if p % i == 0: prime = False break return prime n = int(raw_input('Ener number to test: ')) for p in range(3, n/2, 2): if is_prime(p) and is_prime(n-p): print n, '= %d + %d' % (p, n-p) print "Found two prime numbers that sum to",n break main() Thanks!
https://www.daniweb.com/programming/software-development/threads/113981/need-help-with-this-script-please
CC-MAIN-2016-50
refinedweb
244
82.58
Name | Synopsis | Description | Return Values | Errors | Files | Usage | Attributes | See Also #include <stdlib.h> void closefrom(int lowfd); int fdwalk(int (*func)(void *, int), void *cd); The closefrom() function calls close(2) on all open file descriptors greater than or equal to lowfd. The effect of closefrom(lowfd) is the same as the code #include <sys/resource.h> struct rlimit rl; int i; getrlimit(RLIMIT_NOFILE, &rl); for (i = lowfd; i < rl.rlim_max;_max . The fdwalk() function can be used for fine-grained control over the closing of file descriptors. For example, the closefrom() function can be implemented as: static int close_func(void *lowfdp, int fd) { if (fd >= *(int *)lowfdp) (void) close(fd); return (0); } void closefrom(int lowfd) { (void) fdwalk(close_func, &lowfd); } The fdwalk() function can then be used to count the number of open files in the process.
http://docs.oracle.com/cd/E19082-01/819-2243/closefrom-3c/index.html
CC-MAIN-2014-35
refinedweb
139
59.13